0% found this document useful (0 votes)
15 views

Loops Manual of (For Loop, While Loop and Do-While Loop)

Uploaded by

hifadi1393
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Loops Manual of (For Loop, While Loop and Do-While Loop)

Uploaded by

hifadi1393
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

For Loop:

 Loop: a control structure that causes a statement or statements to repeat


 Useful for counter-controlled loop
 General Format:
for (initialization; test; update)
statement; // or block in { }
 No semicolon after the update expression or after the)

for Loop - Mechanics


for (initialization; test; update)
statement; // or block in { }
1. Perform initialization
2. Evaluate test expression
 If true, execute statement
 If false, terminate loop execution
3. Execute update, then re-evaluate test expression
Example:
Code:
int count;
for (count = 1; count <= 5; count++)
cout << "Hello" << endl;
Execution Process:

Flow Chart:
Example 1: Write a program in C++ to find the first 10 natural
numbers.
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "\n\n Find the first 10 natural numbers:\n";
cout << "---------------------------------------\n";
cout << " The natural numbers are: \n";
for (i = 1; i <= 10; i++)
{
cout << i << " ";
}
cout << endl;
return 0;
}

Example 2: Write a program in C++ to find the sum of first 10 natural


numbers.
#include <iostream>
using namespace std;
int main()
{
int i,sum=0;
cout << "\n\n Find the first 10 natural numbers:\n";
cout << "---------------------------------------\n";
cout << " The natural numbers are: \n";
for (i = 1; i <= 10; i++)
{
cout << i << " ";
sum=sum+i;
}
cout << "\n The sum of first 10 natural numbers: "<<sum << endl;
}
Example 3: Write a program in C++ to display n terms of natural
number and their sum.
#include <iostream>
using namespace std;
int main()
{
int n,i,sum=0;
cout << "\n\n Display n terms of natural number and their sum:\n";
cout << "---------------------------------------\n";
cout << " Input a number of terms: ";
cin>> n;
cout << " The natural numbers upto "<< n <<"the terms are: \n";
for (i = 1; i <= n; i++)
{
cout << i << " ";
sum=sum+i;
}
cout << "\n The sum of the natural numbers is: "<<sum << endl;
}
Example 4: Write a program in C++ to find the factorial of a number.
#include <iostream>
using namespace std;
int main()
{
int num1,factorial=1;
cout << "\n\n Find the factorial of a number:\n";
cout << "------------------------------------\n";
cout << " Input a number to find the factorial: ";
cin>> num1;
for(int a=1;a<=num1;a++)
{
factorial=factorial*a;
}
cout<<" The factorial of the given number is: "<<factorial<<endl;
return 0;
}

Example 5: A person invests $ 1000.00 in a savings account yielding 5 %


interest. Assuming that all interests is left on deposit in the account, calculate
and print the amount of money in the account at the end of each year for ten
years. Use the following formula for determining these amounts:
a = p(1 + r) ^2
where
p = original amount invested (Principal),
r = annual interest rate,
n = number of years, and
a = amount on deposit at the end of the nth year.
//Calculation of Compound Interest
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
double amount, // amount on deposit
principal = 1000.0, // starting principal
rate = .05; // interest rate
cout << "Year" << setw( 21 )<< "Amount on deposit" << endl;
cout << "--------------------------------------------\n";
for ( int year = 1; year <=10; year++ )
{
amount = principal * pow( 1.0 + rate, year );
cout << setw( 4 ) << year <<fixed<< setprecision( 2 )
<< setw( 21 )<< amount << endl;
}
return 0;
}

Example 6: Write a program in C++ to check whether a number is


prime or not.
#include <iostream>
using namespace std;
int main()
{
int num1, ctr = 0;
cout << "\n\n Check whether a number is prime or not:\n";
cout << "--------------------------------------------\n";
cout << " Input a number to check prime or not: ";
cin>> num1;
for (int a = 1; a <= num1; a++)
{
if (num1 % a == 0)
{
ctr++;
}
}
if (ctr == 2)
{
cout << " The entered number is a prime number. \n";
}
else {
cout << " The number you entered is not a prime number. \n";
}
return 0;
}

// Using the Break statement in a for structure


