0% found this document useful (0 votes)
3 views124 pages

C Operators and Programming Examples

The document provides a comprehensive overview of various operators and programming problems in C, categorized into arithmetic, relational, logical, bitwise, assignment, increment/decrement, ternary, sizeof, pointer, member access, comma, and conditional compilation operators. It includes practical programming problems that demonstrate the use of these operators, as well as control structures like selection, loop, and jump statements. Each section contains example code snippets to illustrate the concepts discussed.

Uploaded by

etech608
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views124 pages

C Operators and Programming Examples

The document provides a comprehensive overview of various operators and programming problems in C, categorized into arithmetic, relational, logical, bitwise, assignment, increment/decrement, ternary, sizeof, pointer, member access, comma, and conditional compilation operators. It includes practical programming problems that demonstrate the use of these operators, as well as control structures like selection, loop, and jump statements. Each section contains example code snippets to illustrate the concepts discussed.

Uploaded by

etech608
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter-I: List of the operators and programs based on the operator

List of operator defini on:

A. Arithme c Operators: Perform basic arithme c opera ons like addi on, subtrac on,
mul plica on, and division.
+ (Addi on)
- (Subtrac on)
* (Mul plica on)
/ (Division)
B. Rela onal Operators: Compare values and determine rela onships between them.
> (Greater than)
< (Less than)
== (Equal to)
!= (Not equal to)
C. Logical Operators: Perform logical opera ons on boolean values.
&& (Logical AND)
|| (Logical OR)
! (Logical NOT)
D. Bitwise Operators: Perform opera ons at the bit level.
& (Bitwise AND)
| (Bitwise OR)
^ (Bitwise XOR)
~ (Bitwise NOT)
<< (Le shi )
>> (Right shi )
E. Assignment Operators: Assign values to variables and perform an opera on in the same
step.
= (Assignment)
+= (Add and assign)
-= (Subtract and assign)
*= (Mul ply and assign)
/= (Divide and assign)
%= (Modulo and assign)
F. Increment and Decrement Operators: Increase or decrease the value of a variable by one.
++ (Increment)
-- (Decrement)
G. Ternary Operator: A shorthand way to write an if-else statement in a single line.

condi on ? expression_if_true : expression_if_false

H. Sizeof Operator: Determine the size, in bytes, of a data type or variable.

sizeof

I. Pointer Operators: Used with pointers for dereferencing and address retrieval.

* (Pointer dereference)

& (Address-of)

J. Member Access Operator: Access members of a structure or union through a pointer.

->
K. Comma Operator: Separate expressions within a larger expression and return the value of
the last expression.
,
L. Bitwise Shi Operators: Perform bitwise shi s to the le or right.

<< (Le shi )

>> (Right shi )

M. Logical NOT Operator: Perform logical nega on.

N. Condi onal Compila on Operator: Used in preprocessor direc ves for condi onal
compila on.

# (Used in preprocessor direc ves)

Note: proper usage of these operators, along with an understanding of operator


precedence, will help you write efficient and effec ve C code.

1. Problem: Arithme c Opera ons


Problem Statement: Write a C program that takes two numbers as input and performs
arithme c opera ons (addi on, subtrac on, mul plica on, division) on them.

#include <stdio.h>

int main() {
double num1, num2;

prin ("Enter two numbers: ");


scanf("%lf %lf", &num1, &num2);

prin ("Sum: %lf\n", num1 + num2);


prin ("Difference: %lf\n", num1 - num2);
prin ("Product: %lf\n", num1 * num2);

if (num2 != 0) {
prin ("Division: %lf\n", num1 / num2);
} else {
prin ("Cannot divide by zero.\n");
}

return 0;
}

2. Problem: Rela onal Operators


Problem Statement: Write a C program that takes two integers as input and checks
whether the first number is greater than, less than, or equal to the second number.

#include <stdio.h>
int main() {
int num1, num2;

prin ("Enter two integers: ");


scanf("%d %d", &num1, &num2);

if (num1 > num2) {


prin ("%d is greater than %d\n", num1, num2);
} else if (num1 < num2) {
prin ("%d is less than %d\n", num1, num2);
} else {
prin ("%d is equal to %d\n", num1, num2);
}

return 0;
}

3. Problem: Logical Operators


Problem Statement: Write a C program that takes a number as input and checks whether it
is divisible by both 3 and 5.

#include <stdio.h>

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

if (num % 3 == 0 && num % 5 == 0) {


prin ("%d is divisible by both 3 and 5.\n", num);
} else {
prin ("%d is not divisible by both 3 and 5.\n", num);
}

return 0;
}

4. Problem: Bitwise Operators


Problem Statement: Write a C program that takes an integer as input and prints its binary
representa on.

#include <stdio.h>

void printBinary(int num) {


for (int i = sizeof(int) * 8 - 1; i >= 0; --i) {
if (num & (1 << i)) {
prin ("1");
} else {
prin ("0");
}
}
prin ("\n");
}

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

prin ("Binary representa on: ");


printBinary(num);

return 0;
}

5. Problem: Assignment Operators


Problem Statement: Write a C program that takes an integer as input and increases it by 10
using assignment operators.

#include <stdio.h>

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

num += 10;

prin ("A er adding 10: %d\n", num);

return 0;
}

6. Problem: Increment and Decrement Operators


Problem Statement: Write a C program that takes an integer as input and prints its value
before and a er incremen ng and decremen ng.

#include <stdio.h>

int main() {
int num;
prin ("Enter an integer: ");
scanf("%d", &num);

prin ("Original value: %d\n", num);

num++;
prin ("A er incremen ng: %d\n", num);

num--;
prin ("A er decremen ng: %d\n", num);

return 0;
}

7. Problem: Ternary Operator


Problem Statement: Write a C program that takes an integer as input and prints whether it
is posi ve, nega ve, or zero using the ternary operator.

#include <stdio.h>

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

(num > 0) ? prin ("Posi ve\n") : ((num < 0) ? prin ("Nega ve\n") : prin ("Zero\n"));

return 0;
}

8. Problem: Bitwise Shi Operators


Problem Statement: Write a C program that takes an integer as input and performs le and
right shi s on its binary representa on.

#include <stdio.h>

void printBinary(int num) {


for (int i = sizeof(int) * 8 - 1; i >= 0; --i) {
if (num & (1 << i)) {
prin ("1");
} else {
prin ("0");
}
}
prin ("\n");
}

int main() {
int num;
prin ("Enter an integer: ");
scanf("%d", &num);

prin ("Binary representa on before le shi : ");


printBinary(num);

int le Shi ed = num << 1;


prin ("A er le shi : ");
printBinary(le Shi ed);

int rightShi ed = num >> 1;


prin ("A er right shi : ");
printBinary(rightShi ed);

return 0;
}

9. Problem: Sizeof Operator


Problem Statement: Write a C program that demonstrates the use of the sizeof operator to
determine the sizes of different data types.

#include <stdio.h>

int main() {
prin ("Size of int: %lu bytes\n", sizeof(int));
prin ("Size of char: %lu bytes\n", sizeof(char));
prin ("Size of float: %lu bytes\n", sizeof(float));
prin ("Size of double: %lu bytes\n", sizeof(double));

return 0;
}

10. Problem: Operator Precedence


Problem Statement: Write a C program that takes three integers as input and evaluates the
expression (a + b) * c using proper operator precedence.

#include <stdio.h>

int main() {
int a, b, c;

prin ("Enter three integers: ");


scanf("%d %d %d", &a, &b, &c);

int result = (a + b) * c;
prin ("(%d + %d) * %d = %d\n", a, b, c, result);

return 0;
}

Chapter-II: simple C programming problems to familiar with the working


environment, input/output statements, and basic programming concepts.
1. Problem: Print "Hello, World!"
Problem Statement: Write a C program that prints "Hello, World!" to the console.

#include <stdio.h>

int main() {
prin ("Hello, World!\n");
return 0;
}

2. Problem: Add Two Numbers


Problem Statement: Write a C program that takes two integers as input and prints their
sum.
#include <stdio.h>

int main() {
int num1, num2;

prin ("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

int sum = num1 + num2;

prin ("Sum: %d\n", sum);

return 0;
}

3. Problem: Calculate Area of a Rectangle


Problem Statement: Write a C program to calculate and print the area of a rectangle given
its length and width.

#include <stdio.h>

int main() {
double length, width;

prin ("Enter length and width of the rectangle: ");


scanf("%lf %lf", &length, &width);

double area = length * width;

prin ("Area: %lf\n", area);

return 0;
}

4. Problem: Convert Celsius to Fahrenheit


Problem Statement: Write a C program that converts a temperature in Celsius to
Fahrenheit.

#include <stdio.h>

int main() {
double celsius, fahrenheit;

prin ("Enter temperature in Celsius: ");


scanf("%lf", &celsius);

fahrenheit = (celsius * 9 / 5) + 32;

prin ("Temperature in Fahrenheit: %lf\n", fahrenheit);

return 0;
}

5. Problem: Swap Two Numbers


Problem Statement: Write a C program to swap the values of two variables without using a
temporary variable.

#include <stdio.h>

int main() {
int num1, num2;

prin ("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

// Swapping without a temporary variable


num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;

prin ("A er swapping:\n");


prin ("Number 1: %d\n", num1);
prin ("Number 2: %d\n", num2);

return 0;
}

6. Problem: Calculate Simple Interest


Problem Statement: Write a C program to calculate the simple interest given the principal
amount, rate of interest, and me.

#include <stdio.h>

int main() {
double principal, rate, me, interest;

prin ("Enter principal amount: ");


scanf("%lf", &principal);

prin ("Enter rate of interest: ");


scanf("%lf", &rate);

prin ("Enter me (in years): ");


scanf("%lf", & me);

interest = (principal * rate * me) / 100.0;

prin ("Simple Interest: %lf\n", interest);


return 0;
}

7. Problem: Check Even or Odd


Problem Statement: Write a C program that takes an integer as input and checks whether
it is even or odd.

#include <stdio.h>

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

if (num % 2 == 0) {
prin ("%d is even.\n", num);
} else {
prin ("%d is odd.\n", num);
}

return 0;
}

8. Problem: Calculate Factorial


Problem Statement: Write a C program to calculate the factorial of a posi ve integer.

#include <stdio.h>

int main() {
int num;

prin ("Enter a posi ve integer: ");


scanf("%d", &num);

int factorial = 1;
for (int i = 1; i <= num; ++i) {
factorial *= i;
}

prin ("Factorial of %d: %d\n", num, factorial);

return 0;
}
9. Problem: Generate Fibonacci Series
Problem Statement: Write a C program to generate the Fibonacci series up to a given
number of terms.

#include <stdio.h>

int main() {
int num_terms;

prin ("Enter the number of terms: ");


scanf("%d", &num_terms);

int term1 = 0, term2 = 1;

prin ("Fibonacci Series:\n");


for (int i = 1; i <= num_terms; ++i) {
prin ("%d, ", term1);
int next_term = term1 + term2;
term1 = term2;
term2 = next_term;
}

prin ("\n");

return 0;
}

10. Problem: Calculate Power


Problem Statement: Write a C program to calculate the result of raising a number to a
given posi ve integer exponent.

#include <stdio.h>

double power(double base, int exponent) {


double result = 1.0;
for (int i = 0; i < exponent; ++i) {
result *= base;
}
return result;
}

int main() {
double base;
int exponent;

prin ("Enter the base: ");


scanf("%lf", &base);

prin ("Enter the exponent: ");


scanf("%d", &exponent);
double result = power(base, exponent);

prin ("%lf raised to the power of %d is %lf\n", base, exponent, result);

return 0;
}

Chapter-III: Programs using Control Structures


Control structures are programming constructs that are used to control the flow of execution in a
C program. They allow a programmer to specify conditions that determine which statements are
executed and which are skipped, to loop through statements until a condition is met, or to jump
to a different part of the program.

There are three main types of control structures in C:

Selection statements allow the programmer to decide based on a condition. The most
common selection statements in C are the if statement and the switch statement.
Loop statements allow the programmer to execute a block of statements repeatedly
until a condition is met. The most common loop statements in C are the for loop, the
while loop, and the do-while loop.
Jump statements allow the programmer to transfer control to a different part of the
program. The most common jump statements in C are the break, continue, and goto
statements.
Control structures are essential for writing efficient and readable C programs. They
allow the programmer to control the flow of execution clearly and easy to understand.

Here are some examples of control structures in C:


When not to
Statement Definition Merits Demerits When to use use
When you
Evaluates a need to
condition and execute
executes a block When you multiple
of statements if Simple and need to make a statements if
the condition is easy to decision based the condition
if true. understand. Can be nested. on a condition. is true.
Evaluates a
condition and
executes one
block of When you
statements if the need to make a When you
condition is true, decision based only need to
and another on a condition execute one
block of and execute block of
statements if the More flexible different statements if
condition is than if statements for the condition
if-else false. statement. Can be nested. each outcome. is true.
Evaluates a
variable against
a set of cases and
executes the Can be used
block of to handle
statements multiple When you When the
associated with Easy to read conditions need to handle
number of
the matching and with a single multiple conditions is
switch case. understand. statement. conditions. large.
When you do
Can be used When you not know the
Executes a block to execute a need to execute number of
of statements block of a block of times the block
repeatedly until a statements a statements a of statements
specified fixed number fixed number needs to be
for condition is met. Easy to use. of times. of times. executed.
Can be used
to execute a When you
block of Can be need to execute
When the code
A for loop statements difficult to a block of is difficult to
within another multiple read and statements read and
nested for for loop. times. understand. multiple times.
understand.
When the
Can be used When you do block of
Executes a block to execute a not know the statements
of statements block of number of should not be
repeatedly as statements an times the block executed an
long as a indefinite of statements indefinite
specified number of needs to be number of
while condition is met. Flexible. times. executed. times.
Executes a block Guarantees Can be When you When you do
do-while of statements that the block difficult to need to make not need to
repeatedly as of statements read and sure that the make sure that
long as a will be understand. block of the block of
specified executed at statements is statements is
condition is met, least once. executed at executed at
but the condition least once. least once.
is checked at the
end of the block.
When you
need to skip
Can be used When you over a section
Terminates the to exit a loop Can be used need to exit a of code, but
current loop or or switch to skip over a loop or switch you do not
switch statement section of statement know where
break statement. early. code. early. the code ends.
When you
need to jump
to a specific
Can be used Can be Should not be point in the
Transfers control to jump to a difficult to used unless code, and there
to a specified specific point read and absolutely is no other
goto label. in the code. understand. necessary. way to do it.
When you
Can be used need to skip When you
Continues with to skip over Can be over the need to
the next iteration the current difficult to current execute all
of the current iteration of a read and iteration of a iterations of a
continue loop. loop. understand. loop. loop.

a. If Statements:
1. Program 1: Check Even or Odd
Problem: Write a program that takes an integer as input and prints whether it's even or
odd.
#include <stdio.h>

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

if (num % 2 == 0) {
prin ("%d is even.\n", num);
} else {
prin ("%d is odd.\n", num);
}

return 0;
}
2. Program 2: Determine Leap Year
Problem: Write a program that checks if a given year is a leap year or not.

#include <stdio.h>

int main() {
int year;

prin ("Enter a year: ");


scanf("%d", &year);

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


prin ("%d is a leap year.\n", year);
} else {
prin ("%d is not a leap year.\n", year);
}

return 0;
}

3. Program 3: Find Maximum of Three Numbers


Problem: Write a program that takes three numbers as input and prints the maximum
of the three.

#include <stdio.h>

int main() {
int num1, num2, num3;

prin ("Enter three numbers: ");


scanf("%d %d %d", &num1, &num2, &num3);

int max = num1;

if (num2 > max) {


max = num2;
}
if (num3 > max) {
max = num3;
}

prin ("Maximum number: %d\n", max);

return 0;
}
4. Program 4: Check for Vowel or Consonant
Problem: Write a program that checks if a given character is a vowel or a consonant.

#include <stdio.h>

int main() {
char ch;

prin ("Enter a character: ");


scanf(" %c", &ch);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||


ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
prin ("%c is a vowel.\n", ch);
} else {
prin ("%c is a consonant.\n", ch);
}

return 0;
}

5. Program 5: Check Posi ve, Nega ve, or Zero


Problem: Write a program that determines whether a given number is posi ve,
nega ve, or zero.

#include <stdio.h>

int main() {
int num;

prin ("Enter a number: ");


scanf("%d", &num);

if (num > 0) {
prin ("%d is posi ve.\n", num);
} else if (num < 0) {
prin ("%d is nega ve.\n", num);
} else {
prin ("The number is zero.\n");
}

return 0;
}
b. If-Else Statements:
1. Program 1: Determine Greater Number
Problem: Write a program that takes two numbers as input and prints the greater one.

#include <stdio.h>

int main() {
int num1, num2;

prin ("Enter two numbers: ");


scanf("%d %d", &num1, &num2);

if (num1 > num2) {


prin ("%d is greater.\n", num1);
} else if (num2 > num1) {
prin ("%d is greater.\n", num2);
} else {
prin ("Both numbers are equal.\n");
}

return 0;
}

2. Program 2: Determine Grade


Problem: Write a program that takes a student's score as input and prints their grade using
if-else if-else ladder.

#include <stdio.h>

int main() {
int score;

prin ("Enter the student's score: ");


scanf("%d", &score);

if (score >= 90) {


prin ("Grade: A\n");
} else if (score >= 80) {
prin ("Grade: B\n");
} else if (score >= 70) {
prin ("Grade: C\n");
} else if (score >= 60) {
prin ("Grade: D\n");
} else {
prin ("Grade: F\n");
}

return 0;
}
3. Program 3: Calculate Discount
Problem: Write a program that calculates the final price of an item a er applying a
discount based on its cost.

#include <stdio.h>

int main() {
float cost, discount, finalPrice;

prin ("Enter the cost of the item: ");


scanf("%f", &cost);

if (cost >= 1000) {


discount = 0.1 * cost; // 10% discount for cost >= 1000
} else {
discount = 0.05 * cost; // 5% discount for cost < 1000
}

finalPrice = cost - discount;

prin ("Final price a er discount: %.2f\n", finalPrice);

return 0;
}

4. Program 4: Determine Quadrant of a Point


Problem: Write a program that takes the coordinates (x, y) of a point and determines
which quadrant it belongs to.
#include <stdio.h>

int main() {
int x, y;

prin ("Enter the coordinates (x, y): ");


scanf("%d %d", &x, &y);

if (x > 0 && y > 0) {


prin ("The point is in the first quadrant.\n");
} else if (x < 0 && y > 0) {
prin ("The point is in the second quadrant.\n");
} else if (x < 0 && y < 0) {
prin ("The point is in the third quadrant.\n");
} else if (x > 0 && y < 0) {
prin ("The point is in the fourth quadrant.\n");
} else {
prin ("The point is on an axis.\n");
}

return 0;
}

5. Program 5: Check for Valid Triangle


Problem: Write a program that takes the lengths of three sides of a triangle and
determines whether it's a valid triangle or not.

#include <stdio.h>

int main() {
float side1, side2, side3;

prin ("Enter the lengths of three sides of a triangle: ");


scanf("%f %f %f", &side1, &side2, &side3);

if (side1 + side2 > side3 && side2 + side3 > side1 && side3 + side1 > side2) {
prin ("It's a valid triangle.\n");
} else {
prin ("It's not a valid triangle.\n");
}

return 0;
}

c. Switch Statements:
1. Program 1: Menu-Driven Calculator
Problem: Write a program that implements a menu-driven calculator using a switch
statement.

#include <stdio.h>

int main() {
int choice;
float num1, num2, result;

prin ("Menu-Driven Calculator\n");


prin ("1. Addi on\n");
prin ("2. Subtrac on\n");
prin ("3. Mul plica on\n");
prin ("4. Division\n");
prin ("Enter your choice: ");
scanf("%d", &choice);

prin ("Enter two numbers: ");


scanf("%f %f", &num1, &num2);

switch (choice) {
case 1:
result = num1 + num2;
prin ("Sum: %.2f\n", result);
break;
case 2:
result = num1 - num2;
prin ("Difference: %.2f\n", result);
break;
case 3:
result = num1 * num2;
prin ("Product: %.2f\n", result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
prin ("Quo ent: %.2f\n", result);
} else {
prin ("Division by zero is not allowed.\n");
}
break;
default:
prin ("Invalid choice!\n");
}

return 0;
}

2. Program 2: Convert Number to Words


Problem: Write a program that takes a number (1 to 7) and converts it to the
corresponding day of the week using a switch statement.

#include <stdio.h>

int main() {
int day;

prin ("Enter a number (1 to 7): ");


scanf("%d", &day);

switch (day) {
case 1:
prin ("Sunday\n");
break;
case 2:
prin ("Monday\n");
break;
case 3:
prin ("Tuesday\n");
break;
case 4:
prin ("Wednesday\n");
break;
case 5:
prin ("Thursday\n");
break;
case 6:
prin ("Friday\n");
break;
case 7:
prin ("Saturday\n");
break;
default:
prin ("Invalid input! Please enter a number between 1 and 7.\n");
}

return 0;
}

3. Program 3: Grade System with Default


Problem: Write a program that takes a score as input and prints the corresponding grade
using a switch statement with a default case.

#include <stdio.h>

int main() {

int score;

prin ("Enter the student's score: ");

scanf("%d", &score);

switch (score / 10) {

case 10:

case 9:

prin ("Grade: A\n");

break;

case 8:

prin ("Grade: B\n");

break;

case 7:

prin ("Grade: C\n");

break;

case 6:

prin ("Grade: D\n");

break;

default:
prin ("Grade: F\n");

return 0;

4. Program 4: Find ASCII Value of a Character


Problem: Write a program that takes a character as input and prints its ASCII value using a
switch statement.

#include <stdio.h>

int main() {
char ch;

prin ("Enter a character: ");


scanf(" %c", &ch);

switch (ch) {
case 'A':
case 'a':
prin ("ASCII value of %c is %d\n", ch, (int)ch);
break;
case 'Z':
case 'z':
prin ("ASCII value of %c is %d\n", ch, (int)ch);
break;
default:
prin ("Character %c is not 'A' or 'Z'.\n", ch);
}

return 0;
}

5. Program 5: Evaluate Day of the Week


Problem: Write a program that takes a day number (1 to 366) as input and determines the
day of the week (Sunday to Saturday) for that day using a switch statement.

#include <stdio.h>

int main() {
int dayNumber;

prin ("Enter a day number (1 to 366): ");


scanf("%d", &dayNumber);
int dayOfWeek = (dayNumber - 1) % 7;

switch (dayOfWeek) {
case 0:
prin ("Sunday\n");
break;
case 1:
prin ("Monday\n");
break;
case 2:
prin ("Tuesday\n");
break;
case 3:
prin ("Wednesday\n");
break;
case 4:
prin ("Thursday\n");
break;
case 5:
prin ("Friday\n");
break;
case 6:
prin ("Saturday\n");
break;
default:
prin ("Invalid day number.\n");
}

return 0;
}

d. For Loops:
1. Program 1: Print Numbers from 1 to N
Problem: Write a program that takes an integer N as input and prints all numbers from 1 to
N using a for loop.
#include <stdio.h>

int main() {
int N;

prin ("Enter a posi ve integer N: ");


scanf("%d", &N);

prin ("Numbers from 1 to %d:\n", N);


for (int i = 1; i <= N; i++) {
prin ("%d\n", i);
}

return 0;
}
2. Program 2: Calculate Sum of First N Natural Numbers
Problem: Write a program that calculates and prints the sum of the first N natural numbers
using a for loop.

#include <stdio.h>

int main() {
int N, sum = 0;

prin ("Enter a posi ve integer N: ");


scanf("%d", &N);

for (int i = 1; i <= N; i++) {


sum += i;
}

prin ("Sum of first %d natural numbers: %d\n", N, sum);

return 0;
}

3. Program 3: Print Mul plica on Table


Problem: Write a program that takes an integer as input and prints its mul plica on
table from 1 to 10 using a for loop.

#include <stdio.h>

int main() {
int num;

prin ("Enter an integer: ");


scanf("%d", &num);

prin ("Mul plica on Table for %d:\n", num);


for (int i = 1; i <= 10; i++) {
prin ("%d x %d = %d\n", num, i, num * i);
}

return 0;
}

4. Program 4: Calculate Factorial of a Number


Problem: Write a program that calculates and prints the factorial of a posi ve integer N
using a for loop.

#include <stdio.h>

int main() {
int N;
long long factorial = 1;

prin ("Enter a posi ve integer N: ");


scanf("%d", &N);

for (int i = 1; i <= N; i++) {


factorial *= i;
}

prin ("Factorial of %d = %lld\n", N, factorial);

return 0;
}

5. Program 5: Check Prime Number


Problem: Write a program that checks whether a given integer is prime or not using a for loop.

#include <stdio.h>

int main() {
int num, isPrime = 1; // Assume the number is prime ini ally

prin ("Enter an integer: ");


scanf("%d", &num);

if (num <= 1) {
isPrime = 0; // Numbers less than or equal to 1 are not prime
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0; // It's not prime if there's a factor
break;
}
}
}

if (isPrime) {
prin ("%d is a prime number.\n", num);
} else {
prin ("%d is not a prime number.\n", num);
}

return 0;
}
e. Nested For Loops:
1. Program 1: Print a Pa ern (Half Pyramid)
Problem: Write a program that prints a half pyramid pa ern of asterisks (*) using
nested for loops.

