Introduction to C Programming
C is a powerful and popular programming language used to create software, operating
systems, and apps. It is known for its speed and efficiency.
1. Features of C
- Simple and fast
- Works on different computers
- Used for system programming (e.g., making operating systems)
- Allows low-level (hardware) access
- Has many libraries and functions
2. Structure of a C Program
A C program has the following parts:
- Preprocessor directives – Tells the compiler to include necessary files (e.g.,
#include<stdio.h>)
- Main function – The starting point of every C program (int main() {})
- Statements and expressions – The code that runs inside {}
- Return statement – Ends the main function (return 0;)
Example:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
3. Basic Data Types in C
- int – Stores whole numbers (e.g., 10, -5)
- float – Stores decimal numbers (e.g., 5.5, -3.14)
- char – Stores single characters (e.g., 'A', 'b')
- double – Stores larger decimal numbers
4. Variables and Constants
Variables store values that can change (e.g., int age = 20;)
Constants store fixed values (e.g., #define PI 3.14)
5. Operators in C
Arithmetic: +, -, *, /, %
Comparison: ==, !=, >, <, >=, <=
Logical: && (AND), || (OR), ! (NOT)
6. Control Statements
If Statement (Decision Making):
if (age > 18) {
printf("You are an adult.\n");
}
Loops (Repeating tasks):
For loop: Runs a fixed number of times
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
While loop: Runs until a condition is false
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
7. Functions in C
A function is a block of code that performs a task.
void greet() {
printf("Hello, welcome to C!\n");
}
int main() {
greet();
return 0;
}
8. Arrays in C
An array stores multiple values of the same type.
int numbers[5] = {1, 2, 3, 4, 5};
printf("First number: %d", numbers[0]);
9. Pointers in C
Pointers store memory addresses.
int a = 10;
int *ptr = &a;
printf("Value: %d", *ptr); // Prints 10
10. File Handling in C
C can read and write files.
FILE *fptr;
fptr = fopen("file.txt", "w");
fprintf(fptr, "Hello, File!\n");
fclose(fptr);
Conclusion
C is a strong language used in many areas, including systems programming and embedded
systems. Learning C helps understand how computers work at a deep level.