#include <iostream>
using namespace std;
int main()
{
// x declared here so it can be used after the loop.
int x;
for ( x = 1; x <= 10; x++ )
{
if ( x == 5 )
break; // break loop only if x is 5
cout << x << " ";
}
cout << "\nBroke out of loop at x of " << x << endl;
return 0;
}

// Using the continue statement in a for structure

#include <iostream>
using namespace std;
int main()
{
for ( int x = 1; x <= 10; x++ )
{
if ( x == 5 )
continue; // skip remaining code in loop only if x is 5
cout << x << " ";
}
cout << "\nUsed continue to skip printing the value 5" << endl;
return 0;
}
While Loop:
 Loop: a control structure that causes a statement or statements to repeat
 General format of the while loop:
while (expression)
statement;
 statement; can also be a block of statements enclosed in { }

Example 1: Write a program using while loop that show the


sum of first five numbers.
Code:
#include<iostream>
using namespace std;
int main()
{
int number=1,sum=0;
while(number<=5)
{
sum=sum+number;
number++;
}
cout<<"Sum is "<<sum;
return 0;
}
Execution Process:

Flow chart:

Example 2: Write a program for take input the list of numbers


and print their squares.
Code:
#include <iostream>
using namespace std;
int main()
{
int minimum=1;
int maximum=10;
int num=minimum;
cout<<"Number number squared \n ";
while(num<=maximum)
{
cout<<num<<"\t\t"<<num*num<<endl;
num++;
}
return 0;
}

Output:

Example 3: Write a program in C++ to find the factorial of a


number.

#include <iostream>
using namespace std;
int main()
{
int n;
cout<< "Input a number to find the factorial:";
cin>>n;
int factorial = 1;
int i = 1;
while (i <= n)
{
factorial = factorial*i;
i++;
}
cout << factorial;
}

Example 4: A class of ten students took a quiz. The grades


(integers in the range 0 to 100) for this quiz are available to
you. Calculate and display the total of all student grades and
the class average on the quiz.
#include <iostream>
using namespace std;
int main()
{
int total; // sum of grades entered by user
int gradeCounter; // number of the grade to be entered next
int grade; // grade value entered by user
double average; // average of grades
// initialization phase
total = 0; // initialize total
gradeCounter = 1; // initialize loop counter
// processing phase
while ( gradeCounter <= 10 ) // loop 10 times
{
cout << "Enter grade: "<<gradeCounter; // prompt for input
cin >> grade; // input next grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter by 1
} // end while
// termination phase
average = total / 10; // integer division yields integer result
// display total and average of grades
cout << "\nTotal of all 10 grades is " << total << endl;
cout << "Class average is " << average << endl;

}
Formulating Algorithms (Sentinel-Controlled Repetition)
Example 5: Develop a class averaging program that will
process an arbitrary number of grades each time the program
is run.
# include <iostream>
# include <iomanip>
using namespace std;
int main()
{
int total, // sum of grades
gradeCounter, // number of grades entered
grade; // one grade
float average; // average of grades
// initialization phase
total = 0; // Clear total
gradeCounter = 0; // prepare to loop
// processing phase
cout << "Enter grade, type -1 to indicate the end outer: ";
cin >> grade; // input grade
while ( grade != -1) // loop until -1 is entered
{
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
cout << "Enter grade, type -1 to indicate the end inner: ";
cin >> grade;
}
// termination phase
if ( gradeCounter != 0 )
{
average = static_cast< float >( total ) / gradeCounter;
cout << "Class average is " << setprecision( 2 ) <<fixed<< average << endl;
}
else
{
cout << "No grades were entered"<<endl;
}
return 0; //indicate program ended successfully
}
Example 6: A college has a list of test results (1 = pass, 2 = fail)
for 10 students. Write a program that analyzes the results. If
more than 8 students pass, print "Raise Tuition".
//Analysis of examination results

