Hello. The code is correct until the summary. i do not know if it is correct. ca
ID: 3549943 • Letter: H
Question
Hello. The code is correct until the summary. i do not know if it is correct. can you please confirm i am right? The summary statement is
printf("Summary ");
printf("2: %d ", prod2);
printf("3: %d ", prod3);
printf("4: %d ", prod4);
return 0;
Below is the question given to us and my code:
Integer values are to be read from the keyboard. All values read are greater or equal to 1 except for a sentinel value of -1. Write a C program that reads these values and calculates the following products
product vales read that have a remainder of 2 when divided by 5
product vales read that have a remainder of 3 when divided by 5
product vales read that have a remainder of 4 when divided by 5
Your program prints a summary of these products. provide test results for 3,14,24,23,35,6,13,21,36,-1
Use a switch statement inside the sentinel controlled while loop that manages the input.
My code so far is
// Excercise 4 Part B
#include <stdio.h>
int main(){
printf("Excercise 4 (B) ");
printf("Enter integer that is greater than 0. Enter -1 to exit. ");
int x;
int prod2=1;
int prod3=1;
int prod4=1 ;
scanf("%d",&x);
while (x!=-1){
switch(x%5){
case 2:
prod2=prod2*x;
break;
case 3:
prod3=prod3*x;
break;
case 4:
prod4=prod4*x;
break;
}
printf("Enter integer that is greater than 0. Enter -1 to exit. ");
scanf("%d",&x);
}
printf("Summary ");
printf("2: %d ", prod2);
printf("3: %d ", prod3);
printf("4: %d ", prod4);
return 0;
}
after running the program the summary table give me
Case 2: 1
Case 3: 897
Case 4:336
Is the summary table coded properly? is this the correct answer?
Explanation / Answer
just before printing check the values of prod2 , prod3 and prod4 if any of them is 1 make it 0 since we did not find that
product. i,e,
#include <stdio.h>
int main(){
printf("Excercise 4 (B) ");
printf("Enter integer that is greater than 0. Enter -1 to exit. ");
int x;
int prod2=1;
int prod3=1;
int prod4=1 ;
scanf("%d",&x);
while (x!=-1){
switch(x%5){
case 2:
prod2=prod2*x;
break;
case 3:
prod3=prod3*x;
break;
case 4:
prod4=prod4*x;
break;
}
printf("Enter integer that is greater than 0. Enter -1 to exit. ");
scanf("%d",&x);
}
if (prod1==1)
prod1=0;
if (prod2==1)
prod2=0;
if (prod3==1)
prod3=0;
printf("Summary ");
printf("2: %d ", prod2);
printf("3: %d ", prod3);
printf("4: %d ", prod4);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.