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

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;
}

        

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote