Search This Blog

Thursday, March 28, 2019

Data Sets

 Weather



@relation weather

@attribute matchno numeric

@attribute humidity numeric

@attribute temperature numeric

@attribute weathercondition{sunny,cloudy}

@attribute occuranceofrain{y,n,maybe}

@attribute possibilityofmatch{y,n,maybe}

@data   

1,29,39,sunny,n,y

2,23,35,sunny,n,y

3,12,20,cloudy,y,n

4,22,25,cloudy,maybe,maybe

5,17,23,cloudy,y,n

6,30,45,sunny,n,y

7,15,24,cloudy,maybe,maybe

8,20,29,cloudy,maybe,maybe

9,30,35,sunny,n,y

10,29,35,sunny,n,y

11,29,24,sunny,n,y

12,26,30,sunny,n,y

13,22,24,cloudy,maybe,maybe

14,23,24,cloudy,maybe,maybe

15,30,38,sunny,n,y

16,29,30,sunny,n,y

17,19,21,cloudy,y,n

18,22,24,cloudy,n,y

19,28,30,sunny,n,y

20,31,37,sunny,n,y


 employee







@relation employee
@attribute eid numeric
@attribute ename string
@attribute age {20-29,>30,<22}
@attribute income{20000-30000,>30000,<40000}
@attribute buys{YES,NO}
@data
101,"A",20-29,20000-30000,YES
102,"B",<22,>30000,NO
103,"C",>30,<40000,NO
104,"D",20-29,20000-30000,YES
105,"E",20-29,>30000,NO
106,"F",<22,<40000,NO
107,"G",<22,>30000,NO
108,"H",>30,20000-30000,NO
109,"I",20-29,<40000,NO
110,"J",<22,<40000,NO
111,"K",20-29,20000-30000,NO
112,"L",<22,20000-30000,NO
113,"M",20-29,20000-30000,NO
114,"N",20-29,20000-30000,YES
115,"O",<22,<40000,NO
116,"P",20-29,20000-30000,YES
117,"Q",<22,<40000,NO
118,"R",>30,20000-30000,NO
119,"S",20-29,20000-30000,YES
120,"T",<22,<40000,NO








labour

@relation labour
@attribute lid numeric
@attribute lname string
@attribute age {30-39,45-50}
@attribute workinghours {6-8,8-10}
@attribute income {20000-30000,30000-40000}
@data
101001,"A",30-39,8-10,30000-40000
101002,"B",45-50,6-8,20000-30000
10103,"C",30-39,8-10,30000-40000
10104,"D",45-50,6-8,20000-30000
10105,"E",30-39,8-10,30000-40000
10106,"F",45-50,6-8,20000-30000
10107,"G",45-50,6-8,20000-30000
10108,"H",30-39,8-10,30000-40000
10109,"I",30-39,8-10,30000-40000
101010,"J",45-50,6-8,20000-30000
101011,"K",30-39,8-10,30000-40000
101012,"L",45-50,6-8,20000-30000
101013,"M",45-50,6-8,20000-30000
101014,"N",30-39,8-10,30000-40000
101015,"O",45-50,6-8,20000-30000
101016,"P",45-50,6-8,20000-30000
101017,"Q",30-39,8-10,30000-40000
101018,"R",45-50,6-8,20000-30000
101019,"S",45-50,6-8,20000-30000
101020,"T",30-39,8-10,30000-40000

 student


@relation student
@attribute sid numeric
@attribute name string
@attribute age numeric
@attribute branch {IT}
@attribute percentage {70-80,80-90,90-100}
@attribute grade {C,B,A}
@data
101,"A",19,IT,70-80,C
102,"B",19,IT,90-100,A
103,"C",20,IT,90-100,A
104,"D",18,IT,70-80,C
105,"E",19,IT,80-90,B
106,"F",20,IT,80-90,B
107,"G",20,IT,70-80,C
108,"H",20,IT,80-90,B
109,"I",19,IT,90-100,A
110,"J",18,IT,70-80,C
111,"K",18,IT,80-90,B
112,"L",20,IT,70-80,C
113,"M",19,IT,80-90,B
114,"N",19,IT,80-90,B
115,"O",20,IT,90-100,A
116,"P",20,IT,70-80,C
117,"Q",19,IT,90-100,A
118,"R",20,IT,80-90,B
119,"S",20,IT,90-100,A
120,"T",20,IT,70-80,C














Friday, March 22, 2019

