C Program Module 2-4
C Program Module 2-4
Reading a Character:
1. Using getchar()
• getchar() reads a single character from standard input (usually the keyboard).
• It waits until the user presses the Enter key and returns the entered character as an int
(ASCII value).
Example:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar(); // Read a character
printf("You entered: ");
putchar(ch); // Display the character
return 0;
}
• getchar() can also read whitespace characters like spaces, tabs, and newlines.
2. Using scanf()
• scanf("%c", &ch) reads a single character from the input and stores it in the variable ch.
Example:
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
printf("You entered: %c\n", ch);
return 0;
}
Writing a Character:
1. Using putchar()
Example:
#include <stdio.h>
int main() {
char ch = 'A';
putchar(ch); // Output: A
return 0;
}
2. Using printf()
Example:
#include <stdio.h>
int main() {
char ch = 'B';
printf("Character: %c\n", ch);
return 0;
}
Formatted input and output functions allow structured reading and displaying of data:
• scanf() reads input based on format specifiers and stores the values in the corresponding
variables.
Example:
#include <stdio.h>
int main() {
int a;
float b;
char ch;
printf("Enter an integer, a float, and a character: ");
scanf("%d %f %c", &a, &b, &ch);
printf("You entered: %d, %.2f, %c\n", a, b, ch);
return 0;
}
Format Specifier Description Example
%d Integer 42
%f Float 3.14
%c Character A
%s String "Hello"
%lf Double 3.1415
Formatted Output using printf()
Example:
#include <stdio.h>
int main() {
int a = 42;
float b = 3.14;
char ch = 'X';
printf("Integer: %d\n", a);
printf("Float: %.2f\n", b);
printf("Character: %c\n", ch);
return 0;
}
Decision Making
1. If
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
#include <stdio.h>
int main() {
int num = 10;
if (num > 5) {
printf("Number is greater than 5\n");
}
return 0;
}
2. If-Else Statement
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
3. Else-If Ladder
Syntax:
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if no condition is true
}
Example:
int num = 0;
if (num > 0) {
printf("Positive");
} else if (num < 0) {
printf("Negative");
} else {
printf("Zero");
}
4. Switch Statement
Syntax:
switch(expression) {
case value1:
// Code
break;
case value2:
// Code
break;
default:
// Code
}
Example:
int day = 2;
switch(day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
default: printf("Invalid day");
}
5. Conditional Operator
Syntax:
Example:
int a = 10;
int b = (a > 5) ? 1 : 0;
printf("%d", b);
Loops
A loop is used to execute a block of code repeatedly as long as a specified condition is true.
Loops help reduce code repetition and make programs more efficient.
Types of Loops:
1. While Loop
2. Do-While Loop
3. For Loop
4. Nested Loops
While Loop
The while loop executes a block of code as long as the specified condition is true.
Syntax:
while (condition) {
// Code to execute
}
#include <stdio.h>
int main() {
int i = 1; // Initialization
while (i <= 5) { // Condition
printf("%d\n", i);
i++; // Update
}
return 0;
}
Output:
1
2
3
4
5
Do-While Loop
The do-while loop executes the loop body at least once and then checks the condition.
Syntax:
do {
// Code to execute
} while (condition);
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
return 0;
}
Output:
1
2
3
4
5
• The do-while loop executes at least once, even if the condition is false initially.
Example:
int x = 5;
do {
printf("Hello\n");
} while (x < 0);
For Loop
The for loop is used when the number of iterations is known beforehand.
Syntax:
• Condition – Evaluated before each iteration; if true, the loop executes; if false, the loop
stops.
#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
Output:
1
2
3
4
5
Example: Reverse counting using a for loop
#include <stdio.h>
int main() {
for (int i = 5; i >= 1; i--) {
printf("%d\n", i);
}
return 0;
}
Output:
5
4
3
2
1
Example: Increment by 2
#include <stdio.h>
int main() {
for (int i = 0; i <= 10; i += 2) {
printf("%d\n", i);
}
return 0;
}
Output:
0
2
4
6
8
10
Nested Loops
Syntax:
}
}
• For each iteration of the outer loop, the inner loop runs completely.
#include <stdio.h>
int main() {
int n = 5;
printf("\n");
return 0;
Jump Statements
Statement Description
break Exits the loop or switch statement immediately.
continue Skips the current iteration and jumps to the next.
goto Transfers control to a labeled statement.
Break Statement
Output:
1
2
Continue Statement
Output:
1
2
4
5
Goto Statement
Syntax:
goto label;
label:
// Code to execute
Example:
int i = 1;
start:
if (i <= 5) {
printf("%d\n", i);
i++;
goto start;
}
Output:
1
2
3
4
5
Unit -3
Arrays in C
One-Dimensional Array
A one-dimensional array stores a list of elements of the same data type in a single row or line.
data_type array_name[size];
Example:
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
array_name[i];
Example:
#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("%d\n", numbers[i]); // Access and display each element
}
return 0;
}
Output:
10
20
30
40
50
Two-Dimensional Array
A two-dimensional array is an array of arrays, used to store data in a tabular format (rows and
columns).
data_type array_name[rows][columns];
Example:
int matrix[3][4];
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 4;
• Syntax:
array_name[row][column];
Example:
#include <stdio.h>
int main() {
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
return 0;
}
Output:
1 2 3
4 5 6
7 8 9
Multi-Dimensional Arrays
data_type array_name[size1][size2][size3]...[sizeN];
Example:
• A 3D array of size 2 x 3 x 4:
int array[2][3][4];
Example:
int array[2][3][4] =
{
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
Example:
#include <stdio.h>
int main() {
int array[2][2][3] = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};
Dynamic Arrays in C
A dynamic array is an array whose size is determined during runtime. Unlike static arrays,
where the size is fixed at compile time, dynamic arrays allow for flexible memory allocation
and resizing based on the program’s requirements.
In C, dynamic memory allocation is managed using the following functions from the stdlib.h
library:
• If the size requirement is not known beforehand, dynamic arrays allow for adjusting the size
at runtime.
Strings in C
In C, a string is defined as an array of characters terminated by a null character ('\0'). The null
character marks the end of the string, allowing functions to identify where the string ends.
1. Declaring Strings
Syntax:
char str[size];
• size – Number of characters in the string including the null character ('\0')
Example 1:
Example 2:
Example 3:
Using a pointer:
Example:
#include <stdio.h>
int main() {
char name[20];
return 0;
}
Output:
Example:
#include <stdio.h>
int main() {
char name[50];
return 0;
}
Example:
#include <stdio.h>
int main() {
char name[50];
return 0;
}
Since characters are represented by ASCII values internally, they can be manipulated using
arithmetic operations.
#include <stdio.h>
int main() {
char c = 'A';
c = c + 1; // Increment ASCII value of 'A' (65) by 1
return 0;
}
int main() {
char c = 'D';
printf("%d\n", c - 'A'); // Output: 3
return 0;
}
4. Comparison of Strings
You cannot directly compare strings using == because strings are pointers to memory
locations.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
return 0;
}
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[20];
strcpy(str2, str1);
return 0;
}
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);
return 0;
}
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
char *pos = strchr(str, 'o');
if (pos != NULL) {
printf("Character found at position: %ld\n", pos - str);
} else {
printf("Character not found\n");
}
return 0;
}
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
char *pos = strstr(str, "World");
if (pos != NULL) {
printf("Substring found at position: %ld\n", pos - str);
} else {
printf("Substring not found\n");
}
return 0;
}
5.7 strrev() – Reverse a String (Not part of standard C, but can be implemented)
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
}
Function Description
strlen() Length of string
strcpy() Copy string
strcat() Concatenate strings
strcmp() Compare strings
strchr() Find character in string
strstr() Find substring
strrev() Reverse string (custom implementation)
Functions in C
Functions are reusable blocks of code designed to perform a specific task. They allow
programmers to break down complex problems into smaller, manageable parts, improving the
clarity, reusability, and efficiency of the code.
. Library functions
These functions are defined in the library of C compiler which are used frequently in the C
program.
Function Declaration
• Informs the compiler about the function name, return type, and parameters.
Function Definition
Function Call
Function Syntax:
return_type function_name(parameters) {
// Function body
}
Example:
#include <stdio.h>
// Function declaration
int add(int, int);
int main() {
int sum = add(5, 7); // Function call
printf("Sum: %d\n", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b; // Return statement
}
A function can return a value to the calling function using the return statement.
Return Types:
int getNumber() {
return 42;
}
char* getMessage() {
return "Hello, World!";
}
Function Declaration
• Informs the compiler about the function’s name, return type, and parameters.
Example:
Function Call
Example:
int sum = add(3, 5);
Call by Value
• Changes to the parameter within the function do not affect the original value.
Example:
#include <stdio.h>
void modifyValue(int a) {
a = 20;
}
int main() {
int x = 10;
modifyValue(x);
printf("%d\n", x); // Output: 10
return 0;
}
Call by Reference
• Changes to the parameter within the function affect the original value.
Example:
#include <stdio.h>
int main() {
int x = 10;
modifyValue(&x);
printf("%d\n", x); // Output: 20
return 0;
}
Categories of Functions
void display() {
printf("Hello");
}
int main() {
display();
return 0;
}
Example:
int main() {
greet("John");
return 0;
}
Example:
int getNumber() {
return 42;
}
int main() {
int num = getNumber();
printf("%d\n", num);
return 0;
}
int main() {
int result = sum(5, 3);
printf("%d\n", result);
return 0;
}
Nesting of Functions
Example:
#include <stdio.h>
int main() {
int result = sum(sum(2, 3), sum(4, 5));
printf("%d\n", result);
return 0;
}
Recursion
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
int main() {
printf("%d\n", factorial(5)); // Output: 120
return 0;
}
Command Line Arguments
Command line arguments allow passing input values when executing a program.
Example:
#include <stdio.h>
Execution:
Output:
Argument 0: ./program
Argument 1: Hello
Argument 2: World
Example:
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
In C, strings are arrays of characters terminated by '\0'. When passed to a function, the base
address of the string is passed, allowing direct access and modification of the original string.
Methods of Passing Strings
• Pass by Reference: Directly pass the string; changes will reflect in the original string.
Syntax
or
Examples
int main() {
char str[] = "Hello";
display(str);
}
Unit IV
Storage Classes in C
Storage classes in C define the scope, visibility, and lifetime of variables. They determine
how and where variables are stored, how long they persist, and how they are accessed.
1. auto
2. register
3. static
4. extern
• Lifetime: Created when the block is entered and destroyed when exited.
Example:
#include <stdio.h>
void example() {
auto int x = 10; // auto keyword is optional
printf("%d\n", x);
}
int main() {
example();
}
Output:
10
• Lifetime: Created when the block is entered and destroyed when exited.
• Storage: Stored in the CPU registers (if available) for faster access.
Example:
#include <stdio.h>
void example() {
register int x = 5;
printf("%d\n", x);
}
int main() {
example();
}
Output:
5
3. static Storage Class
Example:
#include <stdio.h>
void example() {
static int x = 0;
x++;
printf("%d\n", x);
}
int main() {
example(); // Output: 1
example(); // Output: 2
}
File 1: file1.c
#include <stdio.h>
int x = 10;
void display() {
printf("%d\n", x);
}
File 2: file2.c
#include <stdio.h>
int main() {
printf("%d\n", x);
}
Output:
10
Structure
A structure is a collection of variables of different data types grouped under a single name.
Defining a Structure
struct Student {
int id;
char name[50];
float marks;
};
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student s1;
[Link] = 101;
[Link] = 85.5;
strcpy([Link], "John");
Initialization of Structure
You cannot directly compare structures using ==. Use memcmp() or compare individual
members:
Array of Structures
Example:
#include <stdio.h>
struct Student {
int id;
char name[50];
};
int main() {
struct Student s[3] = {{101, "John"}, {102, "Alex"}, {103, "Mary"}};
return 0;
}
struct Student {
int id;
char name[50];
int marks[5];
};
struct Date {
int day;
int month;
int year;
};
struct Student {
int id;
char name[50];
struct Date dob;
};
Pass by Value:
Pass by Reference:
Union
A union allows storing different types of data in the same memory location. Memory is
shared by all members.
Defining a Union
union Data {
int i;
float f;
char str[20];
};
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
int main() {
union Data data;
data.i = 10;
printf("i = %d\n", data.i);
data.f = 220.5;
printf("f = %.2f\n", data.f);
strcpy([Link], "C Programming");
printf("str = %s\n", [Link]);
return 0;
}
Pointers in C
A pointer is a variable that stores the memory address of another variable. Instead of storing a
value directly, a pointer stores the location in memory where the value is stored.
Declaration
data_type *pointer_name;
Examples:
Initialization
You can assign the address of a variable to a pointer using the address-of operator (&):
int x = 10;
int *ptr = &x;
1. Direct Access:
int x = 10;
printf("%d", x);
Use the dereference operator (*) to access the value stored at the address:
int x = 10;
int *ptr = &x;
printf("%d", *ptr); // Output: 10
Pointer Expressions
You can perform arithmetic operations on pointers like addition and subtraction:
Pointer Addition:
Adding a value to a pointer increases its value by the size of the data type.
Pointer Subtraction:
Subtracting a value from a pointer decreases its value by the size of the data type.
ptr--;
printf("%d\n", *ptr); // Output: 10
The difference between two pointers gives the number of elements between them:
When you increment a pointer, it increases by the size of the data type:
Example:
An array name acts as a constant pointer to the first element of the array.
Pointer to Array:
int main() {
int arr[] = {10, 20, 30};
display(arr, 3);
}
Pass by Value:
void modify(int x) {
x = 20;
}
int main() {
int num = 10;
modify(num);
printf("%d", num); // Output: 10
}
Pass by Reference:
Passing the address using a pointer allows modification of the original value:
int* getPointer() {
static int x = 10;
return &x;
}
int main() {
int *ptr = getPointer();
printf("%d", *ptr); // Output: 10
}
Pointers can store the address of a structure and access members using -> operator.
Example:
#include <stdio.h>
struct Student {
int id;
char name[50];
};
int main() {
struct Student s1 = {101, "John"};
struct Student *ptr = &s1;
return 0;
}
#include <stdio.h>
struct Student {
int id;
char name[50];
};
int main() {
struct Student s1 = {101, "John"};
display(&s1);
return 0;
}
int x = 10;
int *ptr = &x;
int **pptr = &ptr;
Dynamic memory allocation in C allows programs to request and manage memory during
runtime, providing flexibility when the required memory size isn’t known at compile time.
• Purpose: Allocates a specified number of bytes and returns a pointer to the first byte of the
allocated memory.
• Details: The memory allocated by malloc() is uninitialized, meaning it may contain garbage
values. It’s essential to check if the allocation was successful by verifying that the returned
pointer is not NULL.
• Example:
• Details: Unlike malloc(), calloc() initializes the allocated memory to zero, ensuring that all
elements start with a known value.
• Example:
3. realloc() (Reallocation):
• Purpose: Resizes a previously allocated memory block, preserving its content up to the
lesser of the new and old sizes.
• Details: If the new size is larger, the additional memory is uninitialized. If the memory
block pointed to by ptr cannot be resized, realloc() allocates a new memory block, copies the
existing data to it, and frees the old block.
• Example:
4. free() (Deallocation):
• Details: It’s crucial to free dynamically allocated memory when it’s no longer needed to
prevent memory leaks, which can lead to increased memory usage and potential program
instability.
• Example:
free(ptr);
ptr = NULL; // Avoid dangling pointer
Exmple
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
// 1. Using malloc()
scanf("%d", &n1);
if (ptr == NULL) {
return 1;
ptr[i] = i + 1;
printf("\n");
scanf("%d", &n2);
// Reallocating memory
if (temp == NULL) {
return 1;
ptr = temp;
ptr[i] = i + 1;
}
// Displaying the elements after reallocation
printf("\n");
free(ptr);
return 0;