SlideShare a Scribd company logo
2
Most read
5
Most read
6
Most read
C++ language structure
Loops have as purpose to repeat a statement a certain number of times or
while a condition is fulfilled.
The While loop
The while loop Its format is:
while(condition)
{
statement(s);
}
its functionality is simply to repeat statement while the condition set in
expression is true. For example, we are going to make a program to
countdown using a while-loop, When the program starts the user is
prompted to insert a starting number for the countdown. Then the while
loop begins, if the value entered by the user fulfills the condition n>0
(that n is greater than zero) the block that follows the condition will be
executed and repeated while the condition (n>0) remains being true.
#include <iostream>
using namespace std;
int main ()
{ int n;
cout << "Enter the starting number >
";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << "FIRE!n";
return 0;
}
Out put
The whole process of the previous program can be interpreted
according to the following script (beginning in main):
1. User assigns a value to n
2. The while condition is checked (n>0). At this point there are two
possibilities: * condition is true: statement is executed (to step 3) *
condition is false: ignore statement and continue after it (to step 5)
3. Execute statement: cout << n << ", "; --n; (prints the value of n on
the screen and decreases n by 1)
4. End of block. Return automatically to step 2
5. Continue the program right after the block: print FIRE! and end
program.
#include <iostream>
using namespace std;
int main()
{
int i;
i=1;
while (i<=100)
{
cout<<"*t";
i++;
}
return 0;
}
Out put
The do-while loop
Its format is:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that
condition in the do-while loop is evaluated after the execution of
statement instead of before, granting at least one execution of
statement even if condition is never fulfilled. The do-while loop is
an exit-condition loop. This means that the body of the loop is always
executed first. Then, the test condition is evaluated. If the test
condition is TRUE, the program executes the body of the loop again. If
the test condition is FALSE, the loop terminates and program execution
continues with the statement following the while.
#include <iostream>
using namespace std;
int main ()
{
Long int n;
do
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "n";
}
while (n != 0);
return 0;
}
Example 3 : write a program with using do-while to enter number until zero
Out put
#include <iostream>
using namespace std;
int main ()
{
char ans;
do
{
cout<< "Do you want to continue (Y/N)?n";
cout<< "You must type a 'Y' or an 'N'.n";
cin >> ans;
}
while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
}
Example 4: The following program fragment is an input routine that insists that
the user type a correct response .in this case, a small case or capital case 'Y' or
'N'. The do-while loop guarantees that the body of the loop (the question) will
always execute at least one time.*/
// do loop execution
#include <iostream>
using namespace std;
int main ()
{
int a = 10;
do {
cout << "value of a: " << a << endl;
a = a + 1;
}
while( a < 20 );
return 0;
}
Out put
Example 5: write a program to print a value of a with adding 1.
The for loop
Its format is:
for (initialization; condition; increase) statement
and its main function is to repeat statement while condition remains true, like the while
loop. But in addition, the for loop provides specific locations to contain an
initialization statement and an increase statement. So this loop is specially designed
to perform a repetitive action with a counter which is initialized and increased on each
iteration.
It works in the following way:
1. initialization is executed. Generally it is an initial value setting for a counter variable.
This is executed only once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
3. statement is executed. As usual, it can be either a single statement or a block
enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back
to step 2.
Example 6 : C++ Program to find factorial of a number (Note: Factorial of positive
integer n = 1*2*3*...*n)
#include <iostream>
using namespace std;
int main ()
{
int i, n, factorial = 1;
cout<<"Enter a positive integer: ";
cin>>n;
for (i = 1; i <= n; ++i)
{
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
Out put
#include <iostream>
using namespace std;
int main ()
{
int i, n, factorial = 1;
cout<<"Enter a positive integer: ";
cin>>n;
if (n<1)
cout<<"error input positive number";
else
for (i = 1; i <= n; ++i)
{
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
Example 7: write a program for factorial with using loops and condition
Out put
#include <iostream>
using namespace std;
int main ()
{
int i, n;
int d1,d2,d3,d4,d5;
int sum, average;
string name;
cout<<"Enter a positive integer: ";
cin>>n;
for (i = 1; i <= n; ++i)
{
cin>>name;
cin>>d1>>d2>>d3>>d4>>d5;
sum=d1+d2+d3+d4+d5;
average=sum/5;
Example 8: write a program to find the average and final result of more than one student
cout<< "naverage="<<average;
If((d1>=50)&&(d2>=50)&&(d3>=50)&&(d4>=50)&&(d5>=50))
cout<<"nPASS";
else
cout<<"nFAIL";
}
return 0;
}
Out put
Switch – case
Its form is the following:
switch (expression)
{
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break; . . .
default:
default group of statements
}
It works in the following way: switch evaluates expression and checks if it is
equivalent to constant1, if it is, it executes group of statements 1 until it finds
the break statement. When it finds this break statement the program jumps to
the end of the switch selective structure.
If expression was not equal to constant1 it will be checked against constant2. If it
is equal to this, it will execute group of statements 2 until a break keyword is
found, and then will jump to the end of the switch selective structure.
Finally, if the value of expression did not match any of the previously specified
constants (you can include as many case labels as values you want to check), the
program will execute the statements included after the default: label, if it exists
(since it is optional)
#include <iostream>
using namespace std;
int main ()
{
int x;
cin>>x;
switch (x)
{
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "value of x unknown";
}
return 0;
}
Example 9: write a program to display the value of x with multiple options
Out put
#include <iostream>
using namespace std;
int main ()
{
float x,y,z;
char a;
cin>>x>>y;
cin>>a;
switch (a)
{
case '+':
z=x+y;
cout << " X+Y="<<z;
break;
Example 10 : write a program to make a calculator with using switch case
case '-':
z=x-y;
cout << " X-Y="<<z;
break;
case '*':
z=x*y;
cout<<" X*Y="<<z;
break;
default:
z=x/y;
cout << "x/y="<<z;
}
return 0;
}
Out put
#include <iostream>
using namespace std;
int main ()
{
// local variable declaration:
int grade;
cin>>grade;
switch(grade)
{
case 90:
cout << "Excellent!" << endl;
break;
case 80:
cout << "Very Good" <<
endl;
break;
Example 11 : write a program to make a convert the numbers to evaluation
case 70:
cout << "Good" << endl;
break;
case 60:
cout << "Merit" << endl;
break;
case 50:
cout<<"Accept";
break;
default :
cout << "Fail" << endl;
}
cout << "Your grade is " << grade <<
endl;
return 0;
} Out put

More Related Content

PPTX
Loop control in c++
PPT
Looping in c++
PPT
While loop
PPTX
Loop c++
PPTX
Presentation on nesting of loops
PPTX
Do...while loop structure
Loop control in c++
Looping in c++
While loop
Loop c++
Presentation on nesting of loops
Do...while loop structure

What's hot (20)

PPTX
Loops c++
DOCX
Looping statements
PPT
C++ control loops
PPTX
Forloop
PPT
Iteration
PPT
Looping statements in Java
PPTX
While , For , Do-While Loop
PPTX
Comp ppt (1)
PPT
Looping in c++
PDF
Control statements
PPTX
The Loops
DOCX
Java loops
PPTX
Loops in C Programming Language
PPTX
Types of loops in c language
PPSX
C lecture 4 nested loops and jumping statements slideshare
PPTX
Looping statement
PDF
While loops
PPTX
Loops in c language
Loops c++
Looping statements
C++ control loops
Forloop
Iteration
Looping statements in Java
While , For , Do-While Loop
Comp ppt (1)
Looping in c++
Control statements
The Loops
Java loops
Loops in C Programming Language
Types of loops in c language
C lecture 4 nested loops and jumping statements slideshare
Looping statement
While loops
Loops in c language
Ad

Viewers also liked (20)

PPTX
Loops in C Programming
PPTX
Loops in C
PPTX
PPTX
Loops Basics
PPTX
Looping and switch cases
PPTX
Do While and While Loop
PPTX
C if else
PPSX
INTRODUCTION TO C PROGRAMMING
PDF
Nesting of for loops using C++
PPT
Chapter 05 looping
PPTX
Understand Decision structures in c++ (cplusplus)
PPTX
Switch Case in C Programming
PPTX
Switch case and looping
PPT
C++ programming
PPT
Basics of c++ Programming Language
PPTX
Module 2: C# 3.0 Language Enhancements (Slides)
PDF
c++ for loops
PPT
Ch01 introduction
PPT
Java Programming: Loops
Loops in C Programming
Loops in C
Loops Basics
Looping and switch cases
Do While and While Loop
C if else
INTRODUCTION TO C PROGRAMMING
Nesting of for loops using C++
Chapter 05 looping
Understand Decision structures in c++ (cplusplus)
Switch Case in C Programming
Switch case and looping
C++ programming
Basics of c++ Programming Language
Module 2: C# 3.0 Language Enhancements (Slides)
c++ for loops
Ch01 introduction
Java Programming: Loops
Ad

Similar to C++ loop (20)

PDF
C++ control structure
DOC
Control structures
DOCX
C++ Loops General Discussion of Loops A loop is a.docx
PPT
03 conditions loops
PPTX
Cs1123 6 loops
PPT
C++ programming
PDF
Workbook_2_Problem_Solving_and_programming.pdf
PPTX
Switch case and looping kim
PPTX
Switch case and looping
PPTX
Computational Physics Cpp Portiiion.pptx
PDF
Chapter 3 Computer Programmingodp-1_250331_041044.pdf
PPTX
Final project powerpoint template (fndprg) (1)
PPTX
Lec7 - Loops updated.pptx
PPT
for loops in C++ and their functions and applicability
PPTX
Lecture 5
PPT
FP 201 - Unit 3 Part 2
PPT
12 lec 12 loop
PPT
ch5_additional.ppt
PPT
Control Statement.ppt
C++ control structure
Control structures
C++ Loops General Discussion of Loops A loop is a.docx
03 conditions loops
Cs1123 6 loops
C++ programming
Workbook_2_Problem_Solving_and_programming.pdf
Switch case and looping kim
Switch case and looping
Computational Physics Cpp Portiiion.pptx
Chapter 3 Computer Programmingodp-1_250331_041044.pdf
Final project powerpoint template (fndprg) (1)
Lec7 - Loops updated.pptx
for loops in C++ and their functions and applicability
Lecture 5
FP 201 - Unit 3 Part 2
12 lec 12 loop
ch5_additional.ppt
Control Statement.ppt

Recently uploaded (20)

PDF
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Modernizing your data center with Dell and AMD
PDF
SAP855240_ALP - Defining the Global Template PUBLIC.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Cloud computing and distributed systems.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
Advanced IT Governance
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
REPORT: Heating appliances market in Poland 2024
PDF
Omni-Path Integration Expertise Offered by Nor-Tech
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
KodekX | Application Modernization Development
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
CIFDAQ's Teaching Thursday: Moving Averages Made Simple
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Modernizing your data center with Dell and AMD
SAP855240_ALP - Defining the Global Template PUBLIC.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
NewMind AI Weekly Chronicles - August'25 Week I
MYSQL Presentation for SQL database connectivity
Cloud computing and distributed systems.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
madgavkar20181017ppt McKinsey Presentation.pdf
CroxyProxy Instagram Access id login.pptx
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Advanced IT Governance
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
REPORT: Heating appliances market in Poland 2024
Omni-Path Integration Expertise Offered by Nor-Tech
Review of recent advances in non-invasive hemoglobin estimation
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
KodekX | Application Modernization Development
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf

C++ loop

  • 2. Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled. The While loop The while loop Its format is: while(condition) { statement(s); } its functionality is simply to repeat statement while the condition set in expression is true. For example, we are going to make a program to countdown using a while-loop, When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows the condition will be executed and repeated while the condition (n>0) remains being true.
  • 3. #include <iostream> using namespace std; int main () { int n; cout << "Enter the starting number > "; cin >> n; while (n>0) { cout << n << ", "; --n; } cout << "FIRE!n"; return 0; } Out put
  • 4. The whole process of the previous program can be interpreted according to the following script (beginning in main): 1. User assigns a value to n 2. The while condition is checked (n>0). At this point there are two possibilities: * condition is true: statement is executed (to step 3) * condition is false: ignore statement and continue after it (to step 5) 3. Execute statement: cout << n << ", "; --n; (prints the value of n on the screen and decreases n by 1) 4. End of block. Return automatically to step 2 5. Continue the program right after the block: print FIRE! and end program.
  • 5. #include <iostream> using namespace std; int main() { int i; i=1; while (i<=100) { cout<<"*t"; i++; } return 0; } Out put
  • 6. The do-while loop Its format is: do statement while (condition); Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled. The do-while loop is an exit-condition loop. This means that the body of the loop is always executed first. Then, the test condition is evaluated. If the test condition is TRUE, the program executes the body of the loop again. If the test condition is FALSE, the loop terminates and program execution continues with the statement following the while.
  • 7. #include <iostream> using namespace std; int main () { Long int n; do { cout << "Enter number (0 to end): "; cin >> n; cout << "You entered: " << n << "n"; } while (n != 0); return 0; } Example 3 : write a program with using do-while to enter number until zero Out put
  • 8. #include <iostream> using namespace std; int main () { char ans; do { cout<< "Do you want to continue (Y/N)?n"; cout<< "You must type a 'Y' or an 'N'.n"; cin >> ans; } while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n')); } Example 4: The following program fragment is an input routine that insists that the user type a correct response .in this case, a small case or capital case 'Y' or 'N'. The do-while loop guarantees that the body of the loop (the question) will always execute at least one time.*/
  • 9. // do loop execution #include <iostream> using namespace std; int main () { int a = 10; do { cout << "value of a: " << a << endl; a = a + 1; } while( a < 20 ); return 0; } Out put Example 5: write a program to print a value of a with adding 1.
  • 10. The for loop Its format is: for (initialization; condition; increase) statement and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the for loop provides specific locations to contain an initialization statement and an increase statement. So this loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each iteration. It works in the following way: 1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }. 4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
  • 11. Example 6 : C++ Program to find factorial of a number (Note: Factorial of positive integer n = 1*2*3*...*n) #include <iostream> using namespace std; int main () { int i, n, factorial = 1; cout<<"Enter a positive integer: "; cin>>n; for (i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; } cout<< "Factorial of "<<n<<" = "<<factorial; return 0; } Out put
  • 12. #include <iostream> using namespace std; int main () { int i, n, factorial = 1; cout<<"Enter a positive integer: "; cin>>n; if (n<1) cout<<"error input positive number"; else for (i = 1; i <= n; ++i) { factorial *= i; // factorial = factorial * i; } cout<< "Factorial of "<<n<<" = "<<factorial; return 0; } Example 7: write a program for factorial with using loops and condition Out put
  • 13. #include <iostream> using namespace std; int main () { int i, n; int d1,d2,d3,d4,d5; int sum, average; string name; cout<<"Enter a positive integer: "; cin>>n; for (i = 1; i <= n; ++i) { cin>>name; cin>>d1>>d2>>d3>>d4>>d5; sum=d1+d2+d3+d4+d5; average=sum/5; Example 8: write a program to find the average and final result of more than one student
  • 15. Switch – case Its form is the following: switch (expression) { case constant1: group of statements 1; break; case constant2: group of statements 2; break; . . . default: default group of statements } It works in the following way: switch evaluates expression and checks if it is equivalent to constant1, if it is, it executes group of statements 1 until it finds the break statement. When it finds this break statement the program jumps to the end of the switch selective structure. If expression was not equal to constant1 it will be checked against constant2. If it is equal to this, it will execute group of statements 2 until a break keyword is found, and then will jump to the end of the switch selective structure. Finally, if the value of expression did not match any of the previously specified constants (you can include as many case labels as values you want to check), the program will execute the statements included after the default: label, if it exists (since it is optional)
  • 16. #include <iostream> using namespace std; int main () { int x; cin>>x; switch (x) { case 1: cout << "x is 1"; break; case 2: cout << "x is 2"; break; default: cout << "value of x unknown"; } return 0; } Example 9: write a program to display the value of x with multiple options Out put
  • 17. #include <iostream> using namespace std; int main () { float x,y,z; char a; cin>>x>>y; cin>>a; switch (a) { case '+': z=x+y; cout << " X+Y="<<z; break; Example 10 : write a program to make a calculator with using switch case
  • 18. case '-': z=x-y; cout << " X-Y="<<z; break; case '*': z=x*y; cout<<" X*Y="<<z; break; default: z=x/y; cout << "x/y="<<z; } return 0; } Out put
  • 19. #include <iostream> using namespace std; int main () { // local variable declaration: int grade; cin>>grade; switch(grade) { case 90: cout << "Excellent!" << endl; break; case 80: cout << "Very Good" << endl; break; Example 11 : write a program to make a convert the numbers to evaluation
  • 20. case 70: cout << "Good" << endl; break; case 60: cout << "Merit" << endl; break; case 50: cout<<"Accept"; break; default : cout << "Fail" << endl; } cout << "Your grade is " << grade << endl; return 0; } Out put