Introduction to C Programming
C is a general-purpose, high-level, procedural programming language developed by Dennis Ritchie in 1972 at Bell Laboratories. It is one of the oldest and most widely used programming languages, often referred to as the "mother of all modern languages."
Basic C Programming Structure
#include <stdio.h> // Preprocessor directive
int main() { // Main function
printf("Hello, World!"); // Print statement
return 0; // Exit code
}
The basic structure of a C program includes a preprocessor directive like #include <stdio.h> to include standard input-output functions. The main() function serves as the entry point of the program. Inside main(), statements like printf() display output to the console. The program ends with return 0;, which signals successful termination to the operating system.
C Program Building Blocks
-
Header Files
- Starts with
#include <filename> - Common headers:
stdio.h,math.h,string.h
- Starts with
-
Main Function
- Entry point of a C program:
int main()
- Entry point of a C program:
-
Statements and Semicolons
- Every statement ends with a semicolon
;
- Every statement ends with a semicolon
A C program is composed of several essential components. Header files like stdio.h or math.h are included at the beginning using the #include directive to provide access to standard functions. The main() function acts as the starting point for program execution. Inside the main function, you write statements that define what the program should do—each ending with a semicolon ; to indicate the end of that instruction.
Preprocessor Directives
| Directive | Purpose |
|---|---|
| #include | Add libraries |
| #define | Define constants/macros |
| #if, #else, #endif | Conditional compilation |
Preprocessor directives in C are instructions processed before actual compilation begins. They typically begin with a # symbol. For example, #include is used to add standard or user-defined libraries, #define creates constants or macros, and conditional directives like #if, #else, and #endif control which parts of the code are compiled based on specific conditions.
C Data Types
| Type | Size (Typical) | Description |
|---|---|---|
| int | 4 bytes | Integer value |
| float | 4 bytes | Decimal value |
| double | 8 bytes | Large decimal |
| char | 1 byte | Character value |
| void | 0 bytes | No Value |
Data types in C define the type of data a variable can hold. Each type specifies the memory size and the operations that can be performed on the data. Common types include int for integers, float and double for decimal numbers, char for single characters, and void to represent the absence of a value, typically used in functions that return nothing.
Variables and Constants
int age = 21;
float pi = 3.14;
const int MAX = 100; // Constant variable
In C, variables are used to store data that can change during program execution, while constants hold fixed values that cannot be altered once defined. Variables must be declared with a data type, such as int or float. Constants are declared using the const keyword to ensure their values remain unchanged.
Operators in C
- Arithmetic:
+,-,*,/,% - Relational:
==,!=,<,>,<=,>= - Logical:
&&,||,! - Assignment:
=,+=,-=, etc. - Increment/Decrement:
++,--
Operators in C are special symbols used to perform operations on variables and values. They are categorized based on the type of operation they perform. Arithmetic operators handle mathematical calculations, while relational operators compare values. Logical operators are used to combine conditions, and assignment operators assign or update values in variables. Increment and decrement operators are used to increase or decrease values by one.
Input and Output
#include <stdio.h> // Required for input/output functions
int main() {
int age;
scanf("%d", & age); // Input
printf("Age: %d", age); // Output
return 0;
}
In C, input and output operations are handled using functions from the <stdio.h> library. The scanf() function is used to take input from the user, and printf() is used to display output on the screen. Format specifiers like %d are used to indicate the type of data being handled, such as integers, floats, or characters.
Arrays in C
int nums[5] = {1, 2, 3, 4, 5};
printf("%d", nums[2]); // Output: 3
Arrays in C are used to store multiple values of the same data type in a single variable. Each element in an array is accessed using an index, starting from 0. For example, nums[2] accesses the third element in the array. Arrays must be declared with a fixed size, and values can be assigned at declaration or individually.
Conditional Statements
Conditional statements in C allow the program to take different actions based on whether a specified condition is true or false. Common conditional structures include if, if-else, if-else if, and switch. These statements enable decision-making, allowing your program to respond dynamically to different inputs or states during execution.
Simple if Statement
#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("Number is positive.\n");
}
return 0;
}
The if statement in C checks a condition and executes a block of code only if the condition is true. It is the most basic form of decision-making. In the example above, the program checks if the number is greater than 0 and prints a message if the condition is satisfied.
if-else Statement
#include <stdio.h>
int main() {
int number = -5;
if (number > 0) {
printf("Positive number\n");
} else {
printf("Not a positive number\n");
}
return 0;
}
The if-else statement in C provides two paths of execution: one if the condition is true and another if it is false. In the example above, if the number is greater than 0, it prints "Positive number", otherwise it prints "Not a positive number".
if-else if Statement
#include <stdio.h>
int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A\n");
} else if (marks >= 75) {
printf("Grade: B\n");
} else if (marks >= 60) {
printf("Grade: C\n");
} else {
printf("Grade: Fail\n");
}
return 0;
}
The if-else if statement allows multiple conditions to be checked in sequence. The program executes the first true condition it encounters. In this example, the code evaluates the student's marks and assigns a grade based on the score.
Nested if Statement
#include <stdio.h>
int main() {
int a, b, c;
// Input three numbers
printf("Enter three numbers:\n");
scanf("%d %d %d", & a, & b, & c);
// Nested if logic
if (a > b) {
if (a > c) {
printf("The greatest number is: %d\n", a);
} else {
printf("The greatest number is: %d\n", c);
}
} else {
if (b > c) {
printf("The greatest number is: %d\n", b);
} else {
printf("The greatest number is: %d\n", c);
}
}
return 0;
}
A nested if statement is an if statement placed inside another if or else block. This allows more complex decision-making by checking multiple levels of conditions. In the given example, the program compares three numbers and determines which one is the greatest by using nested if statements.
Loops in C programming
In C programming, loops are used to repeatedly execute a block of code as long as a specified condition is true. They help in reducing code redundancy and improving efficiency. The main types of loops in C are for, while, and do-while, each suited for different use cases depending on when and how often the condition is checked.
For Loop
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
The for loop in C is used when the number of iterations is known. It consists of three parts: initialization, condition, and increment/decrement. The loop executes the block of code repeatedly until the condition becomes false.
While Loop
int i = 0;
while (i < 5) {
printf("%d\n", i);
i++;
}
The while loop in C is used to execute a block of code as long as a specified condition is true. It checks the condition before executing the loop body, making it an entry-controlled loop.
Do-While Loop
int i = 0;
do {
printf("%d\n", i);
i++;
} while (i < 5);
The do-while loop in C is similar to the while loop, but the key difference is that the loop body executes at least once before the condition is checked. It is an exit-controlled loop.
Nested-for Loop
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
// inner loop body
}
}
A nested-for loop in C means having one for loop inside another. It is commonly used for working with multi-dimensional data, such as printing patterns or iterating through matrices. The outer loop controls the number of rows, and the inner loop handles the columns or repeated operations within each row.
User-Defined Functions in C
int add(int a, int b) {
return a + b;
}
// Function Call:
int result = add(5, 3);
User-defined functions in C allow programmers to break a large program into smaller, manageable sections. These functions are created by the user to perform specific tasks, improve code reusability, and make the program more organized and readable. A function typically includes a return type, function name, parameters, and a function body.
Pointers in C
int x = 10;
int *ptr = & x; // Pointer to x
printf("%d", *ptr); // Dereference pointer
Pointers in C are variables that store the memory address of another variable. They are powerful tools that allow direct memory access and manipulation. Using pointers, you can create dynamic data structures, pass large variables to functions efficiently, and manage memory manually. The * operator is used to access the value stored at the pointed address (dereferencing), while the & operator is used to get the address of a variable.
Strings in C
char name[] = "Waleed";
printf("Name: %s", name);
// String Functions (from <string.h>):
// strlen(), strcpy(), strcmp(), strcat()
Strings in C are arrays of characters terminated by a null character '\0'. They are used to store and manipulate text. C provides several standard library functions in <string.h> to work with strings, such as strlen() to find the length, strcpy() to copy, strcmp() to compare, and strcat() to concatenate strings.
File Handling in C
FILE *fp = fopen("file.txt", "w");
fprintf(fp, "Hello File");
fclose(fp);
File handling in C allows programs to read from and write to files using the standard I/O library <stdio.h>. The fopen() function opens a file, fprintf() writes formatted output to the file, and fclose() closes the file after operations are done. File handling is essential for data storage and retrieval in applications.
Math Functions (<math.h>)
- sqrt(x): Square root
- pow(x, y): x raised to y
- abs(x): Absolute value
The <math.h> library in C provides a range of mathematical functions to perform complex calculations. Commonly used functions include sqrt(x) for calculating the square root, pow(x, y) for raising a number to a power, and abs(x) for finding the absolute value. These functions make mathematical computations easier and more efficient in C programs.
Storage Classes in C
| Keyword | Description |
|---|---|
| auto | Default for local vars |
| register | Stored in register |
| static | Keeps value between calls |
| extern | Declared elsewhere |
In C programming, storage classes define the scope, lifetime, and visibility of variables. The auto keyword is the default for local variables, while register suggests storing the variable in a CPU register for faster access. The static keyword retains the value of a variable across multiple function calls. The extern keyword is used to declare a variable that is defined in another file or scope, enabling access to global variables across multiple files.
Sample Mini Program
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", & a, & b);
printf("Sum = %d", a + b);
return 0;
}
This is a simple C program that takes two integer inputs from the user and prints their sum. It uses the scanf() function to receive input and printf() to display the result. This example demonstrates basic input/output handling, arithmetic operation, and syntax of a complete C program.
Try running this program online: Programiz C Online Compiler
Click here to download Dev C++ Compiler.
Click to go back Home.
Comments
Comments in C are used to explain code, improve readability, or temporarily disable code from execution. They are ignored by the compiler. Single-line comments start with
//and are used for brief notes. Multi-line comments are wrapped between/*and*/and can span multiple lines.