Design LALR Bottom up Parser using YACC.

Design LALR Bottom up Parser.

<parser.l>
%{
#include<stdio.h> #include "y.tab.h"
%}
%%
[0-9]+ {yylval.dval=atof(yytext); return DIGIT;
}
\n|. return yytext[0];
%%
<parser.y>
%{
/*This YACC specification file generates the LALR parser for the program considered in experiment 4.*/
#include<stdio.h>
%}
%union
{
double dval;
}
%token <dval> DIGIT
%type <dval> expr
%type <dval> term
%type <dval> factor
%%
line: expr '\n' { printf("%g\n",$1);
}
;
expr: expr '+' term {$$=$1 + $3 ;}
| term
;
term: term '*' factor {$$=$1 * $3 ;}
| factor
;
factor: '(' expr ')' {$$=$2 ;}
| DIGIT
 
;
%%
int main()
{
yyparse();
}
yyerror(char *s)
{
printf("%s",s);
}
Output:
$lex parser.l
$yacc –d parser.y
$cc lex.yy.c y.tab.c –ll –lm
$./a.out 2+3
5.0000





click here to download

Implement the Lexical Analyzer Using Lex Tool.




/* program name is lexp.l */
%{
/* program to recognize a c program */ int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);} int |
float | char | double | while | for |
do | if |
break | continue | void | switch | case | long | struct | const | typedef | return | else |
goto {printf("\n\t%s is a KEYWORD",yytext);} "/*" {COMMENT = 1;}
/*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/

"*/" {COMMENT = 0;}
/* printf("\n\n\t%s is a COMMENT\n",yytext);}*/
{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}
\} {if(!COMMENT) printf("\n BLOCK ENDS");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);}
\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc,char **argv)
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1],"r"); if(!file)
{
printf("could not open %s \n",argv[1]); exit(0);
}
yyin = file;
}
yylex(); printf("\n\n"); return 0;
} int yywrap()
{
return 0;
}

Input:
$vi var.c #include<stdio.h> main()
{
int a,b;
}

Output:
$lex lex.l
$cc lex.yy.c
$./a.out var.c
#include<stdio.h> is a PREPROCESSOR DIRECTIVE FUNCTION
main (
)
BLOCK BEGINS
int is a KEYWORD a IDENTIFIER
b IDENTIFIER BLOCK ENDS

Saturday, March 16, 2019

sample lex

/*lex program to count number of words*/
%{
#include<stdio.h>
#include<string.h>
int i = 0;
%}

/* Rules Section*/
%%
([a-zA-Z0-9])* {i++;} /* Rule for counting
number of words*/

"\n" {printf("%d\n", i); i = 0;}
%%

int yywrap(void){}

int main()
{
// The function that starts the analysis
yylex();

return 0;
}

Monday, February 18, 2019

Problem Design




1.      Indian government had decided that all information related to the airport should be organized using automation, and you have been hired to design the system. For this the relevant information is as follows:
ü  Every airplane has a registration number, and each airplane is of a specific model.
ü  The airport accommodates a number of airplanes models, and each model is identified by a model number and has a capacity and a weight.
ü  The number of technicians works at the airport. You need to store the name, SSN, address, phone number and a salary of each technician.
ü  Each technician is an expert on one or more plane model(s), and his or her expertise may overlap with that of other technicians. This information about technicians must also be recorded.
ü  Traffic controllers must have an annual medical examination. For each traffic controller, you must store the date of the most recent exam.
ü  All airport employees belong to a union. You must store the union membership number of each employee. You can assume that each employee is uniquely identified by a social security number.
ü  The airport has a number of tests that are used periodically to ensure that airplanes are still airworthy. Each test has a Indian Aviation Administration (IAA) test number, a name, and a maximum possible score.
ü  The IAA requires the airport to keep track of each time a given airplane is tested by a given technician using a given test. Foe each testing event the information needed is the date, the number of hours the technicians spent doing the test, and the score the airplane received on the test.
2. You are appointed to design International movie data base system. The system stores and manipulates information about movies, casts (actors or actresses), crews, studios, awards, cinemas, news, etc. The following gives the rDesign the problemequirements for the IMDB.
ü  IMDB records the information about each studio, such as studio name, year established, year closed (if applicable), country, etc The system records overall movie information, such as movie title, tagline, genre, year made, country, website, running time, language, colour, rating, showing start date, ranking, etc.
ü  Tagline is a one-sentence description of a movie. Values of colour could be “True” or “False” for colour movie or black/white movie respectively. And Rating could be “G”, “PG”, “M”, “MA”, etc. Studios produce movies.
ü  The genre describes the type of a movie, such as “comedy”, “drama”, “biography”, “action”, “thriller”, “horror”, “romance”, “war”, “animation”, “adventure”, etc. One movie may have more than one genre.You may record the people involved with the movies with their titles, family names, given names, genders, websites, emails, dates of birth, cities of birth, countries of birth, and other necessary information.
ü  A casts is actor or actress in a movie. Crews are staff other than casts involved with a movie, such as “Director”.  You should record each role’s name for casts. For example, “Actor of leading role”, “Actor of supporting role”, etc.
ü  You should record each job title for crews. For example, “Director”, “Producer”, “Writer”, etc. You may assume a person only performs one role in a movie. IMDB records the name of each part in a movie, also records the job title for each crew in a movie. There are many movie awards around the world from different organization. The organization is recorded with name and country.  Each organization holds one award ceremony in each year.
ü  You should record the award and nominations with title, category, etc. Award titles could be classified as to two categories: for person (such as “Best Actor of leading role”, “Best Director”) or for movie “Best movie”, etc. There will be many nominations for an award in a given year, but only one winner for the award in that year. An award may been won many times, or may have never been awarded (or nominated)

