The C programming language was developed by Dennis Ritchie in 1972 at Bell Laboratories. It was designed as a system programming language for developing operating systems, specifically UNIX.
Example:
C was used to write the UNIX operating system, making it one of the most widely used programming languages.
A C program consists of functions, variables, and statements organized in a specific structure. The general structure of a C program is:
#includeint main() { // Variable declaration // Statements return 0; }
Components:
In C, functions are the fundamental building blocks that perform specific tasks. Functions enhance modularity and code reusability.
Example: #includevoid greet() { printf("Hello, World!"); } int main() { greet(); // Function call return 0; }
C programming has several fundamental components:
The character set includes letters, digits, and symbols that can be used in a C program.
Example:
Letters: A-Z, a-z
Digits: 0-9
Special Characters: +, -, *, /, %, #, etc.
Tokens are the smallest building blocks of a C program. Types of tokens include:
Example:
int a = 5; // Tokens: int, a, =, 5, ;
Keywords are reserved words with predefined meanings.
Example:
int, float, if, else, while, for, return
Identifiers are names given to variables, functions, or arrays by the programmer.
Rules:
1. Must start with a letter or underscore.
2. Cannot be a keyword.
3. Case-sensitive.
Example:
int age;
Variables: Named storage locations for data. Constants: Fixed values that do not change during program execution.
Example:
Variable: int age = 25;
Constant: const float PI = 3.14;
Data types specify the type of data a variable can hold.
Example:
int a = 10; // Integer
float b = 5.5; // Floating point
char c = 'A'; // Character
Comments are non-executable statements used to describe the code.
Example:
// This is a single-line comment
/* This is a
multi-line comment */
C provides various operators to perform operations on data. Types include:
Example:
int a = 5, b = 10;
int sum = a + b; // Arithmetic Operator
if (a > b) { // Relational Operator
printf("a is greater than b");
}
Precedence: Determines the order in which operators are evaluated.
Associativity: Determines the direction of evaluation (left-to-right or right-to-left).
Operators with higher precedence are evaluated first. Associativity resolves conflicts between operators with the same precedence.
Example:
Expression: 5 + 2 * 3
Evaluation: 5 + (2 * 3) = 11 (Multiplication has higher precedence than addition)
An expression is a combination of variables, operators, and constants that produce a value.
A statement is a single instruction executed by the program.
Example:
int a = 10; // Expression statement
if (a > 5) { // Control statement
printf("a is greater than 5");
}
C provides several built-in operators and functions for performing standard tasks.
Example:
printf("Enter a number: ");
scanf("%d", &a);
putchar('A');
Example:
char ch;
printf("Enter a character: ");
ch = getchar();
putchar(ch); // Prints the entered character
Header files contain declarations of functions and macros used in C programs. Common header files include:
Example: #include// Includes standard input/output library
Preprocessor directives are instructions processed before compilation. Common directives include:
Example: #include// Includes stdio.h #define PI 3.14 // Defines a constant
Decision-making structures allow a program to execute certain sections of code based on conditions.
The if statement executes a block of code if the condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
int a = 5;
if (a > 0) {
printf("a is positive");
}
The if-else statement executes one block of code if the condition is true, and another block if it is false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
int a = -5;
if (a > 0) {
printf("a is positive");
} else {
printf("a is negative");
}
Nested if-else allows decision-making within another if-else structure.
Example:
int a = 10;
if (a > 0) {
if (a % 2 == 0) {
printf("a is positive and even");
} else {
printf("a is positive and odd");
}
}
The switch statement selects one block of code to execute from multiple choices.
Syntax:
switch (expression) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no cases match
}
Example:
int day = 3;
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 3: printf("Wednesday"); break;
default: printf("Invalid day");
}
Loop control structures are used to repeat a block of code while a condition is true.
The while loop executes a block of code as long as the condition is true.
Syntax:
while (condition) {
// Code to execute
}
Example:
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
The do-while loop executes a block of code at least once before checking the condition.
Syntax:
do {
// Code to execute
} while (condition);
Example:
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
The for loop is used to execute a block of code a specific number of times.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
Nested for loops allow one loop inside another to handle multi-dimensional data or patterns.
Example:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
printf("i = %d, j = %d\n", i, j);
}
}
C includes other control statements for specific purposes:
Examples:
break:
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
printf("%d ", i); // Outputs: 1 2
}
continue:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
printf("%d ", i); // Outputs: 1 2 4 5
}
goto:
label:
printf("This is a label.");
goto label; // Infinite loop
exit:
if (condition) {
printf("Exiting program");
exit(0);
}
Problem solving is the process of identifying solutions to a given problem by understanding and analyzing it systematically.
Example:
Finding a lost key:
1. Trial and Error: Search one place at a time randomly.
2. Brainstorming: List all possible places and prioritize.
3. Divide and Conquer: Divide the area into sections and search systematically.
Example:
Problem: Calculate the area of a rectangle.
1. Define: Input length and breadth.
2. Analyze: Area = length × breadth.
3. Explore: Use a formula or program to compute.
Algorithm: A step-by-step procedure to solve a problem.
Flowchart: A graphical representation of an algorithm using symbols.
Example:
Algorithm:
1. Start
2. Input length and breadth
3. Calculate area = length × breadth
4. Print area
5. Stop
Flowchart:
(Start) → [Input length, breadth] → [Calculate area] → [Print area] → (End)
Conditionals use if-else or switch-case logic to execute specific code based on conditions.
Example:
Pseudo-code:
IF age >= 18 THEN
PRINT "Eligible to vote"
ELSE
PRINT "Not eligible"
END IF
Loops are used to repeat code while a condition is true.
Example:
Pseudo-code:
FOR i = 1 TO 5 DO
PRINT i
END FOR
Big-O notation describes the efficiency of an algorithm in terms of its execution time relative to the input size.
Example:
O(1): Accessing an array element
O(n): Traversing an array
O(n²): Nested loops
Task: Make tea
Algorithm:
1. Boil water
2. Add tea leaves
3. Add sugar and milk
4. Stir and boil
5. Strain into cup
Flowchart:
(Start) → [Boil water] → [Add ingredients] → [Stir and boil] → [Strain] → (End)
Addition and multiplication are fundamental arithmetic operations.
Example:
Input: a = 5, b = 3
Addition: sum = a + b = 8
Multiplication: product = a * b = 15
Algorithm:
1. Input the number.
2. If number > 0, print "Positive".
3. If number < 0, print "Negative".
4. If number % 2 == 0, print "Even"; else print "Odd".
Flowchart:
(Start) → [Input number] → [Check sign] → [Check even/odd] → (End)
Example:
Input: -4
Output: Negative, Even
Algorithm:
1. Input two numbers a and b.
2. If a > b, max = a; else max = b.
Example:
Input: a = 5, b = 3
Output: Maximum = 5
Algorithm:
1. Input three numbers a, b, c.
2. Compare a, b, c to find the largest.
Example:
Input: a = 3, b = 7, c = 5
Output: Maximum = 7
Algorithm:
1. Input n.
2. Sum = n * (n + 1) / 2.
Example:
Input: n = 5
Output: Sum = 15
Algorithm:
1. Input numbers in an array.
2. Sum all elements in the array.
Example:
Input: [1, 2, 3, 4, 5]
Output: Sum = 15
Algorithm:
1. Input dividend and divisor.
2. Compute quotient = dividend / divisor.
Example:
Input: dividend = 10, divisor = 3
Output: Quotient = 3
Algorithm:
1. Input number n.
2. Reverse the digits using a loop.
Example:
Input: n = 1234
Output: Reversed = 4321
Algorithm:
1. Input n.
2. Loop from 1 to 10, calculate n * i.
Example:
Input: n = 5
Output: 5, 10, 15, 20, ..., 50
Algorithm:
1. Input a, b.
2. Compute power using loop or pow(a, b).
Example:
Input: a = 2, b = 3
Output: 8
Algorithm:
1. Input n.
2. Multiply numbers from 1 to n.
Example:
Input: n = 5
Output: Factorial = 120
Algorithm:
1. Input angle x.
2. Calculate sine and cosine using series expansion.
Example:
Input: x = 30° (in radians)
Output: sin(x), cos(x)
Algorithm:
1. Input n and r.
2. Compute nCr = n! / (r! * (n-r)!).
Example:
Input: n = 5, r = 2
Output: nCr = 10
Algorithm:
1. Generate rows using combination formula.
Example:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Algorithm:
1. Input n.
2. Check if n is divisible only by 1 and itself.
Example:
Input: n = 7
Output: Prime
Algorithm:
1. Input n.
2. Find all numbers that divide n without a remainder.
Example:
Input: n = 12
Output: 1, 2, 3, 4, 6, 12
Algorithm:
1. Input n.
2. Check if the sum of its divisors equals n.
Example:
Input: n = 6
Output: Perfect Number
Algorithm:
1. Input two numbers.
2. Use Euclid's algorithm to find GCD.
Example:
Input: a = 54, b = 24
Output: GCD = 6
Algorithm:
1. Input a and b.
2. Swap using a third variable or arithmetic operations.
Example:
Input: a = 3, b = 5
Output: a = 5, b = 3
Functions are blocks of code designed to perform specific tasks and enhance reusability.
printf(),
scanf(), sqrt().
Example:
Library function: printf("Hello, World!");
User-defined function:
void greet() {
printf("Hello, User!");
}
Declaration: Specifies the function name, return type, and parameters without providing the body.
Definition: Specifies the body of the function and its implementation.
Syntax:
Declaration: return_type function_name(parameters);
Definition: return_type function_name(parameters) {
// Body of the function
}
Example:
Declaration: int add(int, int);
Definition: int add(int a, int b) {
return a + b;
}
A function call executes the code defined in a function. It can be:
Example:
int add(int a, int b);
int main() {
int sum = add(5, 3); // Function call
printf("Sum: %d", sum);
}
Functions can be classified based on return type and parameters:
void greet() { }int getNumber() { }void printSum(int, int) { }
int add(int, int) { }
Example:
void greet() {
printf("Hello!");
}
int add(int a, int b) {
return a + b;
}
In Call by Value, the function receives a copy of the variable's value.
Example:
void change(int x) {
x = 10; // Changes only the local copy
}
int main() {
int a = 5;
change(a);
printf("%d", a); // Output: 5
}
In Call by Reference, the function receives the variable's address, allowing modifications to the original value.
Example:
void change(int *x) {
*x = 10; // Changes the actual value
}
int main() {
int a = 5;
change(&a);
printf("%d", a); // Output: 10
}
Example:
int globalVar = 10; // Global scope
int main() {
int localVar = 5; // Local scope
}
Storage classes define the scope, lifetime, and visibility of variables.
Example:
void demo() {
static int count = 0; // Retains value between calls
count++;
printf("%d", count);
}
Recursion occurs when a function calls itself to solve smaller instances of the problem.
Example:
Factorial using recursion:
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
printf("Factorial: %d", factorial(5)); // Output: 120
}