Lab Manual PPS

Program to find the value of y for a particular value of n.

Write a program to find the value of y for a particular value of n.
The a, x, b, n is input by user
if n=1 y=ax%b
if n=2 y=ax2+b2
if n=3 y=a-bx
if n=4 y=a+x/b

Code

#include <stdio.h>

int main()
{
    int a, b, x, n;
    float y;
    printf("Enter value of a: ");
    scanf("%d", &a);
    printf("Enter value of b: ");
    scanf("%d", &b);
    printf("Enter value of x: ");
    scanf("%d", &x);
    printf("Choose n from 1 to 4:");
    scanf("%d", &n);
    switch(n)
    {
        case 1: y=a*x%b;
                printf("%.2f", y);
                break;
        case 2: y=a*x*x+b*b;
                printf("%.2f", y);
                break;
        case 3: y=a-b*x;
                printf("%.2f", y);
                break;
        case 4: y=a+x/b;
                printf("%.2f", y);
                break;
        default : printf("your input is wrong, Please choose value from 1 to 4 for n.");
    }

    return 0;
}

Description

This is a C program that takes input values of a, b, x, and n from the user and calculates y based on the value of n using a switch statement.

Here’s a step-by-step breakdown of what the code does:

  1. The program includes the standard input/output library stdio.h.
  2. The program defines the main() function, which is the entry point of the program.
  3. The program declares four variables of integer and float data types, a, b, x, and y, and an integer variable n.
  4. The program prompts the user to enter the value of a using printf().
  5. The program reads the value of a entered by the user using scanf() and stores it in the variable a.
  6. The program prompts the user to enter the value of b using printf().
  7. The program reads the value of b entered by the user using scanf() and stores it in the variable b.
  8. The program prompts the user to enter the value of x using printf().
  9. The program reads the value of x entered by the user using scanf() and stores it in the variable x.
  10. The program prompts the user to enter a value of n between 1 and 4 using printf().
  11. The program reads the value of n entered by the user using scanf() and stores it in the variable n.
  12. The program uses a switch statement to calculate the value of y based on the value of n entered by the user.
  13. If n is 1, the program calculates y as a*x%b.
  14. If n is 2, the program calculates y as a*x*x+b*b.
  15. If n is 3, the program calculates y as a-b*x.
  16. If n is 4, the program calculates y as a+x/b.
  17. If the value of n entered by the user is not between 1 and 4, the program displays an error message using printf().
  18. The program displays the value of y using printf() with two decimal places.
  19. The program returns 0, which indicates successful completion of the main() function.

Output

Enter value of a: 2
Enter value of b: 4
Enter value of x: 12
Choose n from 1 to 4: 2
304.00