#include <stdio.h>

int main() {
int rows;

prin ("Enter the number of rows: ");


scanf("%d", &rows);

prin ("Half Pyramid Pa ern:\n");


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
prin ("* ");
}
prin ("\n");
}

return 0;
}

2. Program 2: Print a Pa ern (Inverted Half Pyramid)


Problem: Write a program that prints an inverted half pyramid pa ern of asterisks (*) using
nested for loops.

#include <stdio.h>

int main() {
int rows;

prin ("Enter the number of rows: ");


scanf("%d", &rows);

prin ("Inverted Half Pyramid Pa ern:\n");


for (int i = rows; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
prin ("* ");
}
prin ("\n");
}

return 0;
}
3. Program 3: Print a Pa ern (Right Triangle) Problem: Write a program that prints a
right triangle pa ern of asterisks (*) using nested for loops.

#include <stdio.h>

int main() {
int rows;

prin ("Enter the number of rows: ");


scanf("%d", &rows);

prin ("Right Triangle Pa ern:\n");


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
prin ("* ");
}
prin ("\n");
}

return 0;
}

4. Program 4: Print a Pa ern (Number Pyramid)


Problem: Write a program that prints a number pyramid pa ern using nested for
loops.

#include <stdio.h>

int main() {
int rows;

prin ("Enter the number of rows: ");


scanf("%d", &rows);

prin ("Number Pyramid Pa ern:\n");


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
prin (" "); // Print spaces
}
for (int k = 1; k <= i; k++) {
prin ("%d ", k); // Print numbers
}
prin ("\n");
}

return 0;
}
5. Program 5: Print a Pa ern (Diamond)
Problem: Write a program that prints a diamond pa ern of asterisks (*) using
nested for loops.

#include <stdio.h>

int main() {
int rows, spaces;

prin ("Enter the number of rows: ");


scanf("%d", &rows);

spaces = rows - 1;

prin ("Diamond Pa ern:\n");


for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= spaces; j++) {
prin (" "); // Print spaces
}
for (int k = 1; k <= 2 * i - 1; k++) {
prin ("* "); // Print asterisks
}
prin ("\n");
spaces--;
}

spaces = 1;
for (int i = 1; i <= rows - 1; i++) {
for (int j = 1; j <= spaces; j++) {
prin (" "); // Print spaces
}
for (int k = 1; k <= 2 * (rows - i) - 1; k++) {
prin ("* "); // Print asterisks
}
prin ("\n");
spaces++;
}

return 0;
}
f. While and Do-While Loops:
1. Program 1: Sum of Digits using While Loop
Problem: Write a program that calculates the sum of the digits of a posi ve integer
using a while loop.

#include <stdio.h>

int main() {
int num, digit, sum = 0;

prin ("Enter a posi ve integer: ");


scanf("%d", &num);

while (num > 0) {


digit = num % 10;
sum += digit;
num /= 10;
}

prin ("Sum of digits: %d\n", sum);

return 0;
}

2. Program 2: Reverse a Number using Do-While Loop


Problem: Write a program that reverses a posi ve integer using a do-while loop.

#include <stdio.h>

int main() {
int num, reversedNum = 0, digit;

prin ("Enter a posi ve integer: ");


scanf("%d", &num);

do {
digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
} while (num != 0);

prin ("Reversed number: %d\n", reversedNum);

return 0;
}
3. Program 3: Calculate Factorial using While Loop
Problem: Write a program that calculates and prints the factorial of a posi ve integer
using a while loop.

#include <stdio.h>

int main() {
int num, fact = 1, i = 1;

prin ("Enter a posi ve integer: ");


scanf("%d", &num);

while (i <= num) {


fact *= i;
i++;
}

prin ("Factorial of %d is %d\n", num, fact);

return 0;
}

4. Program 4: Generate Fibonacci Series


Problem: Write a program that generates and prints the Fibonacci series up to a specified
number of terms using a while loop.

#include <stdio.h>

int main() {
int terms, first = 0, second = 1, next, i = 0;

prin ("Enter the number of terms: ");


scanf("%d", &terms);

prin ("Fibonacci Series:\n");

while (i < terms) {


if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
prin ("%d ", next);
i++;
}

prin ("\n");
return 0;
}

5. Program 5: Check Palindrome using Do-While Loop


Problem: Write a program that checks if a posi ve integer is a palindrome using a do-while
loop.
#include <stdio.h>

int main() {
int num, originalNum, reversedNum = 0, digit;

prin ("Enter a posi ve integer: ");


scanf("%d", &num);

originalNum = num;

do {
digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
} while (num != 0);

if (originalNum == reversedNum) {
prin ("%d is a palindrome.\n", originalNum);
} else {
prin ("%d is not a palindrome.\n", originalNum);
}

return 0;
}

g. Break Statements:
1. Program 1: Find Prime Numbers within a Range Problem: Write a program that finds
and prints prime numbers within a specified range using a for loop and the break
statement.
#include <stdio.h>

int main() {
int start, end;

prin ("Enter the range (start and end): ");


scanf("%d %d", &start, &end);

prin ("Prime numbers between %d and %d:\n", start, end);

for (int num = start; num <= end; num++) {


int isPrime = 1; // Assume the number is prime ini ally

if (num <= 1) {
isPrime = 0; // Numbers less than or equal to 1 are not prime
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = 0; // It's not prime if there's a factor
break; // Exit the inner loop.
}
}
}

if (isPrime) {
prin ("%d ", num);
}
}

prin ("\n");

return 0;
}

2. Program 2: Break a Loop with User Input


Problem: Write a program that takes a series of integers as input from the user and
breaks the loop when the user enters a nega ve number.

#include <stdio.h>

int main() {
int num;

prin ("Enter a series of integers (enter a nega ve number to stop):\n");

while (1) {
scanf("%d", &num);

if (num < 0) {
break; // Exit the loop when a nega ve number is entered
}

// Process the input


prin ("You entered: %d\n", num);
}

prin ("Loop terminated.\n");

return 0;
}
h. Goto Statements:
1. Program 1: Use Goto to Exit Loop
Problem: Write a program that demonstrates the use of the goto statement to exit
a loop when a specific condi on is met. In this case, exit the loop when the sum of
integers from 1 to n exceeds 100.

#include <stdio.h>

int main() {
int n, sum = 0, i = 1;

prin ("Enter a posi ve integer (n): ");


scanf("%d", &n);

while (i <= n) {
sum += i;
if (sum > 100) {
goto exit_loop;
}
i++;
}

exit_loop:
prin ("Sum exceeded 100. Current sum: %d\n", sum);

return 0;
}

i. Con nue Statements:


1. Program 1: Skip Odd Numbers using Con nue.
Problem: Write a program that uses a for loop to print all even numbers between 1
and 20, skipping odd numbers using the con nue statement.

#include <stdio.h>

int main() {
prin ("Even numbers between 1 and 20 (skipping odd numbers):\n");
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0) {
con nue; // Skip odd numbers
}
prin ("%d\n", i);
}

return 0;
}
2. Program: Print Mul ples of 5
Problem Statement: Write a program that uses a loop to print all mul ples of 5
between 1 and 50, skipping numbers that are not mul ples of 5.

#include <stdio.h>

int main() {
prin ("Mul ples of 5 between 1 and 50:\n");
for (int i = 1; i <= 50; i++) {
if (i % 5 != 0) {
con nue; // Skip numbers that are not mul ples of 5
}
prin ("%d\n", i);
}

return 0;
}

3. Program: Print Even Numbers with Con nue


Problem Statement: Write a program that uses a loop to print all even numbers
between 1 and 20, skipping odd numbers using the con nue statement.

#include <stdio.h>

int main() {
prin ("Even numbers between 1 and 20 (skipping odd numbers):\n");
for (int i = 1; i <= 20; i++) {
if (i % 2 != 0) {
con nue; // Skip odd numbers
}
prin ("%d\n", i);
}

return 0;
}

4. Program: Print Numbers Skipping 3 and 7


Problem Statement: Write a program that uses a loop to print numbers from 1
to 10, but skips prin ng the numbers 3 and 7 using the con nue statement.

#include <stdio.h>

int main() {
prin ("Numbers from 1 to 10 (skipping 3 and 7):\n");
for (int i = 1; i <= 10; i++) {
if (i == 3 || i == 7) {
con nue; // Skip numbers 3 and 7
}
prin ("%d\n", i);
}
return 0;
}

5. Program: Skip Nega ve Numbers


Problem Statement: Write a program that reads a series of integers from the
user and prints them, but skips prin ng any nega ve numbers using the
con nue statement. The loop con nues un l the user enters 0.

#include <stdio.h>

int main() {
int num;

prin ("Enter a series of integers (enter 0 to stop):\n");

while (1) {
scanf("%d", &num);

if (num == 0) {
break; // Exit the loop when the user enters 0
}

if (num < 0) {
con nue; // Skip nega ve numbers
}

prin ("You entered: %d\n", num);


}

prin ("Loop terminated.\n");

return 0;
}

Chapter-IV: Programs using Concept of loops


A loop is a fundamental programming concept that allows a set of instructions to
be executed repeatedly based on a condition or a specific number of iterations.
Loops are essential for automating repetitive tasks and for processing data
efficiently.
There are two primary types of loops:
Pre-Test Loop (while loop and for loop): In a pre-test loop, the condition is
evaluated before the loop body is executed. If the condition is initially false, the
loop body may not execute at all.
Example: Event-Controlled Loop (while loop):
int i = 0;
while (i < 5) {
printf("Iteration %d\n", i);
i++;
}

In this example, the loop continues if the condition i < 5 is true.


