Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q1/ Construct a while() loop which computes the sum of all prime numbers from 1

ID: 3528633 • Letter: Q

Question

Q1/ Construct a while() loop which computes the sum of all prime numbers from 1 - 100. Show all variable declarations. Q2/ Construct a for() loop which computes the sum of all prime numbers numbers from 1 - 100. Show all variable declarations. Q3/ Construct a do-while() loop which continues to prompt the user for a number, and adds the number to a total, until a negative value is encountered. The negative value should not be included in the sum. The min and max numbers of all numbers entered, should also be stored. Once again, the negative number is not part of the min or max. Show all variable declarations.

Explanation / Answer

//*****************************************

//Q1:Construct a while() loop which computes the sum of all prime numbers from 1 - 100.
//Show all variable declarationsConstruct a while() loop which computes the sum of all prime numbers from 1 - 100.
//Show all variable declarations


#include<stdio.h>


int main(){


int i=1,j, sum=0,prime;


while(i<=100){


prime =1;//assume is prime


if(i<2) //2 is first prime number

prime=0;


for (j=2;j<i;j++){

if(i%j==0){//not prime

prime=0;

break; //break from for j loop

}//end if

}//end for j


if(prime==1)

sum+=i;

i++;

}//end while


printf(" Sum of prime numbers from 1 to 100: %d",sum);

return 0;

}//end main


//*****************************************

//Q1:Construct a for() loop which computes the sum of all prime numbers numbers from 1 - 100.
// Show all variable declarations.


#include<stdio.h>


int main(){


int i=1,j, sum=0,prime;


while(for i=1; i<=100;i++){


prime =1;//assume is prime


if(i<2) //2 is first prime number

prime=0;


for (j=2;j<i;j++){

if(i%j==0){//not prime

prime=0;

break; //break from for j loop

}//end if

}//end for j


if(prime==1)

sum+=i;

}//end for


printf(" Sum of prime numbers from 1 to 100: %d",sum);

return 0;

}//end main

//*****************************************

//Q3/ Construct a do-while() loop which continues to prompt the user for a number, and adds the number to
// a total, until a negative value is encountered. The negative value should not be included in the sum.
//The min and max numbers of all numbers entered, should also be stored. Once again, the negative number is not
//part of the min or max. Show all variable declarations.

#include<stdio.h>


int main(){

int sum=0,min=999999,max=-999999,num;

do{

scanf("%d",&num);

if(num>=0){ //if positive

sum+=num; //add to sum


if(num>max)

max=num;

if(num<min)

min=num;

}

}while(num>=0);


printf("Sum of positive numbers: %d ",sum);

printf("Min: %d Max: %d",min,max);

return 0;

}