SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Loops in c++ programming language
Loops in c++ programming language Loops in c++ programming language
Loops in c++ programming language
MUHAMMAD ALI student of IT at karakoram International university gilgit baltistan
 
Looping statements
Looping statementsLooping statements
Looping statements
Chukka Nikhil Chakravarthy
 
C++ control loops
C++ control loopsC++ control loops
C++ control loops
pratikborsadiya
 
Forloop
ForloopForloop
Forloop
Dipen Vasoya
 
Iteration
IterationIteration
Iteration
Liam Dunphy
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
Sriman Sawarthia
 
Looping in c++
Looping in c++Looping in c++
Looping in c++
deekshagopaliya
 
Loops in c
Loops in cLoops in c
Loops in c
baabtra.com - No. 1 supplier of quality freshers
 
Control statements
Control statementsControl statements
Control statements
Kanwalpreet Kaur
 
The Loops
The LoopsThe Loops
The Loops
Krishma Parekh
 
Java loops
Java loopsJava loops
Java loops
ricardovigan
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
Mahantesh Devoor
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
sneha2494
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
Gagan Deep
 
Looping statement
Looping statementLooping statement
Looping statement
ilakkiya
 
While loops
While loopsWhile loops
While loops
Michael Gordon
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 

Viewers also liked (20)

Loops in C Programming
Loops in C ProgrammingLoops in C Programming
Loops in C Programming
Himanshu Negi
 
Loops in C
Loops in CLoops in C
Loops in C
Kamal Acharya
 
Loops
LoopsLoops
Loops
Peter Andrews
 
Loops Basics
Loops BasicsLoops Basics
Loops Basics
Mushiii
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
MeoRamos
 
Do While and While Loop
Do While and While LoopDo While and While Loop
Do While and While Loop
Hock Leng PUAH
 
C if else
C if elseC if else
C if else
Ritwik Das
 
INTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMINGINTRODUCTION TO C PROGRAMMING
INTRODUCTION TO C PROGRAMMING
Abhishek Dwivedi
 
Nesting of for loops using C++
Nesting of for loops using C++Nesting of for loops using C++
Nesting of for loops using C++
prashant_sainii
 
Loops
LoopsLoops
Loops
International Islamic University
 
Chapter 05 looping
Chapter 05   loopingChapter 05   looping
Chapter 05 looping
Dhani Ahmad
 
Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)Understand Decision structures in c++ (cplusplus)
Understand Decision structures in c++ (cplusplus)
Muhammad Tahir Bashir
 
Switch Case in C Programming
Switch Case in C ProgrammingSwitch Case in C Programming
Switch Case in C Programming
Sonya Akter Rupa
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
patricia Hidalgo
 
C++ programming
C++ programmingC++ programming
C++ programming
viancagerone
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
Module 2: C# 3.0 Language Enhancements (Slides)
Module 2: C# 3.0 Language Enhancements (Slides)Module 2: C# 3.0 Language Enhancements (Slides)
Module 2: C# 3.0 Language Enhancements (Slides)
Mohamed Saleh
 
c++ for loops
c++ for loopsc++ for loops
c++ for loops
MOHAMMED ALZAYLAEE
 
Ch01 introduction
Ch01 introductionCh01 introduction
Ch01 introduction
GRajendra
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
Karwan Mustafa Kareem
 
Ad

Similar to C++ loop (20)

C++ control structure
C++ control structureC++ control structure
C++ control structure
bluejayjunior
 
Control structures
Control structuresControl structures
Control structures
Isha Aggarwal
 
Computational PhysicsssComputational Physics.pptx
Computational PhysicsssComputational Physics.pptxComputational PhysicsssComputational Physics.pptx
Computational PhysicsssComputational Physics.pptx
khanzasad009
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
(•̮̮̃•̃) Prince Do Not Work
 
C++ lecture 02
C++   lecture 02C++   lecture 02
C++ lecture 02
HNDE Labuduwa Galle
 
3. control statement
3. control statement3. control statement
3. control statement
Shankar Gangaju
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
NaumanRasheed11
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Computational Physics Cpp Portiiion.pptx
Computational Physics Cpp Portiiion.pptxComputational Physics Cpp Portiiion.pptx
Computational Physics Cpp Portiiion.pptx
khanzasad009
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
Amrit Kaur
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
Suhail Akraam
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Programming Fundamentals presentation slide
Programming Fundamentals presentation slideProgramming Fundamentals presentation slide
Programming Fundamentals presentation slide
mibrahim020205
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
Mukund Trivedi
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
sana shaikh
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
Ayman Hassan
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
Zohaib Ahmed
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
bluejayjunior
 
Computational PhysicsssComputational Physics.pptx
Computational PhysicsssComputational Physics.pptxComputational PhysicsssComputational Physics.pptx
Computational PhysicsssComputational Physics.pptx
khanzasad009
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
rohassanie
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
NaumanRasheed11
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Computational Physics Cpp Portiiion.pptx
Computational Physics Cpp Portiiion.pptxComputational Physics Cpp Portiiion.pptx
Computational Physics Cpp Portiiion.pptx
khanzasad009
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
Suhail Akraam
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Programming Fundamentals presentation slide
Programming Fundamentals presentation slideProgramming Fundamentals presentation slide
Programming Fundamentals presentation slide
mibrahim020205
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
sana shaikh
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
Zohaib Ahmed
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
Mohamed Ahmed
 
Ad

Recently uploaded (20)

Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 

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