Counter-Controlled Loop (for loop):
for (int i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
In this example, the loop executes exactly five times because the counter variable
i is used to control the number of iterations.
Post-Test Loop (do-while loop):
int i = 0;
do {
printf("Iteration %d\n", i);
i++;
} while (i < 5);
In this example, the loop body executes at least once because the condition is
checked after the first iteration.

Chapter-IV: Understanding Functions


In programming, a function is a self-contained block of code that performs a
specific task or operation. Functions are used to modularize code, improve code
readability, and facilitate code reuse. They play a crucial role in structuring
programs and breaking down complex tasks into manageable pieces.

A subfunction (or subroutine) is a term often used interchangeably with a


function. In many programming languages, a function can also be referred to as
a method, procedure, or subroutine.
Functions generally have the following components:

 Function Name: A unique identifier for the function.


 Parameters (or Arguments): Values that can be passed to the function
for it to work with. Parameters are optional, and a function can have
none or multiple parameters.
 Return Type: The data type of the value that the function can return
after its execution. Functions can return values, or they can be void (no
return value).
 Function Body: The actual code that performs the task or computation.
 Function Call: A statement in your program that invokes or calls the
function, passing any required arguments.

Example program on function call:


#include <stdio.h>

// Function declaration (prototype)


int add(int a, int b);

int main() {
int x = 5, y = 7;
int result = add(x, y); // Function call
printf("Sum: %d\n", result);
return 0;
}

// Function definition
int add(int a, int b) {
return a + b;
}

In this example:

 add is the function name.


 int is the return type; the function returns an integer.
 (int a, int b) are the parameters; the function expects two integer
arguments.
 The function body calculates the sum of the two integers and returns the
result.
A subclass is a concept used in object-oriented programming (OOP) and typically
associated with classes, not functions. In OOP, a class can inherit properties and
methods from another class, creating a parent-child relationship. The child class
is often referred to as a subclass, and the parent class as a superclass. Subclasses
inherit attributes and behaviours (functions or methods) from their superclass.
(The following are not included in our syllabus)

OOP, or Object-Oriented Programming, is a programming paradigm that uses objects


as the fundamental building blocks of a program. It is based on the concept of "objects,"
which are instances of classes, and it emphasizes the organization of code into reusable,
self-contained units.

In OOP, data and the functions that operate on that data are grouped together into
objects, allowing for a more structured and modular approach to software development.
Here are some key concepts and principles of OOP:

1. Classes and Objects: A class is a blueprint or template for creating objects. It


defines the structure and behavior of objects. An object is an instance of a class,
and it represents a specific entity with its own data (attributes) and methods
(functions).
2. Encapsulation: Encapsulation is the concept of bundling data (attributes) and
the methods that operate on that data into a single unit (object or class). It hides
the internal details of how an object works, exposing only what's necessary for
external use. Access to the object's data is controlled through methods.
3. Inheritance: Inheritance allows one class (subclass or derived class) to inherit the
properties and behaviors of another class (superclass or base class). It promotes
code reuse and the creation of a hierarchy of classes.
4. Polymorphism: Polymorphism allows objects of different classes to be treated as
objects of a common superclass. It enables methods to be defined in a generic
way, so they can work with objects of multiple classes.
5. Abstraction: Abstraction is the process of simplifying complex reality by
modeling classes based on the essential attributes and behaviours. It allows
developers to focus on what an object does rather than how it does it.
6. Message Passing: In OOP, objects communicate by sending messages to each
other. A message typically consists of a method call on an object, and it triggers
the execution of the corresponding method.
7. Modularity: OOP promotes modular code organization, making it easier to
manage and maintain large software systems. Each class encapsulates a specific
part of the program's functionality.

OOP languages, such as C++, Java, Python, and C#, are designed to facilitate these
concepts and principles. Developers use classes and objects to model real-world entities
and solve problems in a way that mirrors the real world. OOP is widely used in software
development due to its ability to improve code organization, maintainability, and
reusability.
A. Basic Func on:
Program: A simple func on that adds two numbers and returns the result.

#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {
int result = add(5, 7); // Func on call
prin ("Sum: %d\n", result);
return 0;
}

Explana on: This program defines a basic func on add that takes two integers as parameters
and returns their sum. The func on is called in the main func on, and the result is printed.

B. Void Func on:


Program: A void func on that prints a message without returning a value.
#include <stdio.h>

void greet() {
prin ("Hello, World!\n");
}

int main() {
greet(); // Func on call
return 0;
}

Explana on: This program defines a void func on greet that prints a gree ng message. The
func on is called in the main func on.

C. Func on with Mul ple Parameters:


Program: A func on that calculates the average of three numbers.
#include <stdio.h>

float average(float a, float b, float c) {


return (a + b + c) / 3.0;
}

int main() {
float result = average(5.0, 7.5, 8.2); // Func on call
prin ("Average: %.2f\n", result);
return 0;
}
Explana on: This program defines a func on average that takes three floa ng-point numbers
as parameters and returns their average. The func on is called in the main func on.

D. Recursive Func on:


Program: A recursive func on to calculate the factorial of a number.
#include <stdio.h>

int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}

int main() {
int result = factorial(5); // Func on call
prin ("Factorial: %d\n", result);
return 0;
}

Explana on: This program defines a recursive func on factorial that calculates the factorial
of a non-nega ve integer. The func on calls itself with a smaller argument un l it reaches
the base case.
E. Func on Pointer:
Program: A func on with default arguments to calculate the power of a number.
#include <stdio.h>

double power(double base, int exponent) {


double result = 1.0;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}

int main() {
double result1 = power(2.0, 3); // Func on call with specified exponent
double result2 = power(2.0, 2); // Default exponent is 2
prin ("Result 1: %.2f\n", result1);
prin ("Result 2: %.2f\n", result2);
return 0;
}
Explana on: This program defines a func on power to calculate the power of a number. It
uses a default exponent value of 2 if not specified.
F. Variadic Func on:
Variadic func ons are func ons that can take a variable number of arguments. In C
programming, a variadic func on adds flexibility to the program. It takes one fixed
argument and then any number of arguments can be passed.
Chapter-V: Array
An array in C is a data structure that allows you to store a collection of elements
of the same data type under a single variable name. Each element in an array is
identified by an index, and arrays provide an efficient way to store and access
multiple values of the same type in a contiguous block of memory. Arrays are
commonly used for tasks like storing lists of data, processing data in a structured
manner, and implementing data structures like matrices and vectors.
There are several types of arrays in C:
One-Dimensional Array: A one-dimensional array is a simple list of elements
of the same data type. Elements in a one-dimensional array are accessed using a
single index.
For example:
int numbers[5]; // An array of 5 integers
Two-Dimensional Array: A two-dimensional array is an array of arrays. It's used
to represent tables or matrices with rows and columns. Elements in a two-
dimensional array are accessed using two indices (row and column).
For example:
int matrix[3][3]; // A 3x3 integer matrix
Multi-Dimensional Array: C allows you to create arrays with more than two
dimensions, known as multi-dimensional arrays. These are used for applications
like representing 3D data or higher-dimensional data. Accessing elements
requires specifying multiple indices.
For example:
int cube[2][3][4]; // A 3D array
Character Array (String): A character array is a one-dimensional array of
characters. It is commonly used to store and manipulate strings in C. Strings in C
are null-terminated, meaning they end with a null character '\0'.
For example:
char name[20]; // A character array to store a name
Dynamic Array: In C, arrays have a fixed size determined at compile time.
However, dynamic arrays are implemented using pointers and dynamic memory
allocation functions like malloc() and realloc(). These arrays can grow or shrink
during runtime as needed.
For example:
int* dynamicArray = NULL; // Dynamic array of integers
Jagged Array (Array of Pointers): A jagged array is an array in which each
element is itself an array. Unlike a true two-dimensional array, the sub-arrays can
have different lengths.
For example:
int* rows[3]; // An array of integer pointers, creating a jagged array

Problem 1: Find the Maximum Element in an Array


Problem Statement: Write a C program to find the maximum element in an array
of integers.
Solution:
#include <stdio.h>

int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);

int max = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}

printf("Maximum element in the array: %d\n", max);

return 0;
}
Explanation: In this program, we initialize an array of integers and find the
maximum element by iterating through the array. We start by assuming that the
first element is the maximum and compare it with the other elements. If we find
an element greater than the current maximum, we update the maximum.
Practice 01: Do the above program to get the user input for the array element
count and the element also from the user :
#include <stdio.h>

int main() {
int n;

// Ask the user for the number of elements


printf("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n];

// Ask the user to enter the elements


printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

int max = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}

printf("The maximum value in the array is %d\n", max);


return 0;
}
Explanation:
a) int n;
a. Declares an integer variable n to store the number of elements
in the array.
b) printf("Enter the number of elements in the array: ");
a. Prompts the user to enter the number of elements.
c) scanf("%d", &n);
a. Reads the number of elements entered by the user and stores it
in n.
d) int arr[n];
a. Declares an array arr with n elements. This uses variable-length
array (VLA) feature in C.
e) printf("Enter the elements of the array:\n");
a. Prompts the user to enter the elements of the array.
f) for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); }
a. A for loop that iterates from 0 to n-1, reading each element
entered by the user and storing it in the array arr.
g) int max = arr[0];
a. Initializes the variable max with the value of the first element of
the array.
h) for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } }
a. Iterates through the array starting from the second element,
updating max if a larger element is found.
i) printf("The maximum value in the array is %d\n", max);
a. Prints the maximum value found in the array.

Problem 2: Calculate the Sum of Array Elements


Problem Statement: Write a C program to calculate the sum of elements in an
array of integers.
Solution:
#include <stdio.h>

int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);

int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}

printf("Sum of array elements: %d\n", sum);

return 0;
}
Explanation: This program calculates the sum of array elements by iterating
through the array and adding each element to the sum variable.

Problem 3: Reverse an Array


Problem Statement: Write a C program to reverse an array of integers.
Solution:
#include <stdio.h>

int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);

int start = 0;
int end = n - 1;
int temp;

while (start < end) {


// Swap elements at start and end indices
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}

printf("Reversed array: ");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}
Explanation: In this program, we reverse an array by using two pointers (start
and end) that initially point to the first and last elements of the array, respectively.
We swap elements at these indices and move the pointers inward until they meet
in the middle of the array.

Problem 4: Find the Average of Array Elements


Problem Statement: Write a C program to calculate the average of elements in
an array of integers.
Solution:
#include <stdio.h>

int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);

int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}

float average = (float)sum / n;

printf("Average of array elements: %.2f\n", average);

return 0;
}
Explanation: This program calculates the average of array elements by first
finding the sum of elements and then dividing it by the number of elements (n).
We cast the sum to a float to ensure accurate floating-point division.

Problem 5: Count Even and Odd Numbers in an Array


Problem Statement: Write a C program to count the number of even and odd
elements in an array of integers.
Solution:
#include <stdio.h>

int main() {
int arr[] = {10, 23, 5, 17, 9};
int n = sizeof(arr) / sizeof(arr[0]);

int evenCount = 0;
int oddCount = 0;

for (int i = 0; i < n; i++) {


if (arr[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

printf("Number of even elements: %d\n", evenCount);


printf("Number of odd elements: %d\n", oddCount);

return 0;
}
Explanation: This program counts the number of even and odd elements in an
array by iterating through the array and checking the remainder when each
element is divided by 2. If the remainder is 0, the element is even; otherwise, it's
odd.

Matrix Multiplication:
Problem 6: Matrix Multiplication
Problem Statement: Write a C program to multiply matrix of user defined matrix
Solution:
#include <stdio.h>
int main() {
int m, n, p, q;
// Input the dimensions of the first matrix (m x n)
printf("Enter the dimensions of the first matrix (m x n): ");
scanf("%d %d", &m, &n);

// Input the dimensions of the second matrix (p x q)


printf("Enter the dimensions of the second matrix (p x q): ");
scanf("%d %d", &p, &q);

// Check if matrix multiplication is possible


if (n != p) {
printf("Matrix multiplication is not possible. The number of columns in the
first matrix must be equal to the number of rows in the second matrix.\n");
return 1; // Exit the program with an error code
}

// Declare arrays for the two input matrices and the result matrix
int mat1[m][n], mat2[p][q], result[m][q];

// Input elements for the first matrix


printf("Enter the elements of the first matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &mat1[i][j]);
}
}

// Input elements for the second matrix


printf("Enter the elements of the second matrix:\n");
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
scanf("%d", &mat2[i][j]);
}
}

// Initialize the result matrix with zeros


for (int i = 0; i < m; i++) {
for (int j = 0; j < q; j++) {
result[i][j] = 0;
}
}

// Perform matrix multiplication Here there is no need of 'p' --> Row of 2nd Matrix.

for (int i = 0; i < m; i++) {


for (int j = 0; j < q; j++) {
for (int k = 0; k < n; k++) { here 'n' is included because the Adding should
happen only for the Column of Matrix 1

result[i][j] += mat1[i][k] * mat2[k][j];


}
}
}

// Display the resultant matrix


printf("Resultant Matrix:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < q; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0; // Exit the program with a success code
}
This program takes the dimensions of two matrices (m x n and p x q) as input and
then takes the elements of both matrices. It checks if matrix multiplication is
possible (i.e., the number of columns in the first matrix equals the number of rows
in the second matrix) and then performs matrix multiplication using nested loops.
Finally, it displays the resultant matrix.
2D ARRAY:
Problem 7: 2D Array
Problem Statement: Create a C program to store and display a 2D numeric array
of integers. The program should ask the user for the number of rows and columns,
and then input and display the elements of the 2D array.
Solution:
#include <stdio.h>

int main() {
int rows, cols;

// Input the number of rows and columns


printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

int matrix[rows][cols];

// Input matrix elements


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element at position (%d, %d): ", i, j);
scanf("%d", &matrix[i][j]);
}
}

// Display the matrix


printf("Matrix Elements:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

return 0;
}
Explanation: In this program, the user specifies the number of rows and columns
for a 2D numeric array. We use nested for loops to input and display the elements
of the 2D array. This example demonstrates the use of a 2D numeric array to
organize and display tabular data.

Problem 8: Bubble sorting Array


Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to
be sorted, compares adjacent elements, and swaps them if they are in the wrong
order. The pass through the list is repeated until no swaps are needed, which
means the list is sorted.
Here's how the Bubble Sort algorithm works:
1. Start from the beginning of the list.
2. Compare the first two elements. If the first element is greater than the
second element, swap them.
3. Move to the next pair of elements and repeat the comparison and swap if
necessary.
4. Continue this process until you reach the end of the list.
5. After the first pass, the largest element will have "bubbled up" to the end
of the list.
6. Repeat the process for the remaining unsorted elements, excluding the last
element (since it's already in its correct position).
7. Continue this process until no swaps are needed during a pass, indicating
that the list is sorted.
Bubble Sort is a straightforward sorting algorithm, but it's not very efficient,
especially for large lists.

Problem Statement: An example of sorting a 1D numeric array using the Bubble


Sort algorithm.
Solution:
#include <stdio.h>

void bubbleSort(int arr[], int size) {


for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int numbers[5] = {10, 5, 8, 3, 12};
int size = 5;

// Sort the array using Bubble Sort


bubbleSort(numbers, size);

// Display the sorted array


printf("Sorted Array: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

return 0;
}

Program 9: 2D Array Input and Sum Calculation


Problem Statement: Write a C program that takes user input to fill a 2D array and
then calculates the sum of all elements in the array.
#include <stdio.h>

int main() {
int rows, cols;

// Input the dimensions of the 2D array


printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);

int matrix[rows][cols];
int sum = 0;

// Input array elements


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element at position (%d, %d): ", i, j);
scanf("%d", &matrix[i][j]);
sum += matrix[i][j];
}
}

// Display the sum


printf("Sum of all elements: %d\n", sum);

return 0;
}
Explanation: In this program, the user is prompted to input the dimensions of a
2D array (number of rows and columns) and then fill the array with values.
Afterward, the program calculates and displays the sum of all elements in the
array.