Monday, January 28, 2019


1. What is the output of this C code?



#include <stdio.h>

    void main()

    {

        int x = 4, y, z;

        y = --x;

        z = x--;

        printf("%d%d%d", x,  y, z);

    }



Ans : 2  3  3







2.What is the output of this C code?





 #include <stdio.h>

    int main()

    {

        switch (printf("Do"))

        {

        case 1:

            printf("First\n");

            break;

        case 2:

            printf("Second\n");

            break;                                                     

        default:

            printf("Default\n");

            break;

        }

    }



/Ans: DoSecond





3.What is the output of this C code?



#include <stdio.h>

    int main()

    {

        int a = 10, b = 10;

        if (a = 5)

        b--;

        printf("%d, %d", a, b--);

    }



Ans: a=5  b=9





4.What is the output of this C code?

#include <stdio.h>

    int main()

    {

        int a = 1, b = 1, c;

        c = a++ + b;

        printf("%d, %d", a, b);

    }




Ans: a=2  b=1







5.#include "stdio.h"

int main()

{

 int _ = 18;

 int __ = 38;

 int ___;

 ___ = _ + __;

 printf ("%i", ___);

 return 0;

}



Answer : 56





6.What will be printed as the result of the operation below:main()

{

 int x = 41, y = 43;

 x = y++ + x++;

 y = ++y + ++x;

 printf ("%d %d", x , y);

}

Answer : 86 130

Description : Its actually compiler dependent. After x = y++ + x++, the value of x becomes 85 and y becomes 44, And y = ++y + ++x will be computed as y = (44) + (86). After computation y becomes 130.





7.What will be printed as the result of the operation main()

{

 int x = 7;

 printf ("%d, %d, %d", x,

    x<<5, x>>5);

}





Answer : 7, 224, 0

Description : As x = 7 so first %d gives 7, second %d will take value of x after left shifting it five times, and shifting is done after converting the values to binary, binary value of 7 (000111) will be left shifted twice to make it binary 224(11100000), so x<<5 is 224 and as left shifting does not effect the original value of x its still 5 so third %d will also show 0.









8.What will be the output?



main()



{

if (1, 0)

 printf ("True");

else

 printf ("False");

}



Answer : False

Description :comma(,) operator returns the value which at the right hand side of , and thus if statement become if(0).







9.what is the output ?



#include<stdio.h>

int main()

{

 char arr[5] = "World is beautiful";

 printf ("%s", arr);

 return 0;

}



Answer : World

A warning is also printed “4:19: warning: initializer-string for array of chars is too long [enabled by default]”

Description : Size of any character array cannot be less than the number of characters in any string which it has assigned. Size of an array can be equal (excluding null character) or greater than but never less than.







10.What is the output of following program?



#include<stdio.h>

void main()

{

 int a = 2;

 switch (a)

 {

  case 4: printf ("A");

  break;

  case 3: printf ("B");

  default : printf("C");

  case 1 : printf ("D");

  break;

  case 5 : printf ("E");

 }

}





Answer : CD

