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:
- The program includes the standard input/output library
stdio.h
. - The program defines the
main()
function, which is the entry point of the program. - The program declares four variables of integer and float data types,
a
,b
,x
, andy
, and an integer variablen
. - The program prompts the user to enter the value of
a
usingprintf()
. - The program reads the value of
a
entered by the user usingscanf()
and stores it in the variablea
. - The program prompts the user to enter the value of
b
usingprintf()
. - The program reads the value of
b
entered by the user usingscanf()
and stores it in the variableb
. - The program prompts the user to enter the value of
x
usingprintf()
. - The program reads the value of
x
entered by the user usingscanf()
and stores it in the variablex
. - The program prompts the user to enter a value of
n
between 1 and 4 usingprintf()
. - The program reads the value of
n
entered by the user usingscanf()
and stores it in the variablen
. - The program uses a
switch
statement to calculate the value ofy
based on the value ofn
entered by the user. - If
n
is 1, the program calculatesy
asa*x%b
. - If
n
is 2, the program calculatesy
asa*x*x+b*b
. - If
n
is 3, the program calculatesy
asa-b*x
. - If
n
is 4, the program calculatesy
asa+x/b
. - If the value of
n
entered by the user is not between 1 and 4, the program displays an error message usingprintf()
. - The program displays the value of
y
usingprintf()
with two decimal places. - 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