C is one of the most fundamental programming languages, widely used in system programming, embedded systems, and software development. Let's go through the basics of C programming step by step.
1. Introduction to C Programming
2. Setting Up Your Environment
To write and run a C program, you need:
✅ Compiler: GCC (Linux/macOS), MinGW (Windows), Turbo C, Dev-C++, Code::Blocks, etc.
✅ Editor: VS Code, Code::Blocks, Notepad++, etc.
✅ IDE (Optional): Code::Blocks, Dev-C++ (for easy compilation).
3. Structure of a C Program
A basic C program consists of:
#include <stdio.h> // Header file for input/output functions
int main() { // Entry point of the program
printf("Hello, World!\n"); // Output statement
return 0; // Indicates successful execution
}
Breakdown:
#include <stdio.h>→ Includes the standard input-output header file.int main()→ Main function where execution starts.{ }→ Curly braces indicate the beginning and end of a function.printf("Hello, World!\n");→ Prints output to the screen.return 0;→ Exits the program successfully.
4. Data Types in C
C supports different data types:
| Type | Size (Bytes) | Example |
|---|---|---|
int | 4 | int age = 25; |
float | 4 | float pi = 3.14; |
double | 8 | double price = 9.99; |
char | 1 | char grade = 'A'; |
void | - | void function(); (No return) |
#include <stdio.h>
int main() {
int age = 20;
float height = 5.8;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);
return 0;
}
5. Variables and Constants
A variable is a named memory location that holds data.
Syntax:
datatype variable_name = value;
int num = 10;
float pi = 3.14;
Constants
- A constant is a variable whose value cannot be changed.
- Using
constkeyword: - const int MAX = 100;
Using#define(Preprocessor Directive): - #define PI 3.1415
6. Input & Output in C
| Function | Purpose | Example |
|---|
printf() | Displays output | printf("Hello!"); |
scanf() | Takes user input | scanf("%d", &num); | | | | | |
Example Program: Taking User Input
#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old.\n", age);
return 0;
}
Note: & (Address-of Operator) is required in scanf() to store the input value in a variable.
7. Operators in C
| Operator Type | Example | Description |
|---|
| Arithmetic | + - * / % | Addition, Subtraction, Multiplication, Division, Modulus |
| Relational | == != > < >= <= | Comparison operators |
| Logical | `&& |
| Bitwise | `& | ^ ~ << >>` |
| Assignment | = += -= *= /= | Assign values |
| Increment/Decrement | ++ -- | Increase/Decrease by 1 |