Description : In switch statement default should be at mentioned after all the switch cases. In this case, it gets executed in between and all cases after default are executed before a break statement.





11.What is the output?#include<stdio.h>

#define SQR( x ) ( x * x )

int main()

{

 int b = 5;

 int a = SQR(b+2);

 printf("%d\n", a);

 return 0;

}

Answer : 17









12.#include <stdio.h>



int main()

{

int arr[] = {};

printf("%d", sizeof(arr));

return 0;

}







13.Which one of the following is incorrect?

A. enum fruits = { apple, banana }f;

B. enum fruits{ apple, banana }f ;

C. enum fruits{ apple, banana };

D. enum f{ apple, banana };





14.What will be the output of the C program?



#include<stdio.h>

int main(){

 float me = 5.25;

 double you = 5.25;

 if(me == you)

  printf("I love U");

 else

  printf("I hate U");

 return 0;

}

A. Compilation error



B. I love U

C. Runtime error

D. I hate U



Option: D

Explanation

For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.



15.

DATA MINING

In the University Examinations conducted during the past 5 years, the toppers registration numbers were  7126, 82417914, 7687 and 6657. Your father is an expert in data mining and he could easily infer a pattern in the toppers registration numbers. In all the registration numbers listed here, the sum of the odd digits is equal to the sum of the even digits in the number. He termed the numbers that satisfy this property as Probable Topper Numbers.

Write a program to find whether a given number is a probable topper number or not.




Tuesday, December 11, 2018

string belongs to the given grammar or not

C Program for implementation of  language given below
E-> TE’
 E’-> +TE’ | epsilon
T-> FT’
T’-> *FT’  | epsilon
 F-> (E) | i







#include<stdio.h> #include<conio.h> #include<string.h> #include<process.h> void e(); void e1(); void t(); void t1(); void f(); int ip=0; static char s[10]; void main() { char k; int i; ip=0; clrscr(); printf("enter the string:\n "); scanf("%s",s); printf("the string is : %s\n",s); e(); if(s[ip]=='$') printf("String is accepted "); getch(); } void e() { t(); e1(); return; } void t() { f(); t1(); // return; } void e1() { if(s[ip]=='+') { ip++; t(); e1(); } return; } void t1() { if(s[ip]=='*') { ip++; f(); t1(); } return; } void f() { if(s[ip]=='(') { ip++; e(); if(s[ip]==')') ip++; else printf("error closed paranthesis expected"); } else if(s[ip]=='i') ip++; else printf("id expected "); return; }

Thursday, December 6, 2018

Identifying the given number is valid number or not


#include <stdio.h>
#include<string.h>
int main()
{
    char a[500];
    int i,l,c=1,k=0;
    scanf("%s",a);
    l=strlen(a);
    if(a[0]=='+'||a[0]=='-'||(a[0]>='0'&&a[0]<='9'))
    {
        for(i=1;i<l;i++)
        {
            if(a[i]=='.')
            {
             k++;
             if(k>1)
             {
             printf("invalid");
             return 0;
             }
            }
            else if((a[i]>='0'&&a[i]<='9'))
            c++;
            else
            break;
        }
    if(c==l-1)
    printf("valid");
    else
    printf("invalid");
    }
    else
    printf("invalid");
    return 0;
}

Wednesday, November 14, 2018

problem 10

Crop cultivation strategy 
 
If a crop is grown for once, the fertility of the soil reduces by 30. After cultivation, if the land is left free for one month, the fertility increases by a factor of 2. If the fertility becomes 0, the crop cannot be grown futher. Write a program to get the initial fertility and get the number of months the land is left free after every cultivation and find the number of times the crops are successfully grown, before the fertility becomes 0. 
  
Note 1: If the fertility becomes 0 in the middle of the growth of crop, the crop stops growing. 
Note 2: Stop getting the input if the fertility becomes 0. 

Input Format: 
First input is an integer that corresponds to the initial fertility of the soil. 
Next inputs are number of months the land is left free after every cultivation. 
Output Format: 
Number of times the crops are grown successfully. 
  
Sample Input: 
35 


Sample Output: 

  
  
Explanation
35->after first cultivation fertility become 5 
3-> after 3 months the fertility becomes 40( 5*2 = 10, 10*2 = 20, 20*2 = 40); After second cultivation the fertility becomes 10 
1-> after 1 month the fertility becomes 20; In the middle of the crop growth the fertility becomes 0, so stop. 
So the total number of successful cultivations = 2.

