In this program, we will show you how to write a simple C program that accepts three integers from the user and finds the maximum of them.
The program will use the following steps:
- Include the standard input/output header file 'stdio.h' to use the functions 'printf' and 'scanf'.
- Define the main function that will contain the logic of the program.
- Declare four integer variables: 'a', 'b', 'c', and 'max'. The first three will store the user input, and the last one will store the maximum value.
- Prompt the user to enter three integers using the 'printf' function.
- Read the user input using the 'scanf' function and store it in the variables 'a', 'b', and 'c'.
- Assign the value of a to 'max' as an initial guess.
- Compare 'b' with 'max' using the 'if' statement. If 'b' is greater than 'max', assign 'b' to 'max'.
- Compare 'c' with 'max' using another 'if' statement. If 'c' is greater than 'max', assign 'c' to 'max'.
- Print the value of 'max' using the 'printf' function.
- Return 0 from the main function to indicate successful execution.
The code for the program is given below:
int a, b, c, max;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
max = a;
if (b > max)
max = b;
if (c > max)
max = c;
printf("The maximum of three is %d\n", max);
You will see something like this:
Enter three integers: 10 20 15
The maximum of three is 20
you can try different inputs and see how the program works.
This program is a simple example of how to use C to perform basic arithmetic operations and comparisons. You can modify it to find the minimum of three integers, or sort them in ascending or descending order. You can also use loops and arrays to extend it to handle more than three integers.
We hope you enjoyed this tutorial and learned something new. If you have any questions or feedback, please leave a comment below. Thank you for reading!
We love your feedback and invite you to comment on our articles, exercises, examples, quizzes and others. Your feedback helps us make our content awesome and serve you better. Please leave a comment and tell us what you think. How did our content help you learn something new? Thank you for being a part of our community!
Post a Comment