5. Writing a Program in C (Lesson)
Writing your first Program in C
Now that we know the elements and operators, let's look at how to structure a program that interacts with the user.
6.1 Basic I/O: printf() and scanf()
printf() - Standard Output
Used to display information on the screen.
Syntax: printf("Format String", variables);
printf("The value of X is %d", x);
scanf() - Standard Input
Used to read input from the keyboard.
Syntax: scanf("Format Specifier", &variable_address);
scanf("%d", &age); // The '&' is the address-of operator
6.2 The Compilation Process (Revisited)
As we write more complex programs, it's important to understand what happens when you click "Compile":
- Preprocessing: Lines starting with
#are processed (headers included, macros replaced). - Compilation: C code is converted into Assembly Language.
- Assembly: Assembly code is converted into Machine Code (binary instructions).
- Linking: Multiple object files and libraries are linked together to create the final Executable File.
6.3 Standard Library Functions
C provides many built-in functions via header files:
stdio.h: Standard I/O (printf, scanf, fopen)math.h: Mathematical functions (sqrt, pow, sin)ctype.h: Character testing (isdigit, isalpha)string.h: String manipulation (strlen, strcpy)
6.4 Practical Example: Simple Interest Calculator
Let's write a program that takes user input to calculate Simple Interest.
#include <stdio.h>
int main() {
float principal, time, rate, si;
printf("--- Simple Interest Calculator ---\n");
printf("Enter Principal amount: ");
scanf("%f", &principal);
printf("Enter Time (in years): ");
scanf("%f", &time);
printf("Enter Rate of Interest: ");
scanf("%f", &rate);
// Calculation
si = (principal * time * rate) / 100;
printf("\nThe Simple Interest is: %.2f\n", si);
return 0;
}
Common Errors to Avoid:
- Missing Semicolon (
;): Every statement in C must end with a semicolon. - Missing
&inscanf(): Without the address-of operator,scanfdoesn't know where to store the data. - Wrong Format Specifier: Using
%dfor afloator%ffor anintwill result in garbage values.
Refer to the Lecture Slides for a diagram of the I/O buffer mechanism.