Monday 9 April 2018

Loop Structure in java

Loops :

A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages.

 

1. While loop :- Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

 

Syntax :

 

while (boolean condition)

{

// loop statement.....

}

 

 

Example :

 

Class Technogeeks

{

public static void main(String arg[])

{

int x=1;

while (x<=4)

{

System.out.println("Value of x is" +x);

x++;

}

}

}

 

2. do While loop :- Like a while statement, except that it tests the condition at the end of the loop body.

 

Syntax :

 

do

{

   // Ststements......

}

while (condition);

 

 

Example :

 

class Technogeeks

{

public static void main(String args[])

{

int x = 21;

do

{

System.out.println("Value of x is" +x);

x++;

}

while (x<20);

}

}

 

3. For loop :- Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

 

Syntax :

 

for(initialization condition; texting condition ; increment/decrement)

{

//Statements

}

 

Example :

 

Class Technogeeks

{

public static void main (String args[])

{

for(int x=2; x<=4; x++)

System.out.println("Value of x is " +x);

}

}

 

 

Infinite Loop

 

Example :

 

public class Technogeeks

{

public static void main(String[] args)

{

for(int i=5; i!=0; i -=2)

{

System.out.println(i);

}

int x=5;

While(x==5)

{

System.out.println("In the loop");

}

}

Switch Statement

 We will explain a Switch statement is —

The syntax of switch case is : 

Syntax:-
switch()
{
case1:
statement()
break;
case2:
statement()
break;
default:
statement()
break;
}


Example:-
public class MyClass
{
public static void main(string[] arg)
{
int score=90;
switch(score)
{
Case 90:
System.out println(“Very good”);
break;
Case 60:
System.out println(“Good”);
break;
Case 40:
System.out println(“OK”);
break;
default:
System.out println(“The grade is not valid”);
}
}
}

Logical Operator

In logical operator there are two operator

"&&" This is called as AND operator.
 "||" This is called as OR operator.

Example:-
public Class MyClass
{
public static void main(string[] arg)
{
int sub1=50;
int sub2=30;
if((sub1>=35)&&(sub2>=25))||((sub1<=60)&&(sub2<=40))
{
System.out.println(“The condition is true”);
}
else
{
System.out.println(“The condition is false”);
}
}
}

Here, perform a Logical operator.

Conditional Operator ( if-else Statement)

Condition: if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.

   If Statement

 

Syntax :

   If(condition)

{

//Statement     OR     code to be executed

}

 

Example :

 

Public class ifExample

{

Public static void main(String[] args)

{

Int age =20;

If(age>18)

{

System.out.println(“Age is greater than 18”);

}

}

}

 

2.    If-else Statement

 

Syntax :

If(condition)

{

//code if condition is true

}

Else

{

// code if condition is false

}

 

               Example :

Public classs ifElseExample

{

Public static void main(String [] args)

{

Int number = 13;

If(number%2==0)

{

System.out.println(“even number”);

}

Else

{

System.out.println(“odd number”);

}

}

}