problem 9

Plants under shade

There are certain plants that needs to be grown under the shade of huge trees and the dead leaves from the trees become the natural manure for the plants. So willow trees are planted throughout the village at certain positions.

The position(distance from the first tree) follows the following series 
0 6 10 17 22 30 36.... 

Input format: 
Input is an integer which corresponds to number of willow trees, n. 

Output format: 
Output is the series that contains 'n' numbers. 

Sample Input 1: 

Sample Output 1: 
0 6 10 17 22 30 36 

Sample Input 2: 

Sample Output 2: 
0 6 10 17 22

problem 8

Planting Crop
A farmer who wants to follow the companion planting method for crops, it would better when they are implementing in gardening and agriculture is the planting of different crops in proximity for pest control, pollination, providing habitat for beneficial creatures, maximizing use of space, and to otherwise increase crop productivity. Companion planting is a form of polyculture.

In the Companion planting method, the crops are planted in the following pattern. 
For n = 5, the pattern should be as follows, 
XXXXXXXXX 
XX - XXX -XX 
X - X - X -X -X 
XX -XXX - XX 
XXXXXXXXX 
XX - XXX- XX 
X- X- X - X - X 
XX - XXX -XX 
XXXXXXXXX 

Hint: Number of rows = 2*n - 1 

Write a program to print the pattern for the given ‘n’ value. 

Input format:
Input is an integer which corresponds to the n.

Output format:
Refer the sample output.

Sample Intput 1:
5
Sample Output 1:
XXXXXXXXX
XX - XXX -XX
X - X - X -X -X
XX -XXX - XX
XXXXXXXXX
XX - XXX- XX
X- X- X - X - X
XX - XXX -XX
XXXXXXXXX

Sample Input 2:
9
Sample Output 2:
XXXXXXXXXXXXXXXXX
XX-----XXX-----XX
X-X---X-X-X---X-X
X--X-X--X--X-X--X
X---X---X---X---X
X--X-X--X--X-X--X
X-X---X-X-X---X-X
XX-----XXX-----XX
XXXXXXXXXXXXXXXXX
XX-----XXX-----XX
X-X---X-X-X---X-X
X--X-X--X--X-X--X
X---X---X---X---X
X--X-X--X--X-X--X
X-X---X-X-X---X-X
XX-----XXX-----XX
XXXXXXXXXXXXXXXXX

problem 7

Fencing the ground

Two non-overlapping fields need to be fenced together to guard from cattle. The fence is always a single rectangle, which cover the two fields exactly.

Given the left bottom coordinate, length and width of the two fields, write a program to find dimension of the fence. Print “Invalid Input” if the fields overlap. 
  
Input Format:
The 1st line of the input consists of 4 integers separated by a space that correspond to x, y, l and w of the first rectangle.
The 2nd line of the input consists of 4 integers separated by a space that correspond to x, y, l and w of the second rectangle.
Output Format:
Output consists of 4 integers that correspond to x, y, l and w of the Union rectangle.

Sample Input 1: 
0 2 4 3 
4 0 2 8 
Sample Output 1: 
0 0 6 8 
  
Sample Input 2: 
0 2 4 3 
3 0 2 8 
Sample Output 2: 
Invalid Input

problem 6

Area Split

Pandu, the farmer, has three sons named, Bhima, Arjuna and Nakula. He has also planed for Three field crop rotation and hand over each field to his three sons.


His sons are fond of even numbers. So they wanted to split the field only if he is able to split it into 3 even number(wrt area) fields. Pandu was so particular that the difference in area of the fields should be minimum because he equally like his three sons. He would split the field only if it is possible, else he would do the normal farming. 
Note that it is possible to split only if all three land have positive area. 
Write a program to help Pandu in spliting the land. 
Input Format:
The first (and the only) input line contains integer that corresponds to the area of the field.
Note: Assume input are positive.

Output Format:
In the first line of the output, print "Yes", if the field can be divided into three parts as per the requirements of Pandu, else print "No".
 
If the first line of the output is "Yes", the next line of the output consists of 3 integers separated by a space, which corresponds to the areas of the divided field. In case of distinct integers, the smallest number should appear first. 

Sample Input 1: 

Sample Output 1: 
Yes 
2 2 2 
  
Sample Input 2: 

Sample Output 2: 
No

problem 5

