Lab Sheet 1
Review of Important Concepts in C
1. Loops in C
Loops execute a block of code repeatedly until a condition becomes false.
Types of Loops
In C, there are three types of loops: for loop, while loop, and do-while loop.
A. for Loop
Used when the number of iterations is known. It contains initialization, loop condition, and increment/decrement parts within the loop construct itself. In this loop, the loop condition is checked at the beginning.
Syntax:
for(initialization; condition; increment)
{
statements;
}
Example:
for(int i=1; i<=5; i++)
{
printf("%d\n", i);
}
B. while Loop
Checks the condition before execution. It checks the condition during the loop entry. The increment or decrement logic has to be placed inside the loop explicitly.
Example:
int i=1;
while(i<=5)
{
printf("%d\n", i);
i++;
}
C. do-while Loop
It is an exit-controlled loop. The loop condition is checked at the last part of the loop. So that the loop executes at least once.
Example:
int i=1;
do
{
printf("%d\n", i);
i++;
}
while(i<=5);
Applications
Menu-driven programs
Searching
Sorting
Repeated calculations
2. Nested Loops
A loop inside another loop is called a nested loop. Nested loops are required if a repetition is to be repeated itself.
Structure
for(...)
{
for(...)
{
statements;
}
}
Example
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
printf("* ");
}
printf("\n");
}
Output:
* * *
* * *
* * *
Applications
Pattern printing
Matrix operations
Multiplication tables
Example: Multiplication Table
for(int i=1;i<=5;i++)
{
for(int j=1;j<=10;j++)
{
printf("%4d", i*j);
}
printf("\n");
}
3. Functions in C
A function is a self-contained block of code that performs a specific task. Functions improve program organization, code reusability, readability, and maintainability.
Functions allow programmers to divide a large program into smaller modules. Each function can be developed and tested independently.
Advantages of Functions
Code reusability
Reduced program complexity
Easier debugging
Better maintainability
Supports modular programming
Syntax
return_type function_name(parameters)
{
// Function body
}
Types of Functions
Functions are categorized into Library Functions and User-Defined Functions based on the source of their definition and implementation.
Library Functions
printf()
scanf()
strlen()
User-defined Functions
Example
#include <stdio.h>
int add(int a, int b)
{
return a + b;
}
int main()
{
int result = add(5, 10);
printf("Sum = %d", result);
return 0;
}
Function Categories
The following are the function categories according to return values and arguments.
No arguments, no return value
Arguments, no return value
No arguments, return value
Arguments and return value
4. Recursion
Recursion is a process in which a function calls itself directly or indirectly.
Every recursive function must contain:
Recursive logic
Terminating condition
Not every problem can be solved recursively.
Advantages
Simplifies complex problems
Useful for tree and graph algorithms
Example: Factorial
Mathematical Formula:
n! = n × (n−1)!
Program:
#include <stdio.h>
int factorial(int n)
{
if(n==0)
return 1;
return n * factorial(n-1);
}
int main()
{
printf("%d", factorial(5));
return 0;
}
Recursion Process
factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 120
5. Arrays in C
An array is a collection of elements of the same data type stored in contiguous memory locations.
Advantages
Efficient storage of multiple values
Easy traversal
Supports sorting and searching
Syntax
data_type array_name[size];
Example:
int marks[5];
Initialization
int marks[5] = {10,20,30,40,50};
Accessing Elements
printf("%d", marks[2]);
Array Traversal
for(int i=0;i<5;i++)
{
printf("%d ", marks[i]);
}
Memory Representation
Index: 0 1 2 3 4
Value:10 20 30 40 50
6. Strings in C
A string is an array of characters terminated by a null character (\0).
Declaration
char name[20];
Initialization
char name[] = "Hello";
Memory:
H e l l o \0
Input and Output
scanf("%s", name);
printf("%s", name);
String Functions
The following are some of the string library functions.
strlen(): Length of string
strcpy(): Copy one string to another
strcat(): Concatenate two strings
strcmp(): Compare strings lexicographically
Example
#include <stdio.h>
#include <string.h>
int main()
{
char str[]="Programming";
printf("Length=%d", strlen(str));
return 0;
}
Output:
Length=11
7. Pointers
A pointer is a variable that stores the memory address of another variable.
Declaration
int *ptr;
Pointer Operators
The following are the operators related to pointers.
&: Address of
*: Value at address
Example
int x = 10;
int *ptr = &x;
printf("%d", *ptr);
Output:
10
Advantages
Dynamic memory allocation
Efficient array handling
Function parameter passing
Data structure implementation
8. Structures
A structure is a user-defined data type that groups different data types under one name.
Syntax
struct Student
{
int roll;
char name[20];
float marks;
};
Example
#include <stdio.h>
struct Student
{
int roll;
char name[20];
float marks;
};
int main()
{
struct Student s1;
s1.roll = 101;
s1.marks = 89.5;
printf("%d %.2f", s1.roll, s1.marks);
return 0;
}
Advantages
Organizes related data
Represents real-world entities
Foundation for advanced data structures
Array of Structures
struct Student s[3];
Useful for storing multiple structure-type records; students in the above.
9. File Handling in C
File handling enables permanent storage of data on secondary storage devices.
File Operations
Create
Open
Read
Write
Append
Close
File Pointer
FILE *fp;
Opening a File
fp = fopen("data.txt","w");
File Modes
The following are different file modes.
r: Read
w: Write
a: Append
r+: Read and Write
w+: Read and Write
a+: Read and Append
Writing to a File
Example
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("data.txt","w");
fprintf(fp,"Hello File");
fclose(fp);
return 0;
}
Reading from a File
char text[100];
fp = fopen("data.txt","r");
fgets(text,100,fp);
printf("%s", text);
fclose(fp);
Functions for File I/O
The following are some of the functions useful in reading from a file and writing into it.
fgetc(): Reads the next character from the specified file stream and advances the file pointer.
fputc(): Writes a single character to the specified file stream and advances the position indicator.
fgets(): Reads a line of string from the stream.
fputs(): Writes a null-terminated string to the specified file stream.
fscanf(): Reads formatted data from the file stream into specified variable addresses, similar to scanf().
fprintf(): Writes formatted text and data to the file stream, similar to printf().
fread(): Reads a specified number of elements, each of a specific byte size, from the file stream.
fwrite(): Writes a specified number of elements of a given byte size directly into the file stream.
Applications
Student management systems
Banking systems
Inventory systems
Database storage
Exercises
Write a program to calculate the sum of the following series, correct up to four decimal places. Make a user-defined function that calculates the sum of the following series and returns the value. Read the value of x in degrees, and pass it to your function that returns the sum.
sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...
Write a program to find the golden ratio correct up to four decimal places using the Fibonacci series. Create your own recursive function to return the next Fibonacci number.
Write a program to read the monthly expenditure of a company for a range of years specified by the user. Use an array to construct a table of expenditures and display it in that form. Calculate and display the following:
The total expenditure for each year.
The average monthly expenditure for each year.
The total expenditure for the entire range of years.
The average yearly expenditure in that range of years.
The average monthly expenditure over the entire range of years.
Write a program to find all positions of a character specified by the user in a sentence of text entered by the user using pointers and strings (character array).
Write a program to read and display the names of students and their obtained marks in programming using an array of structures. Display the list of students and marks obtained according to marks in descending order.
Write a program to read the name, roll number, address, and phone number of each student in your class using structures. Store the information in a file so that you can recover it later. Read the records back from the file, sort the records alphabetically by name, and display the sorted list.