 Leap Year

A year is leap, if it is divisible by 4 and 400. But, not by 100.

Public class leapyear

{

Public static void main(String[] args)

{

Int year =2020;

If(year%4==0) && (year%100!=0) || (year% 400==0)

{

System.out.println(“LEAP YEAR”);

}

Else

{

System.out.println(“COMMON YEAR”);

}

}

}

 

3.    If-else-if   : The if-else-if ladder statement executes one condition from multiple statements.

Syntax :

If(condition)

{

//code to be executed if condition1 is true

}

Else if(condition)

{

//code to be executed if condition2 is true

}

Else

{

//code to executed if all condition are false

}

Example :

Public class ifelseifexample{

Public static void main(String[] args){

Int marks =65;

If(marks<50){

System.out.println(“Fail”);

}

Elseif(marks>=60 && marks<70){

System.out.println(“D grade”)

}

Elseif(marks>=70 && marks<80){

System.out.println(“B grade”);

} Elseif(marks>=80 && marks<90){

System.out.println(“c grade”);

}else{

System.out.println(“Invaild”);

}

}

}

 

WRP to check positive, negative and zero?

 

Public class positivenegative

{

Public static void main(String[] args)

{

Int number = -15;

If(number>0)

{

System.out.println(“POSITIVE”);

}

Elseif(number<0)

{

System.out.println(“NEGATIVE”);

}

Else{

System.out.println(“ZERO”);

}

}

}

 

4.    Nested if Statement

Syntax :

If(condition){

//code to executed

}

If(condition){

//code to be excuted

}

Example :

 

Publiuc class nestedif{

Public static void main(Strings[] args)

{

Int age=20;

Int weight=80;

If(age>=18){

If(weight>50)

{

System.out.println(“Your are eligible to donate blood”);

}

}

}

}

Assignment operator (Post increment and Pre increment)

Post increment

int x=10;
x=x+1;
System.out.println(“x”);
 ————————————->>>>Output     :-11

int x=10;
x++;                          //increment by one.
System.out.println(“x”);
—————————————->>>>Output   :-11

int x=10;
System.out.println(“x++”);     //Here,first print the x value then, increment by one.
—————————————–>>>> Output :-10

  • Pre increment
int x=10;
System.out.println(“++x”);   //Here,first increment the value of  x then print x.
———————————>>>Output :-  11

int x=10;
++x;                          //First increment by one the Print the value.
System.out.println(“x”);
—————————————->>>>Output   :-  11

Finally, In this slide we show a assignment operator.

Take a input by user

Take the input from user

Syntax:-
Scanner scan=new Scanner(System.in);

Example:-

*/ Package lesson1;
import java until.scanner;
public class Myclass
{
public static void main(string[] arg);
{
Scanner scan=new Scanner(System.in);
System.out.println(“Enter the some number”);
int user-input-number=scan.nextInt();
System.out.println(“The enter value is-“);
System.out.println(“user-input-number”);
}
}
*/

Math arithmetic operator


Here, the math operator is:-
 
  " + "   (Addition)
  " – "   (Subtraction)

  " * "  (Multiplication)
  " / " (Division)

  " %"  (Modulus)

Example:-
public class math;
{
public static void main(string[]  arg)
{
int x,y,answer;
x=60;
y=30;
answer=x+y;   //(perform add operation)
answer=x-y;    //(perform sub operation)
answer=x*y;   //(perform mul operation)
answer=x/y;    //(perform div operation)
answer=x%y;  //(perform mod operation)

System.out.println(“Answer of addition =”+ answer);
}
}

Variable Declare in Java


  • Declare datatype.
  1. byte (number,1 bytes)
  2. short (number,2 bytes)
  3. int (number,4 bytes)
  4. long (number,8 bytes)
  5. float(float number,4 bytes)
  6. double (float number,8 bytes)
  7. char (a character , 2 bytes)
  8. Boolean (true or false , 1 bytes)
  9. Declare (Example)
  10. short my-variable=10;
  11. float my-decimal=(float) 4.5;
  12. double my-double=11.56;
  13. char my-char=’A’;

Introduction of Java

  • Java is develop by James Gosling in 1991
  • Java is a developed in the early 90s in Sun Microsystems company. Java first version release in 1995 (Java 1.0).
  • Java first name is Oak.
  • It is a high -level language.
  • Java is object oriented programing.
  • Java is run on-Java virtual Machine.

    How to run a Java program?

Java Program is run on Jdk (Java develop Kit) Software.
First of all we will install a jdk Software,then next install a eclipse Software.
Java is run on jvm (Java virtual machine).
In below figure we  will show a how to Execute a one simple program. 

Java is a simple and secure language.



Next slide we will explain , how to write a simple java program.

How to use a simple java program