Program 10: 2D Array Sorting (Bubble Sort)


Problem Statement: Create a C program that sorts a 2D array in ascending order
using the Bubble Sort algorithm.
#include <stdio.h>

void bubbleSort(int arr[], int size) {


for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int rows = 4, cols = 4;
int matrix[4][4] = {
{25, 10, 5, 15},
{40, 20, 30, 35},
{60, 55, 50, 45},
{75, 70, 65, 80}
};

// Sort each row using Bubble Sort


for (int i = 0; i < rows; i++) {
bubbleSort(matrix[i], cols);
}

// Display the sorted matrix


printf("Sorted Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}

return 0;
}
Explanation: This program initializes a 2D array with random values, sorts it in
ascending order using Bubble Sort, and then displays the sorted array.

Program 11: 2D Array Multiplication


Problem Statement: Write a C program to perform matrix multiplication on two
2D arrays.
#include <stdio.h>

int main() {
int rowsA = 3, colsA = 2;
int rowsB = 2, colsB = 3;
int matrixA[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int matrixB[2][3] = {{7, 8, 9}, {10, 11, 12}};
int result[3][3] = {0};

// Perform matrix multiplication


for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}

// Display the result


printf("Matrix A:\n");
// (Display matrix A)
printf("Matrix B:\n");
// (Display matrix B)
printf("Result:\n");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
printf("%d\t", result[i][j]);
}
printf("\n");
}

return 0;
}
Explanation: This program multiplies two 2D arrays and stores the result in a
third array. It demonstrates the concept of matrix multiplication.
Program 12: 2D Array Transposition
Problem Statement: Create a C program that transposes a given 2D array,
switching rows and columns.
#include <stdio.h>

int main() {
int rows = 3, cols = 4;
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int transpose[4][3];
// Transpose the matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Display the transposed matrix


printf("Original Matrix:\n");
// (Display original matrix)
printf("Transposed Matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d\t", transpose[i][j]);
}
printf("\n");
}

return 0;
}
Explanation: This program transposes a 2D array, interchanging rows and
columns, and then displays the transposed array.

Program 13: 2D Array Largest Element


Problem Statement: Write a C program to find and display the largest element in
each 2D array.
#include <stdio.h>

int main() {
int rows = 3, cols = 4;
int matrix[3][4] = {
{45, 12, 76, 23},
{89, 54, 32, 67},
{14, 98, 43, 56}
};
int largest = matrix[0][0];

// Find the largest element


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] > largest) {
largest = matrix[i][j];
}
}
}

// Display the largest element


printf("The largest element in the matrix is: %d\n", largest);

return 0;
}
Explanation: This program finds and displays the largest element in a 2D array.
It demonstrates how to iterate through a 2D array and track the largest element.
Chapter-VI: Syntax Error

Identify and rectify the following syntax error in the given program.
1. if (x > 10
{
printf("x is greater than 10");
}
Solution: The syntax error in this code is a missing closing parenthesis ) in
the if statement condition. It should be if (x > 10).
2. if (condition) {
printf("Condition is true");
} else
{
printf("Condition is false");
Solution: The syntax error in this code is inconsistent formatting. The
opening brace of the else block should be on the same line as else. It should
be } else {.
3. int count = 0;
while (count < 5)
{
printf("Count is %d\n", count);
count++;
Solution: The syntax error in this code is a missing closing brace } for the
while loop. It should be } after count++;.
4. int i = 0;
do {
printf("Value of i is %d\n", i);
} while (i < 5);
Solution: The syntax error in this code is that there's no semicolon ; at the
end of the do-while loop. It should be } while (i < 5);.
5. for (int i = 0; i < 10; i++)
{
printf("Value of i: %d\n", i);
}
Solution: There is no syntax error in this code; it's a correct usage of the for
loop.
6. goto jump;
printf("This code is unreachable\n");
jump:
printf("Jumped to this label");
Solution: The syntax error in this code is that goto statements are not
followed by a semicolon. It should be goto jump; instead of goto jump;.
7. int choice = 2;
switch (choice)
{
case 1:
printf("Choice 1");
case 2:
printf("Choice 2");
case 3:
printf("Choice 3");
}
Solution: There is no syntax error in this code; it's a correct usage of the
switch statement. However, it lacks break statements, which might lead to
unintended fall-through behaviours.
8. int add(int a, b)
{
return a + b;
}
Solution: The syntax error in this code is missing the data type for the second
parameter b in the function declaration. It should be int add(int a, int b).
9. int numbers[5;
Solution: The syntax error in this code is a missing closing square bracket ]
in the array declaration. It should be int numbers[5];.
[Link] values[3];
int x = values[3];
Solution: The syntax error in this code is trying to access an array element
at an out-of-bounds index. The array values have indices 0, 1, and 2, but
we're trying to access index 3, which is out of range. It should be within the
valid index range (0 to 2).
[Link] multiply(int x, y) {
return x * y;
}
Solution: The syntax error in this code is missing data types for both
parameters in the function definition. It should be int multiply(int x, int y).
[Link] vowels[] = {'a', 'e', 'i', 'o' 'u'};
Solution: The syntax error in this code is a missing comma , between the
characters 'o' and 'u' in the array initialization. It should be {'a', 'e', 'i',
'o', 'u'}.
[Link] x = 5
Solution: The syntax error in this code is a missing semicolon ; at the end
of the statement. It should be int x = 5;.
[Link] 123abc = 42;
Solution: The syntax error in this code is using an invalid identifier
(variable name). Variable names cannot start with a digit. It should be
something like int abc123 = 42;.
15.#include <stdio>
int main() {
printf("Hello, World!");
return 0;
}
Solution: The syntax error in this code is an incorrect use of the #include
directive. The <stdio.h> header file should have .h, like this: #include
<stdio.h>.

Chapter-VII: String
Strings in C Programming:
Definition:
Character Arrays: Strings in C are represented as arrays of characters. Each
element in the array holds a character, and the sequence of characters forms
the string.

Null Termination: C strings are null terminated, meaning they end with a
special character called the null character ('\0'). The null character marks
the end of the string.
Types of Strings:
String Literals: Strings can be defined using string literals, enclosed in
double quotes. For example: "Hello, World!".

Character Arrays: Strings can be created by explicitly declaring character


arrays. For example: char myString[] = "Hello";.
How to Use Strings:
1. String Declaration:
char greeting[] = "Hello";
2. String Input/Output:
printf("Enter a string: ");
scanf("%s", myString);
printf("You entered: %s\n", myString);
3. String Functions:
C provides string manipulation functions in the <string.h> header, such as
strlen, strcpy, strcat, strcmp, etc.
4. String Concatenation:
char greeting[20] = "Hello";
char name[] = "John";
strcat(greeting, name);
printf("Greeting: %s\n", greeting); // Output: HelloJohn
5. String Comparison:
char str1[] = "apple";
char str2[] = "orange";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
Example Programs:
1. String Length:
#include <stdio.h>
#include <string.h>

int main() {
char myString[] = "Hello";
int length = strlen(myString);
printf("Length of the string: %d\n", length);
return 0;
}

 char myString[] = "Hello";: Declares a character array myString and


initializes it with the string "Hello".
 int length = strlen(myString);: Uses the strlen function to find the length
of the string and assigns it to the variable length.

2. String Copy:
#include <stdio.h>
#include <string.h>

int main() {
char source[] = "Copy this string!";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
 char source[] = "Copy this string!";: Declares a character array source
and initializes it with the string.
 char destination[20];: Declares an empty character array destination with
enough space to hold the copied string.
 strcpy(destination, source);: Uses the strcpy function to copy the
contents of source to destination.
 printf("Copied string: %s\n", destination);: Prints the copied string.

3. String Concatenation:
#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
 char str1[20] = "Hello, ";: Declares a character array str1 and initializes
it with the string "Hello, ".
 char str2[] = "World!";: Declares a character array str2 and initializes it
with the string "World!".
 strcat(str1, str2);: Uses the strcat function to concatenate str2 to the end
of str1.
 printf("Concatenated string: %s\n", str1);: Prints the concatenated
string.

4. String Reversal:
#include <stdio.h>
#include <string.h>

int main() {
char text[] = "Reverse This!";
strrev(text);
printf("Reversed string: %s\n", text);
return 0;
}
 char text[] = "Reverse This!";: Declares a character array text and
initializes it with the string "Reverse This!".
 strrev(text);: Uses the strrev function to reverse the characters in text in-
place.
 printf("Reversed string: %s\n", text);: Prints the reversed string.

5. String Comparison:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "apple";
char str2[] = "orange";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
return 0;
}
 char str1[] = "apple";: Declares a character array str1 and initializes it
with the string "apple".
 char str2[] = "orange";: Declares a character array str2 and initializes it
with the string "orange".
 strcmp(str1, str2) == 0: Uses the strcmp function to compare str1 and
str2. If the result is 0, it means the strings are equal.
 The program then prints whether the strings are equal or not based on the
comparison result.
These examples demonstrate common string operations in C, utilizing
functions from the <string.h> library. They cover finding the length,
copying, concatenating, reversing, and comparing strings.
Addi onal problem in s ngs in C programming:

1. String Length without ‘strlen’


Problem:
Write a program to find the length of a given string without using the strlen func on.

Solu on:
#include <stdio.h>

int stringLength(const char *str) {


int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}

int main() {
char myString[] = "Assignment";
int length = stringLength(myString);
prin ("Length of the string: %d\n", length);
return 0;
}
Explana on:
The program defines a func on stringLength to find the length of a string using a loop un l
the null character is encountered.

2. String Copy without ‘strcpy’


Problem:
Write a program to copy one string into another without using the strcpy func on.

Solu on:
#include <stdio.h>

void stringCopy(char *dest, const char *src) {


int i = 0;
while (src[i] != '\0') {
dest[i] = src[i];
i++;
}
dest[i] = '\0';
}

int main() {
char source[] = "Copy Assignment";
char des na on[20];
stringCopy(des na on, source);
prin ("Copied string: %s\n", des na on);
return 0;
}
Explana on:
The program defines a func on stringCopy to copy characters from one string to another
using a loop.