#include <iostream>
using namespace std;
int main()
{
// initialize variables in declarations
int passes = 0, // number of passes
failures = 0, // number of failures
studentCounter = 1, // student counter
result; // one exam result
// process 10 students; counter-controlled loop
while ( studentCounter <=10 )
{
cout << "Enter result (1=pass, 2=fail): ";
cin >> result;
if ( result == 1) // if/else nested in while
{
passes = passes + 1;
}
else
{
failures = failures + 1;
}
studentCounter = studentCounter + 1;
}
// termination phase
cout << "Passed " << passes << endl;
cout << "Failed " << failures << endl;
if ( passes > 8 )
{
cout<< "Raise tuition " << endl;
}
return 0;
// successful termination
}
Example 7: Write a program to Printing and count Even
and Odd Numbers using While Loop in C++.
#include<iostream>
using namespace std;
int main()
{
int i=1,n,even=0,odd=0;
cout<<"\nEnter the Ending value:";
cin>>n;
while(i<=n)
{
if(i%2==0)
{
cout<<"\nEven numbers:";
cout<<"\n"<<i;
even++;
}
else
{
cout<<"\nOdd numbers:";
cout<<"\n"<<i;
odd++;
}
i++;
}
cout<<"\nTotal even numbers:"<<even;
cout<<"\nTOtal odd numbers:"<<odd;
return 0;
}
OR

#include<iostream>
using namespace std;
int main()
{
int i=1,n,even=0,odd=0;
cout<<"\nEnter the Ending value:";
cin>>n;
cout<<"\nEven numbers:";
while(i<=n)
{
if(i%2==0)
{
cout<<"\n"<<i;
even++;
}
i++;
}
cout<<"\nOdd numbers:";
i=1;
while(i<=n)
{
if(i%2==1)
{
cout<<"\n"<<i;
odd++;
}
i++;
}
cout<<"\nTotal even numbers:"<<even;
cout<<"\nTOtal odd numbers:"<<odd;
return 0;
}

Example 8: Write a program to check Even and Odd


Numbers using While Loop on the basis of user choice in
C++.
#include <iostream>
using namespace std;
int main()
{
int choice = 1;
while( choice == 1 )
{
int a;
cout << "Enter a number to check even or odd" << endl;
cin >> a; //input number

//check whether number is even or odd

if( a%2 == 0 ){
cout << "Your number is even" << endl;
}
else{
cout << "Your number is odd" << endl;
}
cout << "Want to check more : 1 for yes and 0 for no" << endl;

cin >> choice;


}

cout << "I hope you checked all your numbers" << endl;
return 0;
}

Do while Loop:
 do-while: a posttest loop – execute the loop, then test the expression
 General Format:
do
statement; // or block in { }
while (expression);
 Note that a semicolon is required after (expression)

Example:
Code:
int x = 1;
do
{
cout << x << endl;
} while(x < 0);

Although the test expression is false, this loop will execute one time because do-
while is a posttest loop.

Example 1: Write a program to calculate the average of three


numbers and take a condition to calculate other set of
numbers .
#include <iostream>
using namespace std;
int main()
{
int s1,s2,s3;
double average;
char again;
do
{
cout<<"Enter the three scors";
cin>>s1>>s2>>s3;
average =(s1+s2+s3)/3;
cout<<"The average is "<<average <<"\n";
cout<<"Do you want to average another set? (Y/N)";
cin>>again;
}
while(again=='Y'|| again=='y');
return 0;
}

Example 2: Write a C++ program to implement the Number Guessing Game. In


this game the computer chooses a random number between 1 and 100, and the
player tries to guess the number in as few attempts as possible. Each time the
player enters a guess, the computer tells him whether the guess is too high, too
low, or right. Once the player guesses the number, the game is over.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
int num, guess, tries = 0;
srand(time(0)); //seed random number generator
num = rand() % 100 + 1; // random number between 1 and 100
cout<<num;
cout << "Guess My Number Game\n\n";

do
{
cout << "Enter a guess between 1 and 100 : ";
cin >> guess;
tries++;

if (guess > num)


cout << "Too high!\n\n";
else if (guess < num)
cout << "Too low!\n\n";
else
cout << "\nCorrect! You got it in " << tries << " guesses!\n";
} while (guess != num);

return 0;
}
Practice Questions links website link of
(for loop, while loop and do-while loop)

For loop practicing Exercise:


https://www.w3resource.com/c-programming-exercises/for-loop/
index.php

While/do-while loop practicing Exercise:


https://t4tutorials.com/loop-programming-exercises-and-solutions-in-c/
https://dotnettutorials.net/lesson/while-loop-in-cpp/
https://www.codesdope.com/practice/cpp-loops/
https://home.adelphi.edu/~pe16132/csc171/loopWhileExercise.htm
https://www.guru99.com/cpp-do-while-loop.html

You might also like