Usually our program involves three main operations. The first one is the input operation that uses input functions such as scanf, getch(), gets(), getche(), getchar() and others. The second is the process operation. In this part of our program, we can see some equations that are calculated, conditions which are evaluated, and tasks being performed. The third part is the output operation. Here, we use output statement such as printf() function, puts(), putch(), putchar functions and other output statement functions. To learn this technique, we can jump right in and type our first program that involves these three main operations.
*** Example 1
Write a C program that calculates the sum of two input numbers, and display the result.
Algorithm:
Input | Enter two numbers (n1, n2) |
Process | Compute the sum (sum = n1 + n2) |
Output | Display the sum (sum) |
Solution:
Source code
--------------------------------------------------
#include <stdio.h>
main()
{
int n1, n2, sum;
clrscr();
printf("\n Enter 1st number: ");
scanf("%d", &n1);
printf("\n Enter 2nd number: ");
scanf("%d", &n2);
sum = n1 + n2;
printf("\n The sum is: %d", sum);
getch();
}
--------------------------------------------------
Output
Enter 1st number: 10
Enter 2nd number: 5
***Example 2The sum is: 15
Write a C program that calculates the Area of a sphere using this formula:
A = πr2 value of π is 3.1416.
Algorithm:
Input | Enter radius (r) |
Process | Compute the Area (A = Pi * (r * r)) |
Output | Display the Area (A) |
Solution:
Source code
--------------------------------------------------
#include <stdio.h>#define Pi 3.1416main(){float A, r;clrscr();printf("\n Enter value of radius: ");scanf("%f", &r);
A = Pi * (r * r);printf("\n The area of Sphere is: %f", A);getch();}
--------------------------------------------------
Output
Enter value of radius: 1The area of Sphere is: 3.1416
*** Example 3
Write a program that computes the average of three input quizzes, then display the result.
Algorithm:
Input | Enter three quizzes (q1, q2, q3) |
Process | Compute the average (ave = (q1 + q2 + q3)/3) |
Output | Display the average (ave) |
Solution:
Source code
--------------------------------------------------
#include <stdio.h>main(){int q1, q2, q3;float ave;clrscr();printf("\n Enter three quizzes: ");scanf("%d %d %d", &q1, &q2, &q3);ave = (q1 + q2 + q3)/3;printf("\n The average is: %f", ave);getch();}
--------------------------------------------------
Output
Enter three quizzes: 90 85 93The average is: 89.33
Programming Exercises
- Create a program that asks for a distance in kilometers (km) and converts it into its meters (m) equivalent.
- Write a program that converts the input Celsius degree into its equivalent Fahrenheit degree. Use the formula: F = (9/5) * C + 32
- Write a program the inputs two real numbers then exchanges their values.