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

C++ Loop Exercise

Uploaded by

Memo Seid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

C++ Loop Exercise

Uploaded by

Memo Seid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 13

C++ Loop Exercise

• Write a C++ program to display all natural numbers from 1 to n.


• Write a C++ program to display all alphabets from A to Z.
• Write a C++ program to display all even numbers between 1 to 100.
• Write a C++ program to display the sum of all natural numbers b/n 1 to n.
• Write a C++ program to display the sum of all even numbers b/n 1 to n.
Infinity Loop
#include<iostream>
using namespace std;
int main()
{
int sum=0;
int n;
cout<<“enter a number or enter 0 to exit”<<endl;
cin>>n;
Cont.…
For(; ;)
{
sum+=n;
cout<<“enter a number or enter 0 to exit”<<endl;
cin>>n;
if(n==0)
break;
}
cout<<sum<<endl;
return 0;
}
Using while loop
while(1)
{
sum+=n;
cout<<“enter a number or enter 0 to exit”<<endl;
cin>>n;
if(n==0)
break;
}
cout<<sum<<endl;
return 0;
}
Using do while
do {
sum+=n;
cout<<“enter a number or enter 0 to exit”<<endl;
cin>>n;
if(n==0)
break;
}while(1)
cout<<sum<<endl;
return 0;
}
Write a C++ program to display all natural numbers
from 1 to n.

#include<iostream>
using namespace std;
int main()
{
int n;
cout<<“enter a number”<<endl;
cin>>n;
Cont.…
int k =1;
while(k>n)
{
cout<<k<<endl;
k++;
}
return 0;
}
Write a C++ program to display all even numbers
between 1 to 100.

#include<iostream>
using namespace std;
int main()
{
for(int i= 1; i<=100; i++)
if(i%2==0)
cout<<i<<endl;
}
Write a C++ program to display the sum of all natural
numbers b/n 1 to n.

#include<iostream>
using namespace std;
int main()
{
int sum=0;
int n;
cout<<“enter a number”<<endl;
cin>>n;
Cont.…
int i=1;
do {
sum+=i;
i++;
}while(i<=n)
cout<<sum<<endl;
return 0;
}
Write a C++ program to display the sum of all even
numbers b/n 1 to n.

#include<iostream>
using namespace std;
int main()
{
int sum=0;
int n;
cout<<“enter a number”<<endl;
cin>>n;
Cont.…
int i=1;
do {
if(i%2==0)
sum+=i;
i++;
}while(i<=n)
cout<<sum<<endl;
return 0;
}

You might also like