3. String Concatena on without strcat


Problem:
Write a program to concatenate two strings without using the strcat func on.

Solu on:
#include <stdio.h>

void stringConcat(char *dest, const char *src) {


int destLen = 0;
while (dest[destLen] != '\0') {
destLen++;
}

int i = 0;
while (src[i] != '\0') {
dest[destLen + i] = src[i];
i++;
}
dest[destLen + i] = '\0';
}

int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
stringConcat(str1, str2);
prin ("Concatenated string: %s\n", str1);
return 0;
}
Explana on:
The program defines a func on stringConcat to concatenate two strings without using the
strcat func on.

4. Palindrome Check
Problem:
Write a program to check if a given string is a palindrome.

Solu on:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool isPalindrome(const char *str) {


int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - 1 - i]) {
return false;
}
}
return true;
}

int main() {
char myString[] = "madam";
if (isPalindrome(myString)) {
prin ("The string is a palindrome.\n");
} else {
prin ("The string is not a palindrome.\n");
}
return 0;
}
Explana on:
The program defines a func on is Palindrome to check if a string is a palindrome by
comparing characters from both ends.

5. Count Vowels and Consonants


Problem:
Write a program to count the number of vowels and consonants in a given string.

Solu on:
#include <stdio.h>
#include <ctype.h>

void countVowelsConsonants(const char *str, int *vowels, int *consonants) {


*vowels = 0;
*consonants = 0;

for (int i = 0; str[i] != '\0'; i++) {


char ch = tolower(str[i]);

if (ch >= 'a' && ch <= 'z') {


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
(*vowels)++;
} else {
(*consonants)++;
}
}
}
}

int main() {
char myString[] = "Count Vowels and Consonants";
int numVowels, numConsonants;
countVowelsConsonants(myString, &numVowels, &numConsonants);

prin ("Vowels: %d\nConsonants: %d\n", numVowels, numConsonants);


return 0;
}

Explana on:
The program defines a func on countVowelsConsonants to count the number of vowels and
consonants in a string.

6. Remove Spaces
Problem:
Write a program to remove spaces from a given string.
Solu on:
#include <stdio.h>

void removeSpaces(char *str) {


int i, j;
for (i = 0, j = 0; str[i] != '\0'; i++) {
if (str[i] != ' ') {
str[j++] = str[i];
}
}
str[j] = '\0';
}

int main() {
char myString[] = "Remove Spaces from String";
removeSpaces(myString);
prin ("String without spaces: %s\n", myString);
return 0;
}
Explana on:
The program defines a func on removeSpaces to remove spaces from a string by shi ing
characters.

7. Word Count
Problem:
Write a program to count the number of words in a given string.

Solu on:
#include <stdio.h>

int countWords(const char *str) {


int words = 0;
int inWord = 0;
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n') {
inWord = 0;
} else if (!inWord) {
inWord = 1;
words++;
}
}

return words;
}

int main() {
char myString[] = "Count the Words in This String";
int numWords = countWords(myString);
prin ("Number of words: %d\n", numWords);
return 0;
}
Explana on:
The program defines a func on countWords to count the number of words in a string.
Structure in C
[Link]
structure in C programs
A structure is a user-defined data type that allows us to
group different data types under a single name.
Structures are used to represent a collection of related
variables, possibly of different types, under a single
name. The variables within a structure are called
members.
What are Data
Structures?
Data structures are specialized formats for organizing, processing, and
storing data. They enable efficient data access and modification, which
are critical for the performance of software applications. In essence,
data structures are containers that hold data in a specific layout,
allowing for easy manipulation and retrieval.

The primary goal of using data structures is to reduce the complexity of


data operations. For example, consider a simple list of numbers.
Without a proper data structure, searching for a specific number could
be time-consuming and inefficient. However, with a well-designed data
structure, this operation can be performed quickly and efficiently.

There are various types of data structures, each designed to handle


different kinds of data and operations. Understanding these types and
their appropriate use cases is essential for effective programming and
software development.
Importance of Data Structures

- DATA MANAGEMENT: THEY


THEY ARE THE BACKBONE OF - EFFICIENCY: WELL-DESIGNED PROVIDE SYSTEMATIC WAYS OF
EFFICIENT ALGORITHMS AND ARE DATA STRUCTURES ALLOW FOR ORGANIZING AND MANAGING
CRUCIAL FOR BUILDING EFFICIENT DATA PROCESSING, LARGE VOLUMES OF DATA,
SCALABLE AND HIGH- REDUCING THE TIME AND SPACE MAKING IT EASIER TO STORE,
PERFORMANCE APPLICATIONS. COMPLEXITY OF ALGORITHMS. RETRIEVE, AND MANIPULATE
DATA.

FOR EXAMPLE, CONSIDER A SOCIAL MEDIA APPLICATION


THAT NEEDS TO MANAGE MILLIONS OF USER PROFILES.
- OPTIMIZATION: DATA STRUCTURES USING APPROPRIATE DATA STRUCTURES, THE
HELP IN OPTIMIZING THE APPLICATION CAN EFFICIENTLY HANDLE OPERATIONS
PERFORMANCE OF SOFTWARE SUCH AS SEARCHING FOR A USER, UPDATING PROFILE
APPLICATIONS BY ENABLING FASTER INFORMATION, AND DISPLAYING USER DATA. WITHOUT
DATA ACCESS AND MODIFICATION. PROPER DATA STRUCTURES, THESE OPERATIONS WOULD
BE SLOW AND INEFFICIENT, LEADING TO POOR
APPLICATION PERFORMANCE.
Types of Data Structures

Data Structure Description Use Cases


Store elements of the same type in a contiguous
Arrays block of memory. Provide fast access to elements Storing collections of data.
using indices.
Dynamic data structures consisting of nodes
Dynamic memory allocation, efficient insertion and
Linked Lists connected by pointers. Each node contains data and a
deletion of elements.
reference to the next node.
Linear data structures that follow the Last In, First Out Function call management, expression evaluation,
Stacks
(LIFO) principle. backtracking algorithms.
Linear data structures that follow the First In, First
Queues Task scheduling, breadth-first search algorithms.
Out (FIFO) principle.
Hierarchical data structures consisting of nodes Representing hierarchical relationships, implementing
Trees
connected by edges. efficient search and sorting algorithms.
Representing relationships between entities, network
Graphs Consist of vertices (nodes) and edges (connections).
analysis, pathfinding algorithms.
Real-World Examples B-trees

1. Database Management Systems (DBMS): Databases use various data


structures, such as B-trees and hash tables, to organize and manage data
efficiently. These structures enable fast data retrieval, insertion, and deletion,
ensuring optimal performance for database operations.
2. Operating Systems: Operating systems use data structures like queues and
linked lists to manage processes, schedule tasks, and handle memory allocation.
For example, the CPU scheduling algorithm uses a queue to manage processes
waiting for execution.
3. Web Browsers: Web browsers use stacks to manage the back and forward
navigation history. Each time a user navigates to a new page, the current page is
pushed onto the stack. When the user presses the back button, the browser pops
the top page from the stack and displays it.
4. Social Media Platforms: Social media platforms use graphs to represent
relationships between users. For example, on Facebook, users are represented as
vertices, and friendships between users are represented as edges. Graph
algorithms are used to find mutual friends, suggest new friends, and analyze hash tables
social networks.
Basic syntax for declaring a structure in C:
struct StructureName { For example, consider a structure representing
// Member declarations information about a point in 2D space:
struct Point {
data_type1 member1; int x;
data_type2 member2; int y;
};
// ...
};
Defining a Structure
In C, a structure is defined using the keyword 'struct'. For instance, if we want to create a structure to store information
about a book, we can define it as follows:

c<br />struct Book {<br /> char title[50];<br /> char author[50];<br /> int pages;<br /> float price;<br />};<br />
This structure named 'Book' contains four members: 'title', 'author', 'pages', and 'price'.
Basic syntax for declaring a structure in C:…
We can declare variables of the structure type and access its members using
the dot (.) operator:
struct Point p1; // Declare a variable of type Point

// Access and assign values to members Once a structure is defined, we can declare variables of that
type. For example, using the 'Book' structure defined
p1.x = 10; previously:
p1.y = 20; c<br />struct Book myBook;<br />
This declares a variable 'myBook' of type 'struct Book'.

// Access and use the values


