1/ Construct a while() loop, which computes the sum of all multiples of 7 and 8
ID: 641792 • Letter: 1
Question
1/ Construct a while() loop, which computes the sum of all multiples of 7 and 8 for numbers 1 - 500. Show all variable declarations.
2/ Construct a for() loop, which computes the sum of all multiples of 7 and 8 for numbers 1 - 500. Show all variable declarations.
3/ Construct a do-while() loop, which continues to prompt the user for an integer, and determines the sum of integers entered, until a prime number is encountered. The prime number should not be included in the sum. Show all variable declarations.
Explanation / Answer
1) int i = 1,sum=0;
while(i <= 500)
{
if(i%7== 0 || i%8==0)
{
sum += i;
}
i++;
}
2)
int sum =0;
for(int i = 1; i<= 500 ; i++)
{
if(i%7==0 || i%8==0)
sum += i;
}
3 )bool check(int num)
{
for(int i = 2; i< num/2; i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
int sum = 0, tempsum =0;
do{
sum = tempsum;
cin>>i;
tempsum+=i;
}while(check(i));
cout<<sum;
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.