30. Program that will calculate the sum of every third integer, beginning with i=2 (i.e., calculate the sum 2 + 5+ 8 + 11 + ...) for all values of i that are less than 100.
Chapter 6:
Looping Structures
Programming Exercise
Problem # 30:
Write a loop that will calculate the sum of every third integer, beginning with i=2 (i.e., calculate the sum 2 + 5+ 8 + 11 + ...) for all values of i that are less than 100. write the loop in each of the following ways:
(1) Using a for loop
(2) Using a do while loop
(3) Using a while loop
Solution:
Using a for loop:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i, sum=0;
for(i=2;i<=100;i+=3)
{
sum=sum+i;
}
cout<<"Sum is:"<<sum;
getch();
}
#include<conio.h>
using namespace std;
int main()
{
int i, sum=0;
for(i=2;i<=100;i+=3)
{
sum=sum+i;
}
cout<<"Sum is:"<<sum;
getch();
}
Using a while loop:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i=2, sum=0;
while(i<=100)
{
sum=sum+i;
i+=3;
}
cout<<"Sum is:"<<sum;
getch();
}
#include<conio.h>
using namespace std;
int main()
{
int i=2, sum=0;
while(i<=100)
{
sum=sum+i;
i+=3;
}
cout<<"Sum is:"<<sum;
getch();
}
Using a do while loop:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i=2, sum=0;
do
{
sum=sum+i;
i+=3;
}
while(i<=100);
cout<<"Sum is:"<<sum;
getch();
}
#include<conio.h>
using namespace std;
int main()
{
int i=2, sum=0;
do
{
sum=sum+i;
i+=3;
}
while(i<=100);
cout<<"Sum is:"<<sum;
getch();
}
Let me know in the comment section if you have any question.
Previous Post:
29. Program that could find whether the number entered is odd or even and whether it is prime or not. Before termination find the total number of odds, evens and primes entered.
Comments
Post a Comment