Project predictor
In the three-field system the sequence of field use involved an autumn planting of grain (wheat, barley or rye) and a spring planting of peas, beans, oats or barley. The third was left fallow, in order to allow the soil of that field to regain its nutrients.

The 3 durations(4 months each) are, 
Duration 1: 1-4 (all inclusive) 
Duration 2: 5-8 (all inclusive) 
Duration 3: 9-12 (all inclusive) 

The 2 crops that were used are,  
Crop 1: Winter Wheat 
Crop 2: Beans 

The initial crops in three fields at month 1are, 
Field 1: Winter Wheat 
Field 2: Beans 
Field 3: Left Fallow 

Given the month number and field number, write a program to print the crop name. 

Input Format: 
The first input is an integer corresponds to month number. 
The second input is an integer corresponds to field number. 

Output Format: 
The output is the string. 

Sample Input 1: 
Sample Output 1: 
Winter Wheat 
  
Sample Input 2: 
Sample Output 2: 
Left Fallow 
  
Sample Input 3: 
Sample Output 3: 
Beans

problem 4

Tillage

Reduced tillage or conservation tillage is a practice of minimising soil disturbance and allowing crop residue or stubble to remain on the ground instead of being thrown away or incorporated into the soil. 30 % of the residue becomes natural manure.

Given the total weight of the residue and the total amount of manure needed for the next crop, write a program to determine the amount of manure needed extra. 


Input Format: 
The first line of the input is an integer that corresponds to the total weight of the residue. 
The second line of the input is an integer that corresponds to the total amount of manure needed. 
 
Output Format: 
An output is a float value that corresponds to the amount of manure needed extra, rounded off to 2 decimal places. 

Sample Input:
100
100
Sample Output:
70.00

problem 3

Demand for organic food

The demand for organic food is growing so fast that consumer demand is outstripping some domestic supplies. 


The demand for organic food increases every year by 8.9%. 
Write a program to find the increase in revenue after 3 years. Given the revenue in the first year is ‘x’ crores. 

Input Format: 
The first line of the input is an integer that corresponds to the ‘x’ value. 

Output Format: 
Output is a float value that corresponds to the revenue after 3 years, rounded off to 2 decimal places. 

Sample Input: 

Sample Output: 
5.17

problem - 2

Crop Rotation
Crop rotation is the practice of growing a series of dissimilar or different types of crops in the same area in sequenced seasons. It is done so that the soil of farms is not used for only one set of nutrients. It helps in reducing soil erosion and increases soil fertility and crop yield. 

In crop rotation technique, there are four strategies. Out of those, 
          1) Two field system 
          2) Three field system 
are popularly followed.       

Two Field System:
Under a two-field rotation, half the land was planted in a year, while the other half lay fallow. Then, in the next year, the two fields were reversed.



Three-field system: 
Dividing available lands into three parts. One section was planted in the autumn with rye or winter wheat, followed by spring oats or barley; the second section grew crops such as peas, lentils, or beans; and the third field was left fallow. The three fields were rotated in this manner so that every three years, a field would rest and be fallow. 



Write a program to find the productivity area for two field system and three field system. 

Input Format: 
Input is an integer that corresponds to the area of the farm. 

Output Format: 
The first line of the output is a float value that corresponds to the production area in two field system. 
The second line of the output is a float value that corresponds to the production area in three field system. 

Note: Format the output with 2 decimal points. 
  
Sample Input: 
600 
Sample Output: 
300.00 
400.00

problem -1

Plantation
A certain crop grown in a sunny and hot climate needs more water per day than the same crop grown in a cloudy and cooler climate. There are, however, apart from sunshine and temperature, other climatic factors which influence the crop water need. These factors are humidity and wind speed. When it is dry, the crop water needs are higher than when it is humid. In windy climates, the crops will use more water than in calm climates.
The highest crop water needs are thus found in areas which are hot, dry, windy and sunny. The lowest values are found when it is cool, humid and cloudy with little or no wind. 

Given 3 crops along with the range of the amount of water required and the temperature range.
Crop 1: Rice – 5 to 10 cm , 20 to 27 degree celcius, all  inclusive.
Crop 2: Wheat – 12 to 15 cm, 21 to 24 degree celcius, all inclusive.
Crop 3: Cotton – 6 to 13 am, 18 to 30 degree celcius, all inclusive.
  Note: Follow the above crops order.

Determine what all crops can be planted, given the rainfall and temperature. 

Input format: 
The first input is an integer which corresponds to the water required. 
The second input is an integer which corresponds to the temperature. 