  • In java programing, first create Package .
       package lesson1;                                              //create package
       public class MyClass;                                    // Class is a user-defined function,and class is a key word.
       {
       public static void main(string[] ,arg)             //main function is starting of program.
         {
       System.out.println(“Hello Friends”);              //This function is print the output on output screen.
       }
       }

Pointer and Function

The pointers are very much used in a function. Sometimes only with a pointer a complex function can be easily represented and success. The usage of the pointers in a function defintion may be classified into two groups.
1. Call by Value.
2. Call by reference

Call by Value 
  We have seen that a function in invoked there will be a link established between the formal and actual parameters. A temporary storage is created where the value of actual parameters is stored.

The formal parameters picks up its value from storage area the mechanism of data transfer between actual parameters mechanism of data transfer is referred as call by value.

The corresponding formal parameters represents a local variable in the called function.


This will not change the value of actual parameters.

#include<stdio.h>
void main( )
{
int x,y;
x=20;
y=30;
printf("\n Value of a and b before function call = %d%d",a,b);
fucn(x,y);
printf("\n Value of a and b after function call = %d%d",a,b);
}
fucn(p,q)
int p,q;
{
p=p+q;
q=q+q;
}

Call by Reference
 When we pass address to a function the parameters  receiving the address  should be pointers. The process of calling a function by using pointers to pass the address of the variable is known as call by reference . The function which is called by reference can change the value of the variable used in the call.

/* Example of call by reference */

#include<stdio.h>
void main( )

int x, y;
x=20;
y=30;
printf("\n Value of a and b before function call = %d%d",a,b);
fucn(&x,&y);
printf("\n Value of a and b after function call = %d%d", a,b);
}
fucn(p,q)
int p,q;
{
*p=*p + *p;
*q=*q + *q;
}

Function

A function is a self contained block of statement that performs a coherent task of some kind.

Functions provides modularity to the software.

#include<stdio.h>
int add (int x, int y)
int z;
z = x + y;
return (z);
}
main( )
{
int i,j,k;
i = 10;
j = 20;
k = add(i,j)        /* function call */
printf("The value of k is %d\n",k);
}

Output:-
  The value of k is 30.
 

Pointer

In C language a pointer is a variable that points to or references a memory location in which data is stored. Each memory cell in the computer has an address that can be used to access that location so a pointer variable points to a memory location we can access and change the contents of this memory location via the pointer.

Pointer Declaration :
  A pointer is a variable that contains the memory location of another variable. The syntax is as shown below. You start by specifying the type of data stored in the location identified by the pointer. The asterisk (*) tells the compiler that you are type * variable name

Example :
 int *ptr;
float *string;

Address Operator :
  Once we declare a pointer variable we must point it to something we can do this by assigning to the pointer the address the address of the variable you want to point as in the following example :
ptr=&num;
   This places the address where num is stores into the variable ptr. If num is stored in memory 21260 address then the variable ptr has the value 21260.

Memory Space of int Pointer and long double pointer
  
Size of any type of pointer is independent of the data type which it is pointing i.e. size of pointer is always fixed. Size of any type (near) of pointer in C is two byte.

For example :
 #include<stdio.h>
 void main( )
{
int *p1;
long double *p2;
printf("%d %d", sizeof (p1) , sizeof (p2) );
}

Output :   2     2

Since both pointers int and long double are pointing to only first byte of int data and long double data respectively.
   
Hence both int pointer and long double pointer stores only address in 16 bits. Thus both of the them will occupy exactly equal memory spaces.

The size of void Pointer in C :
     
Size of any type of pointer in C is independent of data type which is pointer pointing i.e. size of all type pointer (near) in C is two byte either it is char pointer double pointer, function or null pointer. Void pointer is not exception of this rule and size of void pointer is also two byte.

String Operations (string.h)

C language recognizes that string is a different class of array by letting us input and output the array as a unit and are terminated by null character. C library supports a large number of string handling functions that can be used to carry out many of the string manipulations such as :-

 * Length (Number of character in the string).
 * Concatenation (Adding two or more strings).
 * Comparing two strings.
 * Substring (Extract substring from a given string).
 * Copy (Copies one string over another).

To do all the operation described here it is essential to include string.h library header file in the program.

strlen( ) Function
  This function counts and returns the number of character in a string. The length does not include a null character.

 Syntax
 n=strlen(string);
                     Where n is integer variable which receives the value of length of the string.

Example :
  length = strlen("Irawen");
The function will assign number of character 9 in the string to a integer variable length.


\*Write a C program to find the length of the string using strlen( ) function. */

#include<stdio.h>
#include<string.h>
void main( )
{
char name[100];
int length;
printf("Enter the string");
gets(name);
length = strlen(name);
printf("\n Number of character in the string is=%d",length);
}

strcat( ) Function
 When you combine two strings , you add the character of one string to the end of other string. The process is called concatenation. The strcat( ) function joins two strings together. It takes the following form

Syntax :
  strcat(string1, string2)
   String1 and string2 are character arrays. When the function strcat is executed string2 is appended to string1. The string2 remains unchanged.

Example :
 strcpy(string1, "sri");
 strcpy(string2,"Bhagavan");
 printf("%s",strcat(string1,string2);
  
From the above program segment the value  of string1 becomes sribhagavan. The string at str2 remains unchanged as bhagavan.

strcmp( ) Function
  In C language we cannot directly compare the value of 2 strings in a condition like if(string1==string2).
  
Most libraries however contain the strcmp( ) function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same. The syntax of strcmp( ) is given below :
       Strcmp(string1,string2)

 String1 and string2 may be string variable or string constants. String1 and string2 may be string variable or string constant some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second.

Example :
strcmp("Newyork","Newyork")  will return zero because 2 strings are equal.

strcmp("their","there") will return a 9 which is the numeric difference between ASCII 'i' and ASCII 'r'.

strcmp("The","the") will return 32 which is the numeric difference between ASCII "T" & "t".


strcmpi( ) Function 
  This function is same as strcmp( ) which compares 2 string but not case sensitive.

Example :
  strcmpi("THE","the");  will return 0;

strcpy( ) Function
  C language not allow you to assign the characters to a string directly as in the statement name="Robert";

Instead use the strcpy( ) function found in most compilers the syntax of the function is illustrated below.
 strcpy(string1,string2);

Strcpy function assign the contents of string2 to string1. String2 may be a character array variable or a string constant.

strcpy(Name,"Robert");
In the above example Robert is assigned to the string called name.

strlwr( ) Funtion
 This function converts all characters in a string from uppercase to lower case.

Syntax:
 strlwr(string);

For example :
strlwr("IRAWEN") converts to Irawen.


strrev( ) Function
  This function reverses the character in a string.

Syntax
  strrev(string);

For example :
strrev("program") reverses the character in a string into "margrop".

strupr( ) Function
  This function converts all character in a string from lower case to uppercase.

Syntax
 strupr(string);

For example :
 strupr("pirawen") will convert the string to PIRAWEN.

/* Example program to use string functions */

#include<stdio.h>
#include<string.h>
void main( )
{
char s1[20], s2[20], s3[20];
int x;
printf("Enter the strings");
scanf("%s%s",s1,s2);
x=strcmp(s1,s2);
if(x!=0)
{
printf("\nStrings are not equal\n");
strcat(s1,s2);
}
else
printf("\nStrings are equal");
strcpy(s3,s1);
l1=strlen(s1);
l2=strlen(s2);
l3=strlen(s3);
printf("\n s1=%s\t length=%d characters\n",s1,l1);
printf("\n s2=%s\t length=%d characters\n",s2,l2);
printf("\n s3=%s\t length=%d characters\n",s3,l3);
}

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (116) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (93) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (747) Python Coding Challenge (213) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses