230 likes | 325 Views
Loops. different types: for while etc. For Loop. for(initialValue ; test-expression ; update-expression) { BODY }. Example. #include<iostream.h> int main() { int a; for (a = 0; a < 10; a++ ) { cout << a << endl; } return 0; }. While loop.
E N D
Loops • different types: • for • while • etc.
For Loop • for(initialValue; test-expression ; update-expression) { BODY }
Example #include<iostream.h> int main() { int a; for (a = 0; a < 10; a++ ) { cout << a << endl; } return 0; }
While loop • while(test-expression) { BODY }
Example #include<iostream.h> int main() { int arSize = 20; char name[arSize]; cin >> name; int a = 0; while (name[a] != ‘\0’) { cout << name[a] << endl; a++; } return 0; }
Conditional Statements • if statements • Syntax: if (condition) { IF_BODY } else { ELSE_BODY }
Conditions: • Relational Expressions: • Comparisons: • e.g • == tests equality • > is greater?
Example int number; cin >> number; if ( number < 0) { cout << “Negative Value” << endl; } else { cout << “Non-negative Value” << endl; }
Comparing two strings #include<iostream.h> int main() { int arSize = 20; char name1[arSize]; char name2[arSize]; cout<<“String1”<<endl; cin>>name1; cout<<“String2”<<endl; cin>>name2;
int len1,len2,a; len1=strlen(name1); len2=strlen(name2); bool flag=true; if (len1 != len2 ) cout<<“different”; else { for (a=0; (name1[a]==name2[a]) && a <len1 ;a++); if (a==len1) cout<<“The same”; else cout<<“different”; } }
Sort an Array of Integer #include<iostream.h> int main() { int arSize = 20; int ArrayNumber[arSize]; int index; for(index=0; index <20; index++) { cout<<“enter an integer”<<endl; cin>>ArrayNumber[index]; }
int i,j; int temp; for( i=1; i< 20;i++) for (j=0; j<20-i ; j++) if (ArrayNumber[ j] > ArrayNumber[ j+1]) { temp= ArrayNumber[ j ]; ArrayNumber[ j ]=ArrayNumber[ j+1]; ArrayNumber[ j+1]=temp; } }
do while do { Body } while( test-expression); Body executes at least once!
Write a program to compute converse of a positive integer number 1246 6421
long num; long num_converse=0; do { num_converse = num_convers*10+ num % 10; num = num/10; } while(num>0); cout<<num_converse;
More about I/O cin.get(), cin.getline() • Both cin.get() and cin.getline() read the entire input line( up to newline character) • getline() discards the newline char whereas get() leaves it in the input queue
Example cin.get(name, Arsize); cin.get(dessert,Arsize); //there is a problem Should be : cin.get(name, Arsize); cin.get(); cin.get(dessert,Arsize); Or we can write cin.get(name, Arsize).get() // read string and newline cin.get(dessert,Arsize); cin.get(name,Arsize) //returns the cin object which can be used to invoke the get().
We can write : cin.getline(nema1,Arsize).getline(name2,Arsize);
char ch; cin.get(ch); we can write ch=cin.get();
Write a program to find the greatest common divisor of 2 input numbers.
Write a program to read n and print out the n lines input like (n=5,7)