printf("Coordinates: (%d, %d)\n", p1.x, p1.y);
Initializing Structures:
Structures can be initialized during declaration using curly braces {}:
struct Point { We can initialize the members of a structure at the time of
declaration or later. Here's how we can do it:
int x;
int y; c<br />struct Book myBook = {"The Great Gatsby", "F. Scott
Fitzgerald", 180, 10.99};<br />
}; This initializes 'myBook' with a title of 'The Great Gatsby', an author
of 'F. Scott Fitzgerald', 180 pages, and a price of 10.99.

// Initializing a structure during declaration


struct Point p1 = {10, 20};
Accessing the Structures:
To access the members of a structure, use the dot operator (.). For
instance, to print the title of 'myBook’, we can write:

c<br />printf("Title: %s\n", [Link]);<br />


This will output the title stored in the 'myBook' structure.
Pointers to Structures:
Using Pointers to Structures

We can also use pointers to structures. Here's an example using the 'Book'
structure:
c<br />struct Book *ptrBook;<br />ptrBook = &myBook;<br />printf("Title:
%s\n", ptrBook->title);<br />
Here, 'ptrBook' is a pointer to a 'Book' structure, and 'ptrBook->title'
accesses the 'title' member of the structure pointed to by 'ptrBook'.
Structure within a Structures:
Structures can be nested within other structures. For example, if you wanted
to store information about a library, you could define a structure like this:

c<br />struct Library {<br /> struct Book collection[100];<br /> int
totalBooks;<br />};<br />
Here, the 'Library' structure contains an array of 'Book' structures and an
integer 'totalBooks' to keep track of the number of books.
Nested Structures: (cont…)
Structures can be nested inside other structures to create more complex data structures:
struct Address {
char street[50];
char city[50];
char state[20];
};

struct Person {
char name[50];
int age;
struct Address address; // Nested structure
};
Passing Structures to Functions:
We can pass structures to functions by value or by reference (using pointers):
// Pass by value
void displayPerson(struct Person p) {
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
}

// Pass by reference
void updateAge(struct Person *p, int newAge) {
p->age = newAge; // Using arrow operator to access members through a
pointer
}
Arrays of Structures:
We can create arrays of structures to store multiple instances of the same structure type:
struct Student {
char name[50];
int age;
float gpa;
};

// Declare an array of structures


struct Student class[3];

// Access and assign values to the array of structures


class[0].age = 20;
class[1].gpa = 3.5;
// ...
Problem 1: Point Structure for 2D Geometry
#include <stdio.h> Cont…
#include <math.h> // Input: Get coordinates of the two points from the user
printf("Enter coordinates for Point 1 (x y): ");
// Define the Point structure scanf("%d %d", &point1.x, &point1.y);
struct Point {
int x; printf("Enter coordinates for Point 2 (x y): ");
scanf("%d %d", &point2.x, &point2.y);
int y;
}; // Calculate and display the distance between the two points
float distance = calculateDistance(point1, point2);
// Function to calculate distance between two points
printf("Distance between the points: %.2f\n", distance);
float calculateDistance(struct Point p1, struct Point p2) {
return sqrt(pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2)); return 0;
}
}
int main() {
// Declare variables of type Point Create a structure called Point to represent a point in 2D space
with x and y coordinates. Write a program that calculates and
struct Point point1, point2;
prints the distance between two points.
Cont…
Problem 2: Book Structure for Library System
Create a structure called Book to represent a book in a library. Include members for the book's title, author,
and publication year. Write a program that maintains an array of books, allows the user to input book details,
and prints the information of a specified book.
#include <stdio.h> Cont…
// Define the Book structure scanf(" %[^\n]", library[i].author);
struct Book { printf("Publication Year: ");
char title[100]; scanf("%d", &library[i].year);
char author[50]; }
int year; // Input: Get the index of the book to display
}; int bookIndex;
int main() { printf("\nEnter the index of the book to display (1-5): ");
// Declare an array of Book structures scanf("%d", &bookIndex);
struct Book library[5];
// Input: Get book details from the user // Display the information of the specified book
for (int i = 0; i < 5; ++i) { printf("\nBook Details:\n");
printf("Enter details for Book %d:\n", i + 1); printf("Title: %s\n", library[bookIndex - 1].title);
printf("Title: "); printf("Author: %s\n", library[bookIndex - 1].author);
scanf(" %[^\n]", library[i].title); printf("Publication Year: %d\n", library[bookIndex - 1].year);
printf("Author: "); return 0;
Cont… }
Problem 3: Employee Management System with Nested Structures
Create a program that manages employee information using nested structures. Define two structures:
Employee to represent basic employee details, and Date to represent the date of birth. The Employee structure
should include a member of type Date. Write a program that allows the user to input employee details and
displays the information.
#include <stdio.h> // Input: Get employee details from the user
// Define the Date structure printf("Enter employee details:\n");
struct Date { printf("Name: ");
int day; scanf(" %[^\n]", [Link]);
int month; printf("Employee ID: ");
int year; scanf("%d", &[Link]);
}; printf("Birth Date (DD MM YYYY): ");
// Define the Employee structure with nested Date structure scanf("%d %d %d", &[Link],
struct Employee { &[Link], &[Link]);
char name[50]; // Display the entered employee details
int employeeId; printf("\nEmployee Details:\n");
struct Date birthDate; printf("Name: %s\n", [Link]);
}; printf("Employee ID: %d\n", [Link]);
int main() { printf("Birth Date: %02d/%02d/%d\n",
// Declare a variable of type Employee [Link], [Link],
struct Employee employee; [Link]);
return 0; }
Problem 4: Student Database using Arrays of Structures
Create a program to manage a database of student information using arrays of structures. Define a structure Student with
members for the student's name, roll number, and marks in three subjects. Write a program that allows the user to input
information for multiple students, calculates their average marks, and displays the details of each student.
#include <stdio.h>
// Define the Student structure
struct Student {
char name[50];
int rollNumber;
float marks[3]; // Marks in three subjects
float averageMarks;
};
int main() {
// Declare an array of Student structures
struct Student students[3]; // Assuming 3 students for this example
// Input: Get student details and marks from the user
for (int i = 0; i < 3; ++i) {
printf("Enter details for Student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
Cont…
cont…
// Input marks for each subject
printf("Enter marks in three subjects:\n");
for (int j = 0; j < 3; ++j) {
printf("Subject %d: ", j + 1);
scanf("%f", &students[i].marks[j]);
}
// Calculate average marks for each student
students[i].averageMarks = 0;
for (int j = 0; j < 3; ++j) {
students[i].averageMarks += students[i].marks[j];
}
students[i].averageMarks /= 3;
}
// Display the details of each student
printf("\nStudent Database:\n");
for (int i = 0; i < 3; ++i) {
printf("\nStudent %d Details:\n", i + 1);
printf("Name: %s\n", students[i].name);
printf("Roll Number: %d\n", students[i].rollNumber);
printf("Marks in three subjects: %.2f, %.2f, %.2f\n", students[i].marks[0], students[i].marks[1],
students[i].marks[2]);
printf("Average Marks: %.2f\n", students[i].averageMarks);
}
1. Write a program to demonstrates the difference between call by value and call by reference using
a structure in C.
#include <stdio.h>

// Define a structure
typedef struct Point {
int x;
int y;
} Point;

// Func on using call by value


void modifyPointByValue(Point point) {
point.x += 10;
point.y += 20;
}

// Func on using call by reference


void modifyPointByReference(Point *point) {
(*point).x += 10; // Using dereference operator
point->y += 20; // Using arrow operator
}

int main() {
// Create a Point structure
Point point1 = {1, 2};

// Call modifyPointByValue func on


modifyPointByValue(point1);
prin ("Point a er call by value: x = %d, y = %d\n", point1.x, point1.y);

// Call modifyPointByReference func on


modifyPointByReference(&point1); // Pass address of the structure
prin ("Point a er call by reference: x = %d, y = %d\n", point1.x, point1.y);

return 0;
}

Explana on:

 We define a structure Point with two integer members x and y.


 The modifyPointByValue func on takes a copy of the Point structure as an argument. Any changes
made inside the func on are not reflected in the original structure.
 The modifyPointByReference func on takes a pointer to the Point structure as an argument. Any
changes made inside the func on are reflected in the original structure.
 In the main func on, we create a Point structure variable point1 and ini alize it with values.
 We call the modifyPointByValue func on with point1 as an argument. This creates a copy of the
structure within the func on. Any changes made to this copy will not affect the original point1.
 We call the modifyPointByReference func on with the address of point1 as an argument. This allows
the func on to modify the original structure directly.
 Finally, we print the values of point1 a er each func on call to demonstrate the difference between
call by value and call by reference.

This program demonstrates that call by value creates a copy of the argument, while call by reference
modifies the original argument directly. Choosing between call by value and call by reference
depends on the specific needs of your program.

2. Structure - Call by Value:


#include <stdio.h>

// Define a structure
typedef struct Point {
int x;
int y;
} Point;

// Func on using call by value


void swapPointsByValue(Point point1, Point point2) {
Point temp = point1;
point1 = point2;
point2 = temp;
}

int main() {
// Create two Point structures
Point point1 = {1, 2};
Point point2 = {3, 4};

// Call swapPointsByValue func on


swapPointsByValue(point1, point2);

// Print the original structures


prin ("Point 1 a er call by value: x = %d, y = %d\n", point1.x, point1.y);
prin ("Point 2 a er call by value: x = %d, y = %d\n", point2.x, point2.y);

return 0;
}

Explana on:

 This program defines a Point structure and a func on swapPointsByValue that takes two Point
structures as arguments.
 The swapPointsByValue func on creates copies of the argument structures and stores them in
temporary variables.
 It then swaps the values of the temporary variables.
 However, since the func on only receives copies of the original structures, any changes made
within the func on are not reflected in the original structures.
 Therefore, prin ng the original point1 and point2 a er the func on call will show their original
values.

3. Structure - Call by reference:


#include <stdio.h>

// Define a structure
typedef struct Point {
int x;
int y;
} Point;

// Func on using call by reference


void swapPointsByReference(Point *point1, Point *point2) {
Point temp = *point1;
*point1 = *point2;
*point2 = temp;
}

int main() {
// Create two Point structures
Point point1 = {1, 2};
Point point2 = {3, 4};

// Call swapPointsByReference func on


swapPointsByReference(&point1, &point2);

// Print the original structures


prin ("Point 1 a er call by reference: x = %d, y = %d\n", point1.x, point1.y);
prin ("Point 2 a er call by reference: x = %d, y = %d\n", point2.x, point2.y);

return 0;
}

Explana on:

 This program uses pointers to pass Point structures to the swapPointsByReference func on.
 Inside the func on, the * operator dereferences the pointers to access the actual structures.
 Swapping the values of the dereferenced pointers directly modifies the original structures.
 Therefore, prin ng the original point1 and point2 a er the func on call will show their swapped
values.
Understanding Pointers in C Programming

Focusing on Pointers fundamental concepts, memory allocation, and their usage in functions.
Pointers are a powerful feature in C that allows for direct memory manipulation, making them
essential for efficient programming. This guide is tailored for first-time learners, complete
with examples to illustrate each concept clearly.

What are Pointers?

Pointers are variables that store the memory address of another variable. They are declared
using the asterisk (*) symbol. Understanding pointers is crucial for dynamic memory
management and efficient data handling in C.

Declaring and Initializing Pointers

To declare a pointer, We specify the type of data it will point to, followed by an asterisk and
the pointer's name. For example:

int *ptr; // Pointer to an integer

We can initialize a pointer by assigning it the address of a variable using the address-of
operator (&):

int var = 10;


ptr = &var; // ptr now holds the address of var

Accessing Values Using Pointers

To access the value stored at the address a pointer points to, We use the dereference
operator (*). For example:

printf("%d", *ptr); // Outputs: 10

Pointers and Memory Allocation

Dynamic memory allocation in C is done using pointers. The malloc, calloc, realloc, and free
functions from the stdlib.h library are used for this purpose.

Using `malloc`
The malloc function allocates a specified number of bytes and returns a pointer to the
allocated memory. Here's an example:

How to allocate memory in C?

Use malloc Use calloc


Allocates a specified number Allocates memory for an
of bytes and returns a pointer array of elements, initializes
to the allocated memory. all bytes to zero, and returns
a pointer to the allocated
memory.
#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr;
int n = 5;

// Allocating memory for an array of 5 integers


arr = (int*)malloc(n * sizeof(int));

// Checking if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initializing and printing the array


for (int i = 0; i < n; i++) {
arr[i] = i + 1;
printf("%d ", arr[i]);
}

// Freeing the allocated memory


free(arr);
return 0;
}

Memory Allocation and Deallocation in C

Allocate
memory for an Initialize and
array print the array

Check if Free the


allocation was allocated
successful memory

Using `calloc`

The calloc function allocates memory for an array and initializes all bytes to zero:
arr = (int*)calloc(n, sizeof(int)); // Allocates memory for n integers and
initializes to 0

Using `realloc`

The realloc function changes the size of previously allocated memory:

arr = (int*)realloc(arr, new_size * sizeof(int)); // Resizes the allocated


memory

Freeing Memory

Always free dynamically allocated memory using the free function to prevent memory leaks:

free(arr);

Pointers in Functions

Pointers can be used to pass variables to functions by reference, allowing the function to
modify the original variable.

Passing by Reference

Here's an example of a function that swaps two integers using pointers:

#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y); // Passing addresses of x and y
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
Returning Pointers from Functions

We can also return pointers from functions. However, be cautious about returning pointers to
local variables, as they will be destroyed once the function exits.

int* createArray(int size) {


return (int*)malloc(size * sizeof(int)); // Return pointer to allocated
memory
}

Returning pointers from functions

Pros Cons

Dynamic Risk of
memory dangling
allocation pointers

Flexible array
Memory leaks
size

Efficient Complex
memory memory
usage management

Conclusion

Pointers are a fundamental aspect of C programming that enable efficient memory


management and manipulation. Understanding how to declare, initialize, and use pointers,
along with their role in dynamic memory allocation and function parameters, is essential for
any aspiring C programmer.
1. Program to Reverse a String using Pointers
#include <stdio.h>
#include <string.h>

// Function to reverse the string


// using pointers
void reverseString(char *str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;

// Get the length of the string


l = strlen(str);

// Setting the begin_ptr


// to start of string
begin_ptr = str;

// Setting the end_ptr the end of


// the string
end_ptr = str + l - 1;

// Swap the char from start and end


// index using begin_ptr and end_ptr
for (i = 0; i < l / 2; i++)
{

// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;

// update pointers positions


begin_ptr++;
end_ptr--;
}
}

int main()
{
// Define the String
char str[100] = "GeeksforGeeks";

// Reverse the string


reverseString(str);

printf("Reverse of the string: %s\n", str);


return 0;
}

2. Move all zeroes to end of array using Two-Pointers


// C implementation to move all zeroes at
// the end of array
#include<stdio.h>

// Function to move all zeroes at


// the end of array
void moveZerosToEnd(int arr[], int n)
{
int j=0, temp, i;

// Traverse the array. If arr[i] is


// non-zero and arr[j] is zero,
// then swap both the element
for(i=0;i<n;i++)
{
if(arr[i]!=0 && arr[j]==0)
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
if(arr[j]!=0)
j+=1;
}
}

// Function to print the array elements


void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}

// Driver Code
int main()
{
int arr[] = {8, 9, 0, 1, 2, 0, 3};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


printArray(arr, n);

moveZerosToEnd(arr, n);
printf("\nModified array: ");
printArray(arr, n);

return 0;
}

create pointers to structs.:

struct name {

member1;

member2;

};

int main()

struct name *ptr, Harry;

Here, ptr is a pointer to struct.

Example: Access members using Pointer

To access members of a structure using pointers, we use the -> operator.

#include <stdio.h>

struct person

int age;

float weight;

};

int main()

struct person *personPtr, person1;

personPtr = &person1;
printf("Enter age: ");

scanf("%d", &personPtr->age);

printf("Enter weight: ");

scanf("%f", &personPtr->weight);

printf("Displaying:\n");

printf("Age: %d\n", personPtr->age);

