Wednesday 6 June 2018

Lesson 4-C++ Loops :- While loop, For loop, Do-While loop - Coding overdose

in programming languages, loops are used to execute a set of statements repeatedly, until a particular condition is satisfied.

There are 3 kind of loops in c++

1. While loop
2.For loop
3.Do-While loop


1.While loop


Example1:-counting from 0 to 9 (using while loop)




#include <iostream>
using namespace std;

int main()
{
    int x=0;

while (x<=9) {
        cout << x<<endl;
        x=x+1;
    }

    return 0;
}









































The same code can be executed by for loop as well



2.For LOOP


syntax :-

   for ( intitiation point ; termination point ;  increment or decrement)

    {condition;
}


Example 1:-counting from 0 to 9 (using for loop)


#include <iostream>
using namespace std;
int main ()

{
    int x=0;

    for ( x=0; x<=9; x=x+1)

    {cout<<x <<endl;
}


    return 0;

}








































Example 2:-Multiplication table

#include <iostream>
using namespace std;
int main()

{

    int a;
    cout << "Enter a positive integer: ";
    cin >> a;

    for (int b=1; b<= 10; b=b+1)

    {
        cout << a << " * " << b << " = " << a * b << endl;
    }

    return 0;

}


















































3.Do while loop


The same program that counted 0-9,,,, can also be made using this loop..

The especiality of do while loop is that it tests the condition at last,, whether its true or not..


syntax :-

do{statements;

}
while ( conditions) ;

dont forget the semicolon after while statement

Example 2:-counting from 0 to 9 (using do-while loop)
    


#include <iostream>
using namespace std;
int main()

{

int x=0;

do {cout<<x<<endl;
x=x+1;}

while (x<=9) ;

    return 0;

}















































in next lesson you will learn about mathematical functions

Mathematical functions in c++








No comments:

Post a Comment