Ternary operator Write a program that loops indefinitely. In each iteration of t
ID: 3857248 • Letter: T
Question
Ternary operator Write a program that loops indefinitely. In each iteration of the loop, read in an integer N (declared as an int) that is inputted by a user, output N/6 if N is nonnegative and divisible by 5, and -1 otherwise. Use the ternary operator (?:) to accomplish this. continue Modify the code from 3.4.1 so that if the condition fails, nothing is printed. Use an if and a continue command (instead of the ternary operator) to accomplish this. break Modify the code from 3.4.2 to let the user break out of the loop by entering -1 or any negative number. Before the program exits, output the string "Goodbye!".Explanation / Answer
3.4.1 : A C code below uses ternary operator to show the output :
#include<stdio.h>
int main(){
int n;
for(;;){ // for loop that loops indefinately
scanf("%d",&n); // scanning the user input
printf("%d",(n%5==0)?n/5 : -1); // use of ternary operation
}
return 0;
}
3.4.2 : A C code uses if condition and continue:
#include<stdio.h>
int main(){
int n;
for(;;){
scanf("%d",&n);
if(n%5!=0)
continue; // continue to the next iteration without printing anything
if(n%5==0)
printf("%d",n/5);
}
return 0;
}
3.4.3 : Use of break
#include<stdio.h>
int main(){
int n;
for(;;){
scanf("%d",&n);
if(n<0){
printf("Goodbye!");
break; // for negative numbers loop breaks
}
if(n%5!=0)
continue;
if(n%5==0)
printf("%d",n/5);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.