Output format: 
Output is a string or a list of strings. 
If there are multiple strings in the output, the order to be followed is Rice, Wheat, Cotton. 

Sample Input 1: 
6 
20 
Sample Output 1: 
Rice 
Cotton 

Sample Input 2: 
15 
21 
Sample Output 2: 
Wheat





Wednesday, October 17, 2018

Service Demo Working code



MainActivity.java



import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
//String msg="android:";    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Log.d(msg, "The onCreate() event");    }

    public void startService(View view) {
        startService(new Intent(getBaseContext(), Myservice.class));
    }

    // Method to stop the service    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), Myservice.class));
    }

}

Myservice.java

public class Myservice extends Service {
    @Nullable    @Override    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override    public int onStartCommand(Intent intent, int flags, int startId) {
        // Let it continue running until it is stopped.        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        return START_STICKY;
    }

    @Override    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

Manifest.xml code ( adding service tag components )
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.admin.servicedemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".Myservice" />

        <activity android:name=".abc"></activity>
    </application>

</manifest>







 Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/button2"
        android:layout_centerVertical="true"
        android:onClick="stopService"
        android:text="stop service"
        tools:layout_editor_absoluteX="96dp"
        tools:layout_editor_absoluteY="130dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="111dp"
        android:layout_marginTop="104dp"
        android:onClick="startService"
        android:text="start service"
        tools:layout_editor_absoluteX="61dp"
        tools:layout_editor_absoluteY="293dp" />
</RelativeLayout






Tuesday, October 9, 2018

Current Location Finding

package com.example.lenovo.mapsdemo;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

   
private GoogleMap mMap;
    LocationManager
locationManager;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_maps);
       
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
       
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.
map);
        mapFragment.getMapAsync(
this);
       
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
       
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
           
// TODO: Consider calling
           
//    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
           
return;
        }

       
if(locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER))
        {
           
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
               
@Override
               
public void onLocationChanged(Location location) {
                   
double lat=location.getLatitude();
                   
double longitud=location.getLongitude();
                    LatLng latLng=
new LatLng(lat,longitud);

                    Geocoder geocoder=
new Geocoder(getApplicationContext());
                   
try {
                        List<Address> addressList=geocoder.getFromLocation(lat,longitud,
1);
                        String st=addressList.get(
0).getLocality();
                        st+=addressList.get(
0).getCountryName();
                       
mMap.addMarker(new MarkerOptions().position(latLng).title(st));
                        
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,20.6f));

                    }
catch (IOException e) {
                        e.printStackTrace();
                    }


                }

               
@Override
                
public void onStatusChanged(String provider, int status, Bundle extras) {

                }

               
@Override
               
public void onProviderEnabled(String provider) {

                }

               
@Override
               
public void onProviderDisabled(String provider) {

                }            });
        }
       
else if(locationManager.isProviderEnabled(locationManager.GPS_PROVIDER))
        {
           
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
               
@Override
               
public void onLocationChanged(Location location) {
                   
double lat=location.getLatitude();
                   
double longitud=location.getLongitude();
                    LatLng latLng=
new LatLng(lat,longitud);
                    Geocoder geocoder=
new Geocoder(getApplicationContext());
                   
try {
                        List<Address> addressList=geocoder.getFromLocation(lat,longitud,
1);
                        String st=addressList.get(
0).getLocality();
                        st+=addressList.get(
0).getCountryName();
                       
mMap.addMarker(new MarkerOptions().position(latLng).title(st));
                       
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,20.6f));
                    }
catch (IOException e) {
                        e.printStackTrace();
                    }
                }
               
@Override
               
public void onStatusChanged(String provider, int status, Bundle extras) {
                }
               
@Override
               
public void onProviderEnabled(String provider) {
                }
               
@Override
               
public void onProviderDisabled(String provider) {

                }
            });
        }
    }
   
/**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
   
@Override
   
public void onMapReady(GoogleMap googleMap) {
       
mMap = googleMap;

       
// Add a marker in Sydney and move the camera
       // LatLng sydney = new LatLng(-34, 151);
       // mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
       // mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,20.6f));
   
}
}

OBJECT ORIENTED PROGRAMMING THROUGH JAVA google classroom link

Classroom link: https://classroom.google.com/c/ODc0OTQxMjY1MjA5?cjc=rq67ikqo class code:  rq67ikqo exam link: https://wayground.com/join?gc=...