printf("weight: %f", personPtr->weight);

return 0;

In this example, the address of person1 is stored in the personPtr pointer using personPtr =
&person1;.

Now, you can access the members of person1 using the personPtr pointer.

Dynamic memory allocation of structs

Sometimes, the number of struct variables we declared may be insu icient. we may need
to allocate memory during run-time. Here's how we can achieve this in C programming.

#include <stdio.h>

#include <stdlib.h>

struct person {

int age;

float weight;

char name[30];

};

int main()

struct person *ptr;

int i, n;
printf("Enter the number of persons: ");

scanf("%d", &n);

// allocating memory for n numbers of struct person

ptr = (struct person*) malloc(n * sizeof(struct person));

for(i = 0; i < n; ++i)

printf("Enter first name and age respectively: ");

// To access members of 1st struct person,

// ptr->name and ptr->age is used

// To access members of 2nd struct person,

// (ptr+1)->name and (ptr+1)->age is used

scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);

printf("Displaying Information:\n");

for(i = 0; i < n; ++i)

printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);

return 0;

In the above example, n number of struct variables are created where n is entered by the
user.

To allocate the memory for n number of struct person, we used,

ptr = (struct person*) malloc(n * sizeof(struct person));

Then, we used the ptr pointer to access elements of person.


C Dynamic Memory Allocation

Additional Example program in malloc() and free():

// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");

scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated

if(ptr == NULL) {

printf("Error! memory not allocated.");

exit(0);

printf("Enter elements: ");

for(i = 0; i < n; ++i) {

scanf("%d", ptr + i);

sum += *(ptr + i);

printf("Sum = %d", sum);

// deallocating the memory

free(ptr);
return 0;

Expected output:

Enter number of elements: 3

Enter elements: 100

20

36

Sum = 156

Here, we have dynamically allocated the memory for n number of int.

Example : calloc() and free()

// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>

#include <stdlib.h>

int main() {

int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");

scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));

if(ptr == NULL) {

printf("Error! memory not allocated.");

exit(0);

printf("Enter elements: ");

for(i = 0; i < n; ++i) {

scanf("%d", ptr + i);


sum += *(ptr + i);

printf("Sum = %d", sum);

free(ptr);

return 0;

Output:

Enter number of elements: 3

Enter elements: 100

20

36

Sum = 156

Example: realloc()

#include <stdio.h>

#include <stdlib.h>

int main() {

int *ptr, i , n1, n2;

printf("Enter size: ");

scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Addresses of previously allocated memory:\n");

for(i = 0; i < n1; ++i)

printf("%pc\n",ptr + i);

printf("\nEnter the new size: ");

scanf("%d", &n2);
// rellocating the memory

ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");

for(i = 0; i < n2; ++i)

printf("%pc\n", ptr + i);

free(ptr);

return 0;

Output:

Enter size: 2

Addresses of previously allocated memory:

26855472

26855476

Enter the new size: 4

Addresses of newly allocated memory:

26855472

26855476

26855480

26855484
File handling in C
Programming
[Link]
Assistant Professor (Senior Grade)
Dept of Mechanical Engineering
ASE-AMRITA VISHWA VIDYAPEETHAM
Coimbatore.
File Handling in C:

File handling in C is the process in which


we create, open, read, write, and close
operations on a file. C language provides
different functions such as fopen(),
fwrite(), fread(), fseek(), fprintf(), etc. to
perform input, output, and many
different C file operations in our
program.
need for File Handling in C
Till now, we have the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry, most programs are
written to store the information fetched from the program. The use of file handling is exactly what the
situation calls for.

In order to understand why file handling is important, let us look at a few features of using files:

• Reusability: The data stored in the file can be accessed, updated, and deleted anywhere and anytime
providing high reusability.
• Portability: Without losing any data, files can be transferred to another in the computer system. The risk of
flawed coding is minimized with this feature.
• Efficient: A large amount of input may be required for some programs. File handling allows you to easily
access a part of a file using few instructions which saves a lot of time and reduces the chance of errors.
• Storage Capacity: Files allow you to store a large amount of data without having to worry about storing
everything simultaneously in a program.
Types of Files in C

A file can be classified into two


types based on the way the file
stores the data. They are as follows:
• Text Files
• Binary Files
Types of Files in C….
1. Text Files
• A text file contains data in the form of ASCII characters and is generally used to store a stream
of characters.
• Each line in a text file ends with a new line character (‘\n’).
• It can be read or written by any text editor.
• They are generally stored with .txt file extension.
• Text files can also be used to store the source code.
2. Binary Files
• A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
• The binary files can be created only from within a program and their contents can only be read by
a program.
• More secure as they are not easily readable.
• They are generally stored with .bin file extension.
C File Operations

C file operations refer to the different possible operations that


we can perform on a file in C such as:
[Link] a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
[Link] an existing file – fopen()
[Link] from file – fscanf() or fgets()
[Link] to a file – fprintf() or fputs()
[Link] to a specific location in a file – fseek(), rewind()
[Link] a file – fclose()
Functions for C File
Operations
File Pointer in C

A file pointer is a reference to a particular position in the opened file. It is used in


file handling to perform all file operations such as read, write, close, etc. We use
the FILE macro to declare the file pointer variable.

The FILE macro is defined inside <stdio.h> header file.

Syntax of File Pointer


FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
Pattern Printing :

1. Printing a CAR

#include <stdio.h>

// Main function where the execution begins

int main() {

// Print the top of the car

printf(" _______ \n");

printf(" ____/ \\____ \n");

printf("| _| _ | \n");

printf("|__| |________| |__|\n");

printf(" () | | () \n");

printf(" |______| \n");

// Return 0 indicates successful execution

return 0;

Explanation:

1. #include <stdio.h>: This line includes the Standard Input Output header file which is nec
essary for using printf function.

2. int main() {: The main function where the program execution starts.

3. printf(" _______ \n");: Prints the top part of the car. \n is used to move to the next line.

4. printf(" ____/ \\____ \n");: Prints the roof and windows of the car.

5. printf("| _| _ | \n");: Prints the main body of the car.

6. printf("|__| |________| |__|\n");: Prints the car's doors.

7. printf(" () | | () \n");: Prints the wheels of the car.

8. printf(" |______| \n");: Prints the bottom part of the car.

9. return 0;: Indicates that the program executed successfully.


2. pattern—a pyramid—in C
#include <stdio.h>

// Main function where the execution begins


int main() {
int i, j, rows = 5; // Variables for loops and number of rows in the pattern

// Loop through each row


for(i = 1; i <= rows; i++) {
// Print spaces to align the stars
for(j = i; j < rows; j++) {
printf(" ");
}
// Print stars for the pyramid pattern
for(j = 1; j <= (2 * i - 1); j++) {
printf("*");
}
// Move to the next line after printing each row
printf("\n");
}

// Return 0 indicates successful execution


return 0;
}

Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. int main() {: The main function where the program execution starts.
3. int i, j, rows = 5;: Declares variables for loops and the number of rows.
4. for(i = 1; i <= rows; i++) {: Outer loop to iterate through each row.
5. for(j = i; j < rows; j++) { printf(" "); }: Prints spaces to align the stars in a pyramid shape.
6. for(j = 1; j <= (2 * i - 1); j++) { printf("*"); }: Prints stars for the pyramid pattern.
7. printf("\n");: Moves to the next line after printing each row.
8. return 0;: Indicates that the program executed successfully.

3. Pascals Triangle Pattern :


#include <stdio.h>

// Function to print Pascal's Triangle


void printPascal(int n) {
int arr[n][n];

// Initialize the first row and first column


for (int line = 0; line < n; line++) {
for (int i = 0; i <= line; i++) {
// The first and last values in every row are 1
if (line == i || i == 0) {
arr[line][i] = 1;
} else {
// Other values are the sum of values just above and left of above
arr[line][i] = arr[line-1][i-1] + arr[line-1][i];
}
printf("%d ", arr[line][i]);
}
printf("\n");
}
}

int main() {
int n = 5; // Number of rows in Pascal's Triangle
printPascal(n);
return 0;
}

Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. void printPascal(int n) {: Function to print Pascal's Triangle up to n rows.
3. int arr[n][n];: Declares a 2D array to hold the values of Pascal's Triangle.
4. for (int line = 0; line < n; line++) {: Outer loop to handle the number of rows.
5. for (int i = 0; i <= line; i++) {: Inner loop to handle the values in each row.
6. if (line == i || i == 0) { arr[line][i] = 1; }: Sets the first and last values of each row to 1.
7. else { arr[line][i] = arr[line-1][i-1] + arr[line-
1][i]; }: Calculates the other values as the sum of the values just above and to the left of
above.
8. printf("%d ", arr[line][i]);: Prints each value in the row.
9. printf("\n");: Moves to the next line after printing a row.
10. int main() { int n = 5; printPascal(n); return 0; }: Main function to call printPascal with 5 ro
ws.

4. Pascal pattern in the file txt format with name [Link]:

#include <stdio.h>

// Function to print Pascal's Triangle and write to a file


void printPascal(int n) {
FILE *filePtr;
filePtr = fopen("[Link]", "w");

if (filePtr == NULL) {
printf("Failed to create the file.\n");
return;
}

int arr[n][n];
for (int line = 0; line < n; line++) {
for (int i = 0; i <= line; i++) {
// The first and last values in every row are 1
if (line == i || i == 0) {
arr[line][i] = 1;
} else {
// Other values are the sum of values just above and left of above
arr[line][i] = arr[line-1][i-1] + arr[line-1][i];
}
// Print to console
printf("%d ", arr[line][i]);
// Write to file
fprintf(filePtr, "%d ", arr[line][i]);
}
printf("\n");
fprintf(filePtr, "\n");
}

fclose(filePtr);
}

// Function to read and display content from the file


void readAndDisplayFile() {
FILE *filePtr;
char ch;

filePtr = fopen("[Link]", "r");

if (filePtr == NULL) {
printf("Failed to open the file.\n");
return;
}

printf("\nReading from file and displaying the Pascal Triangle:\n");


while ((ch = fgetc(filePtr)) != EOF) {
putchar(ch);
}

fclose(filePtr);
}

int main() {
int n = 5; // Number of rows in Pascal's Triangle

// Generate and store Pascal's Triangle in a file


printPascal(n);
// Read and display the content of the file
readAndDisplayFile();

return 0;
}

Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. void printPascal(int n) {: Function to generate Pascal's Triangle and write it to a file.
3. FILE *filePtr; filePtr = fopen("[Link]", "w");: Opens (or creates) the file "[Link]" in
write mode.
4. int arr[n][n];: Declares a 2D array to hold the values of Pascal's Triangle.
5. Nested loops to generate Pascal's Triangle, print to the console, and write to the file.
6. fclose(filePtr);: Closes the file after writing.
7. void readAndDisplayFile() {: Function to read from the file and display the content.
8. filePtr = fopen("[Link]", "r");: Opens the file "[Link]" in read mode.
9. while ((ch = fgetc(filePtr)) != EOF) { putchar(ch); }: Reads characters from the file and prin
ts them to the console.
10. fclose(filePtr);: Closes the file after reading.
11. int main() { int n = 5; printPascal(n); readAndDisplayFile(); return 0; }: Main function to cal
l printPascal and readAndDisplayFile.
5. User input alphabet pyramid pattern printing infinity:
#include <stdio.h>

int main() {
char alphabet = 'A';
int i, j, rows;

// Ask user for the number of rows


printf("Enter the number of rows: ");
scanf("%d", &rows);

// Loop to create the pyramid


for (i = 0; i < rows; i++) {
// Print spaces for alignment
for (j = rows; j > i; j--) {
printf(" ");
}
// Print alphabets for each row
for (j = 0; j <= i; j++) {
printf("%c ", alphabet + j);
}
printf("\n");
}

return 0;
}
Explanation:
1. #include <stdio.h>: Includes the Standard Input Output header file.
2. char alphabet = 'A';: Declares a variable to store the starting alphabet character.
3. printf("Enter the number of rows: "); scanf("%d", &rows);: Prompts the user to enter the n
umber of rows for the pyramid.
4. Nested loops to generate the pyramid:
 First loop: Prints spaces for alignment.
 Second loop: Prints the alphabets for each row.
5. printf("\n");: Moves to the next line after printing each row.

You might also like