Looping Looping means repeating the same code again and again until certain conditions are met It is of 2 types 1.Entry controlled loop-Controlling will be at the starting of the loop Eg:-while,for 2.Exit controlled loop-Controlling will be on the end of the loop Eg:-do….while while Syntax:- while(condition) { ……………….. } Write program to print first n natural numbers using while #include<iostream> using namespace std; int main() { int n,i=1; cout<<”Enter the limit”; cin>>n; while(i<=n) { cout<<i; i++; } return 0; } for- Syntax for(initialisation;condition;increment/decrement) { …………………………… } for will execute like the following
initialisation condition No Yes code of the loop increment/decrement Write program to print first n natural numbers using for loop #include<iostream> using namespace std; int main() { int n,i; cout<<”Enter the limit”; cin>>n; for(i=1;i<=n;i++) { cout<<i; } return 0; } do….while Syntax do { …………………….. }while(condition); Write program to print first n natural numbers using do…while loop #include<iostream> using namespace std; int main()
{ int n,i=1; cout<<”Enter the limit”; cin>>n; do { cout<<i; i++; }while(i<=n); return 0; } Write program to print sum of first n natural numbers using while loop #include<iostream> using namespace std; int main() { int n,i=1,s=0; cout<<”Enter the limit”; cin>>n; while(i<=n) { s=s+i; i++; } cout<<”sum=”<<s; return 0; } Jump statements 1.break- when break is met,loop will terminate and will do codes after the loop 2.continue-when continue is met,loop will terminate and will go for the next iteration.
Search
Read the Text Version
- 1 - 3
Pages: