0% found this document useful (0 votes)
7 views67 pages

Cse1008l Lab Manual

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

CSE1008L PROGRAMMING AND

PROBLEM-SOLVING USING C LAB


LABORATORY MANUAL
School of Engineering & Sciences
Department of Computer Science and Engineering
(Instructor Version)

G D Goenka University
Gurgaon, Haryana

1|P a g e
The document is for internal circulation only.

Copyright © 2024 G D Goenka University. All rights reserved.

All materials on these pages are copyrighted by the G D Goenka University. All rights reserved.
Reproduction, modification, retransmission, in any form or by any means, electronic, mechanical
or otherwise, for reasons other than personal use, is strictly prohibited without prior written
permission.

First Edition
September 2024

Published by:
SCHOOL OF ENGINEERING & SCIENCES
Department of Computer Science and Engineering
G D Goenka University
Gurgaon, Haryana

2|P a g e
PREFACE

The School of Engineering & Sciences (SoES), GDGU has prepared this laboratory
manual. It is designed as an instruction book for purposes listed in order of
importance as follows:
1. To provide techniques, procedures and precautions related to the
experiments.
2. To provide the laboratory safety and general rules and instructions.
3. To provide a general reference book that will give information which will
assist in the understanding of details about the laboratory and the experiment
to be performed.
The manual is prepared with the idea that the revisions must be made periodically
to have the available text that represents the experiments. It has been tried to
maintain the format with diagrams, tables and illustrations.
It is believed that the information in the manual will enhance the practical skills of
the students along with developing the base of the subject.
Any suggestions and comments for further improvement of this manual will be
gratefully acknowledged.

Authors
G D Goenka University, Gurgaon

3|P a g e
VISION AND MISSION

Vision

To be a globally reputed multidisciplinary institution focused on science and


technology, enabling research, innovation, and sustainability, and producing
socially responsible professionals.
Mission

The Mission of School of Engineering and Sciences is to produce globally competent


engineering and sciences professionals through Strong foundation in fundamental
knowledge and skills through experiential learning.
A comprehensive educational experience combining foundational knowledge,
research, and practical application in engineering, sciences, and technology.
A unique academic curriculum crafted through collaboration with key
stakeholders, including industry leaders and professional organizations. State-of-
the-art facilities and effective content delivery by qualified faculty members who
instill the notion of lifelong learning.
International and national exchange programs for faculty members and students
with leading academic and research institutions. Scholarly activities that create and
transfer new knowledge.
Offering internship opportunities and live projects with local industry to foster
innovation and promote sustainable industrialization.

4|P a g e
General Rules and Instructions:
Instruction for Students

To complete all the experiments within time, to understand them completely and
effectively, each student must obey the following points:

General discipline in the Lab

Discipline is always given the highest precedence for maintaining the quality
standard of your lab. Any misconduct will be seriously dealt with and immediately
responded without prior notification.
To ensure a pleasant, productive and comfortable experience for all of our users,
you are directed to adhere to the following guidelines:
1. Students will not be allowed after ten minutes from the scheduled time.

2. Students will not leave the lab till the period is over.

3. Attendance in the lab class is compulsory.

4. Students should maintain silence while performing the experiments.

5. Students should not attend a different lab group/section other than the one
assigned at the beginning of the session.

6. Please help us to keep the facility (Equipment’s- etc.) clean by discarding


trash in the receptacles.

7. Please respect the sensitivities of your peers and refrain from viewing any
inappropriate content.

8. Any attempt on Hacking information will be reciprocated with serious


consequences.

Please abide by the rules and make appropriate use of all facilities. Users found to
be damaging computer configurations, accessing content or systems illegally or
attempting to compromise security may be deprived of the facility or will be fined.

5|P a g e
Preparations and Performance
1. Students should come to the lab thoroughly prepared on the experiments
they are assigned to perform on that day.
2. Faculty may check their preparation and understanding of the
experiments. If not found satisfactory, students may be debarred from
doing the experiments.
3. Students should save the results (Screenshots) of their programs performed
during lab session.
4. Students must bring the lab manual on each practical class with
Algorithm, Flowchart, Program and Results (Screenshots) of the last
experiments performed complete in all respect.
5. Students without lab manual will not be allowed to do the experiments and
hence lose their attendance.

Lab Report

1. Each student is required to write a complete report of the


experiment he/she has performed and bring to lab class
for evaluation in the next working lab.

2. Report should be written very clearly, and lab record


should be maintained neatly.

The lab report must contain the following:

1. Duly completed title page


2. Theory/ Algorithms/ Flowcharts
3. Code of Program
4. Screenshots of Results

6|P a g e
Safety Measures

1. Do not leave your personal belongings unattended. The Computing Labs


and Staff will not be responsible for any lost personal items.

2. In the event of fire, please follow the directions from the Labs Staff.

7|P a g e
CSE1008L: PROGRAMMING AND PROBLEM-SOLVING USING C LAB
2024-25 /Batch

LIST OF EXPERIMENTS

S.No. Topic Page No.


1 Conversion of numbers from decimal to binary or hexadecimal number systems and
vice versa.
2 Design a flowchart for a program that takes two numbers as input from the user and
then performs the following operations:
(i) Add the two numbers.
(ii) Subtract the second number from the first number.
(iii) Multiply the two numbers.
(iv) Divide the first number by the second number (ensure to handle division by
zero).
The flowchart should include decision points to handle division by zero and should
clearly illustrate the flow of the program from input to output.
3 Design a flowchart for a program that calculates the total cost of a customer shopping
cart items, including tax and any applicable discounts. The program should have the
following features:
(i)Prompt the user to input the prices and quantities of each item they wish to purchase.
(ii) Calculate the subtotal by multiplying the price of each item by its quantity and
summing up all the totals.
(iii)Apply any applicable discounts based on the total purchase amount. For example,
if the total purchase amount is above a certain threshold, apply a percentage discount.
(iv)Calculate the tax on the subtotal based on a predetermined tax rate.
(v)Add the tax to the subtotal to obtain the total cost.
(vi)Display the subtotal, any discounts applied, the tax amount, and the final total cost
to the user.
You can break down the program into separate modules or functions, each responsible
for a specific calculation (e.g., subtotal calculation, discount calculation, tax
calculation), and then integrate them into the main program flowchart.
4 Identify and correct the syntactical errors in given program (example given below) to
make it compile and run correctly.

8|P a g e
5 Identify and correct the semantic errors in a given program (example given below) to
make it compile and run correctly.

6 Write a C program that takes an integer as input from the user and prints whether the
number is positive, negative, or zero. Additionally, if the number is positive, check if
it’s even or odd and print that information as well.

7 Write a C program to implement a simple guessing game. The program should generate
a random number between 1 and 100 (inclusive) and prompt the user to guess the
number. After each guess, the program should provide feedback to the user, indicating
whether the guess is too high, too low, or correct. The user should continue guessing
until they correctly identify the random number. Additionally, limit the number of
guesses to 10, and if the user exceeds this limit without guessing the correct number,
display a message indicating that they have lost the game

8 Write a C program that calculates the value of a mathematical expression involving


trigonometric functions and logarithms. The program should prompt the user to input
the values of variables and evaluate the expression. Ensure to handle error cases such
as division by zero or undefined values. Sample mathematical expression to evaluate:
sin(x)+cos(y)/log(z)

9 Write a C program that calculates the factorial of a non-negative integer using


recursion. The factorial of a non-negative integer n, denoted as n!, is the product of all
positive integers less than or equal to n. The factorial of n is defined as:
n! = n*(n-1)*(n-2)*..*3*2*1

10 Write a C Program with an algorithm and flowchart to make a simple calculator


performing +,-,/,* using switch-case. The program takes two integer operands and one
operator from the user, performs the operation and then prints the result.

11 Write a C program that defines macros for mathematical operations (e.g., addition,
subtraction, multiplication, division) and
uses them to perform calculations. The program should use macros to define the
operations and then demonstrate their usage in various mathematical expressions.
12 The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones, usually starting with 0 and 1:

9|P a g e
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Write a C program to generate the first 20 terms of the Fibonacci sequence and print
them.
13 Write a C program that calculates the factorial of a given number using a separate function for
the factorial calculation. The program should prompt the user to enter a non-negative integer,
calculate its factorial using the factorial function, and then print the result.

15 Write a C program to calculate the average of a set of numbers. The program should prompt
the user to enter the number of elements in the set, then prompt the user to enter each element.
Finally, the program should calculate and print the average of the entered numbers using
separate functions for input, calculation, and output. Additionally, use an external variable to
keep track of the sum of the numbers.

16 Write a C program that defines a function to count the number of vowels in a string
using character pointers. The program
should prompt the user to input a string, call the function to count the vowels, and then
print the count
17 Write a C program that defines a function to swap the values of two integers using
pointers. The program should prompt
the user to input two integers, call the swap function to swap their values, and then
print the swapped values.
18 Write a C program that simulates a simple banking system. The program should
include the following functionalities:
a. Deposit: Allow the user to deposit a certain amount into their account.
b. Withdraw: Allow the user to withdraw a certain amount from their account.
c. Check balance: Display the current balance in the account.
Use static variables to keep track of the total balance across all transactions. Ensure that
the total balance is shared
among all instances of the banking system.

19 Write a C program that takes an array of integers as input, calculates the sum and
average of the elements using pointers, and then prints the sum and average.

20 Write a C program that takes two nxn matrix as input from the user, calculates the
product of the matrices and prints it.

21 Write a C program that simulates a simple text editor. The program should allow the
user to perform the following
operations on a text string:
a. Append: Append a string to the end of the current text.
b. Insert: Insert a string at a specific position in the current text.
c. Delete: Delete a substring from the current text.
d. Replace: Replace a substring in the current text with another string.
e. Print: Print the current text.

22 Write a C program that implements a recursive function to generate all possible


combinations of a given set of characters.
10 | P a g e
The program should take a string of characters as input and print all possible
combinations of those characters.
For example, given the input string “ABC”, the program should generate the following
combinations:
a. ABC
b. ACB
c. BAC
d. BCA
e. CAB
f. CBA
23 Write a C program that defines a structure called Student to store the details of a
student including name, roll number, and marks in three subjects (Physics, Chemistry,
and Mathematics). The program should prompt the user to input the details of three
students, store them in an array of Student structures, and then print the details of all
students.
24 Write a C program that defines a structure called Book to store the details of books
including title, author, and price. The program should then create an array of Book
structures to store the details of three books. After storing the details, the program
should print the details of all books.
25 Write a C program that defines a structure called Employee to store the details of an
employee including name, ID, and salary. The program should then create a pointer to
an Employee structure and allocate memory for it dynamically using malloc(). After
allocating memory, prompt the user to input the details of an employee using the
pointer, and then print the details of the employee.
26 Write a C program that simulates a simple online shopping system. The program
should include the following
functionalities:
a. Add item to cart: Allow the user to add items to their shopping cart.
b. Remove item from cart: Allow the user to remove items from their shopping cart.
c. View cart: Display the items currently in the user’s shopping cart.
Ensure that each user has their own shopping cart, and use local variables to represent
the items in the cart.

27 Write a C program that defines a union called Data to represent a data structure that can
store either an integer or a
floating-point number. Additionally, define a structure called BitField to represent a
data structure that stores a set of bit-
fields including a flag, an integer value, and a floating-point value. Then, the program
should create variables of type Data
and BitField, initialize them with some values, and print their contents.
28 Write a C program that defines a typedef for a structure called Point to represent a
point in 2D space. The structure should
have two members: x and y, representing the coordinates of the point. Then, the
program should create a variable of type
Point and initialize it with some values. Finally, it should print the coordinates of the
point.

NAME & SIGNATURE OF COURSE COORDINATOR

11 | P a g e
Experimental Setup Details

Software Requirements: VSCODE

Hardware Requirements:
Operating system: Windows 10 (64 bit) or higher
Processor: A Core i5 (3.10 GHz) or higher processor
RAM: 8 GB of RAM
Storage: 32 GB of available storage space
Monitor resolution: 1366 x 768

12 | P a g e
Experiment 1:
Title Conversion of numbers from decimal to binary or hexadecimal number systems and vice versa.
(a)To familiarize the students about number systems
(b) To represent numbers in various numeration systems
Objectives
(c) To convert a numeral from one base to another base

Theory A number system is defined as a system of writing for expressing numbers. It is the
mathematical notation for representing numbers of a given set by using digits in a consistent
manner. It provides a unique representation of every number and represents the arithmetic and
algebraic structure of the figures. It also allows us to operate arithmetic operations like addition,
subtraction, and division.
There are various types of the number system in mathematics. The four most common number
system types are:
System Base Symbols

Decimal 10 0, 1, … 9

Binary 2 0, 1

Octal 8 0, 1, … 7
Hexa-decimal 16 0, 1, … 9,
A, B, … F

Practice Questions
1. What is the decimal equivalent of the number 3A16?
2. What is the 8 bit unsigned binary result of 5610 − 3110
3. What is the result of adding 710 and −410 using 8 bit signed binary notation?
4. Which of the following 4 bit Excess 3 numbers is equivalent to 510?
5. Consider the equation (123)5 = (x8)y with x and y as unknown. The number of possible
solutions is _____ .
6. The range of integers that can be represented by an n bit 2's complement number system
is:
7. Convert binary 111111110010 to hexadecimal.
8. The representation of octal number (532.2)8 in decimal is ________
9. The decimal equivalent of the octal number (645)8 is ______
10. The quantity of double word is ________
11. Octal to binary conversion: (24)8 =?
12. Convert binary to octal: (110110001010)2 =?
13. The octal number (651.124)8 is equivalent to (______)10.
14. Convert the hexadecimal number (1E2)16 to decimal:

13 | P a g e
Experiment 2
To familiarize the students with flowcharts, pseudocode and algorithms.
Title
(a) Design a flowchart for a program that takes two numbers as input from the user and then
performs the following operations:
(i) Add the two numbers.
(ii) Subtract the second number from the first number.
(iii) Multiply the two numbers.
(iv) Divide the first number by the second number (ensure to handle division by zero).
The flowchart should include decision points to handle division by zero and should
clearly illustrate the flow of the program from input to output.
(b) Design a flowchart for a program that calculates the total cost of a customer shopping cart
items, including tax and any applicable discounts. The program should have the
following features:
(i)Prompt the user to input the prices and quantities of each item they wish to purchase.
Objectives
(ii) Calculate the subtotal by multiplying the price of each item by its quantity and summing
up all the totals.
(iii). Apply any applicable discounts based on the total purchase amount. For example, if the
total purchase amount is above a certain threshold, apply a percentage discount.
(iv)Calculate the tax on the subtotal based on a predetermined tax rate.
(v)Add the tax to the subtotal to obtain the total cost.
(vi)Display the subtotal, any discounts applied, the tax amount, and the final total cost to the
user.
You can break down the program into separate modules or functions, each responsible for a
specific calculation (e.g., subtotal calculation, discount calculation, tax calculation), and then
integrate them into the main program flowchart.

Theory INTRODUCTION
The flowchart is a mean of visually presenting the flow of data through an
information processing systems, the operations performed within system and the
sequence in which they are performed.
A flowchart is a pictorial representation of an algorithm in which the steps are
drawn, in the form of different shapes of boxes and the logical flow indicated by
inter connecting arrows.
Meaning of a Flowchart
A flowchart is a diagrammatic representation that illustrates the sequence of
operations to be performed to get the solution of a problem. Once the flowchart is
drawn, it becomes easy to write the program in any high level language. Hence, it is
14 | P a g e
correct to say that a flowchart is a must for the better documentation of a complex
program.
ADVANTAGES:
Reasons for using flowcharts as a problem-solving tool are:
➢ Makes logic clear
➢ Communication: flowcharts are a good way of communicating the logic
of a system to all concerned.
➢ Using in coding, flowcharts act as a guide during the system’s analysis
and program development phase.

➢ Effective analysis: problem can be analyzed in more effective way.


➢ Efficient program maintenance: The maintenance of a program becomes easy
with the help of flowchart.
➢ Proper documentation: flowcharts serve as a good program documentation.
DISADVANTAGES:
a) Complex logic: Sometimes, the program logic is quite complicated. In this
case, flowchart becomes complex and clumsy.
b) Alterations and modifications: If alterations are required the flowchart may
require re-drawing completely.
c) The essentials of what is done can easily be lost in the technical details of how
it is done.
SYMBOLS:
On flowcharts different geometric shapes are used called flowchart symbols.
Some standard symbols for drawing flowcharts are:

15 | P a g e
Experiment 3
Title To familiarize the students with different operators in C and how to use them to solve expressions.

Objectives (a)Identify and correct the syntactical errors in a given program (example given below) to make it
compile and run correctly.

(b) Identify and correct the semantic errors in a given program (example given below) to make
it compile and run correctly.

16 | P a g e
Theory An operator is a symbol that operates on a value or a variable. For example: + is an operator to
perform addition.
C has a wide range of operators to perform various operations.
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values (constants and variables).
Operator Meaning of Operator
+ Addition or unary plus
- subtraction or unary minus
* Multiplication
/ Division
% remainder after division (modulo division)

C Increment and Decrement Operators


C programming has two operators increment ++ and decrement -- to change the value of an
operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results true or false. Logical operators are commonly used in decision making in C
programming.
Operator Meaning Example

17 | P a g e
&& Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression
((c==5) && (d>5)) equals to 0.
|| Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression
((c==5) || (d>5)) equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression! (c==5) equals to 0.

18 | P a g e
Experiment 4
To familiarize the students with if-else loop.
Title
(a) Write a C program that takes an integer as input from the user and prints whether the
number is positive, negative, or zero. Additionally, if the number is positive, check if it’s
even or odd and print that information as well.
(b) Write a C program to implement a simple guessing game. The program should generate
a random number between 1 and 100 (inclusive) and prompt the user to guess the number.
After each guess, the program should provide feedback to the user, indicating whether the
guess is too high, too low, or correct. The user should continue guessing until they
correctly identify the random number. Additionally, limit the number of guesses to 10,
and if the user exceeds this limit without guessing the correct number, display a message
indicating that they have lost the game
(c) Write a C program that calculates the value of a mathematical expression involving
trigonometric functions and logarithms. The program should prompt the user to input the
values of variables and evaluate the expression. Ensure to handle error cases such as
Objective division by zero or undefined values.Sample mathematical expression to evaluate:
sin(x)+cos(y)/log(z)
(d) Write a C program that calculates the factorial of a non-negative integer using recursion.
The factorial of a non-negative integer n, denoted as n!, is the product of all positive
integers less than or equal to n. The factorial of n is defined as:
n! = n*(n-1)*(n-2)*..*3*2*1
( e ) Write a C program that defines macros for mathematical operations (e.g.,
addition, subtraction, multiplication, division) and
uses them to perform calculations. The program should use macros to define the operations and
then demonstrate their usage in various mathematical expressions.

19 | P a g e
Theory
We have a number of situations where we may have to change the order of execution of
statements based on certain conditions or repeat a group of statements until certain specified
conditions are met. This involves a kind of decision making to see whether a particular condition
has occurred or not and then direct the computer to execute certain statements accordingly.
C language possesses such decision-making capabilities and supports the following statements
known as control or decision-making statements.
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement
Decision making with ‘if’ statement
The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction
with an expression. It takes the following form:
𝑖𝑓(𝑡𝑒𝑠𝑡 𝑒𝑥𝑝𝑟𝑒𝑠𝑠𝑖𝑜𝑛)
It allows the computer to evaluate the expression first and then depending on whether the value
of expression (or condition) is true (1) or false (0), it transfers the control to a particular
statement. This point of program has two paths to follow, one for the true condition and the other
for the false condition.

Entry

test
expression? False

True

Two-way Branching

Examples of decision making, using if statement are


1. if (bank balance is zero) borrow money

20 | P a g e
2. if(age is more than 60) person retires
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
1. Simple if statement
2. if…else statement
3. Nested if…else statement
4. else if ladder
Simple ‘if’ statement
The general form of a ‘simple if’ statement is
‘statement_block’ may be a single statement or a group of statements. If the test expression is
true the ‘statement_block’ will be executed, otherwise the ‘statement_block’ will be skipped and
the execution will jump to ‘statement_x’.
Flowchart for Simple If

PROGRAM (a)
: #include <stdio.h>
int main() {
int number;

// Input: Get the integer from the user


printf("Enter an integer: ");
scanf("%d", &number);

// Check if the number is positive, negative, or zero


if (number > 0) {
printf("The number is positive.\n");

// Check if the positive number is even or odd


if (number % 2 == 0) {
printf("The number is even.\n");
} else {
printf("The number is odd.\n");
}
21 | P a g e
} else if (number < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}

return 0;
}

OUTPUT :

Enter an integer: 6
The number is positive.
The number is even.

PROGRAM (b):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int randomNumber, userGuess;
int attempts = 0;
const int maxAttempts = 10;

// Seed the random number generator


srand(time(NULL));
randomNumber = rand() % 100 + 1; // Random number between 1 and 100

printf("Welcome to the Guessing Game!\n");


printf("I have selected a number between 1 and 100.\n");
printf("You have %d attempts to guess it correctly.\n", maxAttempts);

// Game loop
while (attempts < maxAttempts) {
printf("Enter your guess: ");
scanf("%d", &userGuess);
attempts++;

if (userGuess < 1 || userGuess > 100) {


printf("Please guess a number between 1 and 100.\n");
attempts--; // Don't count invalid attempts
continue;
}

if (userGuess < randomNumber) {


printf("Too low! Try again.\n");
} else if (userGuess > randomNumber) {
printf("Too high! Try again.\n");
} else {
22 | P a g e
printf("Congratulations! You've guessed the correct number: %d\n", randomNumber);
break; // Exit the loop if the guess is correct
}

printf("Attempts remaining: %d\n", maxAttempts - attempts);


}

if (attempts == maxAttempts) {
printf("Sorry! You've used all your attempts. The correct number was: %d\n",
randomNumber);
}

return 0;
}

OUTPUT :

Welcome to the Guessing Game!


I have selected a number between 1 and 100.
You have 10 attempts to guess it correctly.
Enter your guess: 50
Too low! Try again.
Attempts remaining: 9
Enter your guess: 75
Too high! Try again.
Attempts remaining: 8
Enter your guess: 60
Too low! Try again.
Attempts remaining: 7
Enter your guess: 70
Congratulations! You've guessed the correct number: 70

PROGRAM C:
#include <stdio.h>
#include <math.h>

int main() {
double x, y, z;
double result;

// Prompt user for input


printf("Enter the value of x (in radians): ");
scanf("%lf", &x);
printf("Enter the value of y (in radians): ");
scanf("%lf", &y);
printf("Enter the value of z (must be positive for log): ");
scanf("%lf", &z);

// Check for invalid values


if (z <= 0) {
printf("Error: Logarithm of non-positive value is undefined.\n");
23 | P a g e
return 1; // Exit with error code
}

// Calculate the logarithm of z


double logZ = log(z);

// Check for division by zero


if (logZ == 0) {
printf("Error: Division by zero encountered.\n");
return 1; // Exit with error code
}

// Evaluate the expression


result = sin(x) + (cos(y) / logZ);

// Print the result


printf("Result of the expression sin(x) + cos(y) / log(z) = %lf\n", result);

return 0; // Exit successfully


}
OUTPUT :
Enter the value of x (in radians): 1.0
Enter the value of y (in radians): 0.5
Enter the value of z (must be positive for log): 10
Result of the expression sin(x) + cos(y) / log(z) = 1.181891

Program (d)

#include <stdio.h>

// Function to calculate factorial using recursion


unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: 0! = 1 and 1! = 1
} else {
return n * factorial(n - 1); // Recursive case
}
}

int main() {
int num;

// Prompt the user for input


printf("Enter a non-negative integer: ");
scanf("%d", &num);

// Check for non-negative integer


if (num < 0) {
printf("Error: Factorial is not defined for negative integers.\n");
return 1; // Exit with error code
}
24 | P a g e
// Calculate factorial
unsigned long long result = factorial(num);

// Print the result


printf("Factorial of %d is %llu\n", num, result);

return 0; // Exit successfully


}

OUTPUT :

Enter a non-negative integer: 5


Factorial of 5 is 120

Program (e)
#include <stdio.h>

// Define macros for mathematical operations


#define ADD(a, b) ((a) + (b))
#define SUBTRACT(a, b) ((a) - (b))
#define MULTIPLY(a, b) ((a) * (b))
#define DIVIDE(a, b) ((b) != 0 ? ((a) / (b)) : 0) // Check for division by zero

int main() {
// Declare variables
double num1, num2;

// Prompt the user for input


printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);

// Perform calculations using macros


double sum = ADD(num1, num2);
double difference = SUBTRACT(num1, num2);
double product = MULTIPLY(num1, num2);
double quotient = DIVIDE(num1, num2);

// Print the results


printf("Results:\n");
printf("Addition: %.2lf + %.2lf = %.2lf\n", num1, num2, sum);
printf("Subtraction: %.2lf - %.2lf = %.2lf\n", num1, num2, difference);
printf("Multiplication: %.2lf * %.2lf = %.2lf\n", num1, num2, product);
printf("Division: %.2lf / %.2lf = %.2lf\n", num1, num2, quotient);

return 0;
}

OUTPUT :
Enter two numbers: 12.5 3.5
Results:
25 | P a g e
Addition: 12.50 + 3.50 = 16.00
Subtraction: 12.50 - 3.50 = 9.00
Multiplication: 12.50 * 3.50 = 43.75
Division: 12.50 / 3.50 = 3.57

26 | P a g e
Experiment 5
Title To familiarize the students with switch-case statements.

Objectives Write a C Program with an algorithm and flowchart to make a simple calculator performing +,-,/,*
using switch-case. The program takes two integer operands and one operator from the user,
performs the operation and then prints the result.

Theory The switch statement allows us to execute one code block among many alternatives.You can do
the same thing with the if...else..if ladder. However, the syntax of the switch statement is much
easier to read and write.

Syntax of switch...case

switch (expression)

case constant1:

// statements

break;

case constant2:

// statements

break;

default:

// default statements

How does the switch statement work?

The expression is evaluated once and compared with the values of each case label.

27 | P a g e
• If there is a match, the corresponding statements after the matching label are executed. For
example, if the value of the expression is equal to constant2, statements after case constant2: are
executed until break is encountered.

• If there is no match, the default statements are executed.

• If we do not use break, all statements after the matching label are executed.

• The default clause inside the switch statement is optional.

Rules for switch-case

1) The expression provided in the switch should result in a constant value otherwise it would
not be valid.

Valid expressions for switch:

// Constant expressions allowed

switch(1+2+23)

switch(1*2+3%4)

// Variable expression are allowed provided

// they are assigned with fixed values

switch(a*b+c*d)

switch(a+b+c)

2) Duplicate case values are not allowed.

3) The default statement is optional. Even if the switch case statement do not have a default
statement, it would run without any problem.

4) The break statement is used inside the switch to terminate a statement sequence. When a
break statement is reached, the switch terminates, and the flow of control jumps to the next line

28 | P a g e
following the switch statement.

5) The break statement is optional. If omitted, execution will continue on into the next case.
The flow of control will fall through to subsequent cases until a break is reached.

6) Nesting of switch statements are allowed, which means you can have switch statements
inside another switch. However nested switch statements should be avoided as it makes program
more complex and less readable.
PROGRAM :

#include <stdio.h>

int main() {

int num1, num2;

char operator;

int result;

// User input

printf("Enter first integer: ");

scanf("%d", &num1);

printf("Enter second integer: ");

scanf("%d", &num2);

printf("Enter an operator (+, -, *, /): ");

scanf(" %c", &operator); // Notice the space before %c to consume any leftover whitespace

29 | P a g e
// Perform the operation based on the operator

switch (operator) {

case '+':

result = num1 + num2;

printf("%d + %d = %d\n", num1, num2, result);

break;

case '-':

result = num1 - num2;

printf("%d - %d = %d\n", num1, num2, result);

break;

case '*':

result = num1 * num2;

printf("%d * %d = %d\n", num1, num2, result);

break;

case '/':

if (num2 != 0) {

result = num1 / num2;

printf("%d / %d = %d\n", num1, num2, result);

} else {

printf("Error: Division by zero is not allowed.\n");

30 | P a g e
}

break;

default:

printf("Error: Invalid operator.\n");

return 0;

}
OUTPUT:

Enter first integer: 4

Enter second integer: 6

Enter an operator (+, -, *, /): +

4 + 6 = 10

31 | P a g e
Experiment 6
To familiarize the students with for loop
Title
Objectives (a) Write a C program to print the first 10 natural numbers (1 to 10) in reverse order, one
number per line.

(b) The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones, usually starting with 0 and 1:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

Write a C program to generate the first 20 terms of the Fibonacci sequence and print them.

Theory for Loop


The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{ // statements inside the body of loop }
How for loop works?
• The initialization statement is executed only once.

• Then, the test expression is evaluated. If the test expression is evaluated to false, the for
loop is terminated.

• However, if the test expression is evaluated to true, statements inside the body of for loop
are executed, and the update expression is updated.

• Again the test expression is evaluated.

• This process goes on until the test expression is false. When the test expression is false, the
loop terminates.

PROGRAM A)

#include <stdio.h>

int main() {

// Loop from 10 to 1

for (int i = 10; i >= 1; i--) {

printf("%d\n", i);

return 0;

32 | P a g e
}

OUTPUT :

10

PROGRAM (B)

#include <stdio.h>

int main() {

int n = 20; // Number of terms

long long a = 0, b = 1, next;

printf("The first %d terms of the Fibonacci sequence are:\n", n);

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

if (i == 0) {

printf("%lld\n", a); // Print the first term (0)

} else if (i == 1) {

printf("%lld\n", b); // Print the second term (1)

} else {

33 | P a g e
next = a + b; // Calculate the next term

printf("%lld\n", next); // Print the next term

a = b; // Update a to the previous term

b = next; // Update b to the current term

return 0;

OUTPUT :

The first 20 terms of the Fibonacci sequence are:

13

21

34

55

89

144

233

377

610

34 | P a g e
987

1597

2584

4181

35 | P a g e
Experiment 7:
To familiarize the students with functions in C
Title
Objectives (a) Write a C program that calculates the factorial of a given number using a separate function for the
factorial calculation. The program should prompt the user to enter a non-negative integer, calculate
its factorial using the factorial function, and then print the result.

(b) Write a C program to calculate the average of a set of numbers. The program should prompt the
user to enter the number of elements in the set, then prompt the user to enter each element. Finally,
the program should calculate and print the average of the entered numbers using separate functions
for input, calculation, and output. Additionally, use an external variable to keep track of the sum of
the numbers.

(c) Write a C program that defines a function to count the number of vowels in a string using character
pointers. The program should prompt the user to input a string, call the function to count the
vowels, and then print the count

(d) Write a C program that defines a function to swap the values of two integers using pointers. The
program should prompt the user to input two integers, call the swap function to swap their values,
and then print the swapped values.

36 | P a g e
Theory A function is a set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a function so
that instead of writing the same code again and again for different inputs, we can call the function.
Why do we need functions?
Functions help us in reducing code redundancy. If functionality is performed at multiple places in
software, then rather than writing the same code, again and again, we create a function and call it
everywhere. This also helps in maintenance as we have to change at one place if we make future
changes to the functionality.
Functions make code modular. Consider a big file having many lines of codes. It becomes really
simple to read and use the code if the code is divided into functions. Functions provide
abstraction. For example, we can use library functions without worrying about their internal
working.
PROGRAM A)
#include <stdio.h>

// Function prototype
long long factorial(int n);

int main() {
int number;

// Input: Prompt the user to enter a non-negative integer


printf("Enter a non-negative integer: ");
scanf("%d", &number);

// Check if the number is negative


if (number < 0) {
printf("Error: Factorial is not defined for negative integers.\n");
} else {
// Calculate factorial
long long result = factorial(number);
// Output the result
printf("The factorial of %d is %lld.\n", number, result);
}

return 0;
}

// Function to calculate factorial


long long factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! is 1
} else {
long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i; // Multiply each number from 1 to n
}
return fact;
}
}
OUTPUT :
37 | P a g e
Enter a non-negative integer: 5
The factorial of 5 is 120.

PROGRAM b)

#include <stdio.h>

// Function prototypes
void inputNumbers(int *numbers, int count);
float calculateAverage(int *numbers, int count);
void outputAverage(float average);

// External variable to keep track of the sum


long long sum = 0;

int main() {
int count;

// Input: Prompt the user for the number of elements


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

// Declare an array to hold the numbers


int numbers[count];

// Get the numbers from the user


inputNumbers(numbers, count);

// Calculate the average


float average = calculateAverage(numbers, count);

// Output the average


outputAverage(average);

return 0;
}

// Function to input numbers


void inputNumbers(int *numbers, int count) {
printf("Enter %d numbers:\n", count);
for (int i = 0; i < count; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &numbers[i]);
sum += numbers[i]; // Update the external sum variable

38 | P a g e
}
}

// Function to calculate the average


float calculateAverage(int *numbers, int count) {
return (float)sum / count; // Calculate average using the external sum variable
}

// Function to output the average


void outputAverage(float average) {
printf("The average of the entered numbers is: %.2f\n", average);
}
OUTPUT :
Enter the number of elements: 5
Enter 5 numbers:
Number 1: 6
Number 2: 5
Number 3: 4
Number 4: 3
Number 5: 2
The average of the entered numbers is: 4.00
Program c)
#include <stdio.h>

// Function to count vowels in a string


int countVowels(const char *str) {
int count = 0;
while (*str) { // Loop until the end of the string
// Check if the character is a vowel
if (*str == 'a' || *str == 'e' || *str == 'i' || *str == 'o' || *str == 'u' ||
*str == 'A' || *str == 'E' || *str == 'I' || *str == 'O' || *str == 'U') {
count++;
}
str++; // Move to the next character
}
return count; // Return the total count of vowels
}

int main() {
char inputString[100]; // Array to store the input string

// Prompt the user for input


printf("Enter a string: ");
fgets(inputString, sizeof(inputString), stdin);

39 | P a g e
// Call the function to count vowels
int vowelCount = countVowels(inputString);

// Print the result


printf("Number of vowels in the string: %d\n", vowelCount);

return 0; // Exit successfully


}
OUTPUT :
Enter a string: Hello World!
Number of vowels in the string: 3

Program d)
#include <stdio.h>

// Function to swap two integers using pointers


void swap(int *a, int *b) {
int temp = *a; // Store the value pointed to by a in a temporary variable
*a = *b; // Assign the value pointed to by b to the location pointed to by a
*b = temp; // Assign the value in temp to the location pointed to by b
}

int main() {
int num1, num2;

// Prompt the user for input


printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

// Print original values


printf("Before swapping:\n");
printf("num1: %d\n", num1);
printf("num2: %d\n", num2);

// Call the swap function


swap(&num1, &num2);

// Print swapped values


printf("After swapping:\n");
printf("num1: %d\n", num1);
printf("num2: %d\n", num2);

return 0; // Exit successfully

40 | P a g e
}
OUTPUT :
Enter two integers: 5 10
Before swapping:
num1: 5
num2: 10
After swapping:
num1: 10
num2: 5

41 | P a g e
Experiment 8
To familiarize the students with pointers in C
Title
Objectives (a) Write a C program that simulates a simple banking system. The program should include the
following functionalities:
a. Deposit: Allow the user to deposit a certain amount into their account.
b. Withdraw: Allow the user to withdraw a certain amount from their account.
c. Check balance: Display the current balance in the account.
Use static variables to keep track of the total balance across all transactions. Ensure that the total
balance is shared
among all instances of the banking system.

42 | P a g e
Theory
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in
C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
• Normal variable stores the value whereas pointer variable stores the address of the
variable.

• The content of the C pointer always be a whole number i.e. address.

• Always C pointer is initialized to null, i.e. int *p = null.

• The value of null pointer is 0.

• & symbol is used to get the address of the variable.

• * symbol is used to get the value of the variable that the pointer is pointing to.

• If a pointer in C is assigned to NULL, it means it is pointing to nothing.

• Two pointers can be subtracted to know how many elements are available between these
two pointers.

• But, Pointer addition, multiplication, division are not allowed.

• The size of any pointer is 2 byte (for 16 bit compiler).

PROGRAM (a)

#include <stdio.h>

void deposit(float *balance) {

float amount;

printf("Enter amount to deposit: ");

scanf("%f", &amount);

if (amount > 0) {

*balance += amount;

printf("Successfully deposited: %.2f\n", amount);

} else {

43 | P a g e
printf("Invalid deposit amount!\n");

void withdraw(float *balance) {

float amount;

printf("Enter amount to withdraw: ");

scanf("%f", &amount);

if (amount > 0 && amount <= *balance) {

*balance -= amount;

printf("Successfully withdrew: %.2f\n", amount);

} else if (amount > *balance) {

printf("Insufficient balance!\n");

} else {

printf("Invalid withdrawal amount!\n");

void checkBalance(float balance) {

printf("Current balance: %.2f\n", balance);

int main() {

static float totalBalance = 0; // Static variable to keep track of total balance

int choice;

do {

44 | P a g e
printf("\nSimple Banking System\n");

printf("1. Deposit\n");

printf("2. Withdraw\n");

printf("3. Check Balance\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

deposit(&totalBalance);

break;

case 2:

withdraw(&totalBalance);

break;

case 3:

checkBalance(totalBalance);

break;

case 4:

printf("Exiting the system. Goodbye!\n");

break;

default:

printf("Invalid choice. Please try again.\n");

} while (choice != 4);

return 0;

45 | P a g e
}

OUTPUT :

Simple Banking System

1. Deposit

2. Withdraw

3. Check Balance

4. Exit

Enter your choice: 1

Enter amount to deposit: 500

Successfully deposited: 500.00

Simple Banking System

1. Deposit

2. Withdraw

3. Check Balance

4. Exit

Enter your choice: 3

Current balance: 500.00

Simple Banking System

1. Deposit

2. Withdraw

3. Check Balance

4. Exit

Enter your choice: 2

Enter amount to withdraw: 200

Successfully withdrew: 200.00

46 | P a g e
Simple Banking System

1. Deposit

2. Withdraw

3. Check Balance

4. Exit

Enter your choice: 3

Current balance: 300.00

Simple Banking System

1. Deposit

2. Withdraw

3. Check Balance

4. Exit

Enter your choice: 4

Exiting the system. Goodbye!

47 | P a g e
Experiment 9
To familiarize the students with arrays in C
Title

Objective 1.Write a C program that takes an array of integers as input, calculates the sum and average of the
elements using pointers, and then prints the sum and average.
2. Write a C program that takes two nxn matrix as input from the user, calculates the product of
the matrices and prints it.

48 | P a g e
Theory
An array in C or C++ is a collection of items stored at contiguous memory locations and elements
can be accessed randomly using indices of an array. They are used to store similar type of
elements as in the data type must be the same for all elements. They can be used to store
collection of primitive data types such as int, float, double, char, etc of any particular type. To add
to it, an array in C or C++ can store derived data types such as the structures, pointers etc. Given
below is the picturesque representation of an array.

Why do we need arrays?


We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we
want to store a large number of instances, it becomes difficult to manage them with normal
variables. The idea of an array is to represent many instances in one variable.

PROGRAM 1:
#include <stdio.h>

// Function prototypes
void calculateSumAndAverage(int *arr, int size, int *sum, float *average);

int main() {
int n;

// Input: Prompt the user for the number of elements


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

// Declare the array


int arr[n];

// Input: Get the elements of the array


printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}

int sum = 0;
float average = 0.0;

// Calculate sum and average


calculateSumAndAverage(arr, n, &sum, &average);

// Output the sum and average


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

49 | P a g e
printf("Average: %.2f\n", average);

return 0;
}

// Function to calculate sum and average


void calculateSumAndAverage(int *arr, int size, int *sum, float *average) {
for (int i = 0; i < size; i++) {
*sum += *(arr + i); // Add each element to sum
}
*average = (float)(*sum) / size; // Calculate average
}
OUTPUT :
Enter the number of elements in the array: 5
Enter 5 integers:
Element 1: 22
Element 2: 33
Element 3: 44
Element 4: 55
Element 5: 66
Sum: 220
Average: 44.00

PROGRAM 2:
#include <stdio.h>

#define MAX_SIZE 10 // Define maximum size for the matrices

void inputMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n);


void multiplyMatrices(int first[MAX_SIZE][MAX_SIZE], int second[MAX_SIZE][MAX_SIZE],
int result[MAX_SIZE][MAX_SIZE], int n);
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n);

int main() {
int n;
int first[MAX_SIZE][MAX_SIZE], second[MAX_SIZE][MAX_SIZE],
result[MAX_SIZE][MAX_SIZE];

// Input: Prompt the user for the size of the matrices


printf("Enter the size of the matrices (n): ");
scanf("%d", &n);

// Input first matrix


printf("Enter elements of the first matrix:\n");

50 | P a g e
inputMatrix(first, n);

// Input second matrix


printf("Enter elements of the second matrix:\n");
inputMatrix(second, n);

// Calculate the product of the matrices


multiplyMatrices(first, second, result, n);

// Output the resulting matrix


printf("Product of the matrices:\n");
printMatrix(result, n);

return 0;
}

// Function to input a matrix


void inputMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("Element [%d][%d]: ", i + 1, j + 1);
scanf("%d", &matrix[i][j]);
}
}
}

// Function to multiply two matrices


void multiplyMatrices(int first[MAX_SIZE][MAX_SIZE], int second[MAX_SIZE][MAX_SIZE],
int result[MAX_SIZE][MAX_SIZE], int n) {
// Initialize the result matrix to 0
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = 0;
}
}

// Matrix multiplication
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
result[i][j] += first[i][k] * second[k][j];
}
}
}

51 | P a g e
}

// Function to print a matrix


void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

52 | P a g e
Experiment 10
To familiarize the students with strings in C
Title

Objectives (a) Write a C program that simulates a simple text editor. The program should allow the user to
perform the following
operations on a text string:
a. Append: Append a string to the end of the current text.
b. Insert: Insert a string at a specific position in the current text.
c. Delete: Delete a substring from the current text.
d. Replace: Replace a substring in the current text with another string.
e. Print: Print the current text.
(b) Write a C program that implements a recursive function to generate all possible combinations
of a given set of characters.

The program should take a string of characters as input and print all possible combinations of
those characters.
For example, given the input string “ABC”, the program should generate the following
combinations:
a. ABC
b. ACB
c. BAC
d. BCA
e. CAB
f. CBA

53 | P a g e
Theory
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’.

Declaration of strings: Declaring a string is as simple as declaring a one dimensional array.

Syntax for declaring a string: char str_name[size];

In the above syntax str_name is any name given to the string variable and size is used define the
length of the string, i.e the number of characters strings will store. there is an extra terminating
character which is the Null character (‘\0’) used to indicate termination of string which differs
strings from normal character arrays.

Initializing a String: A string can be initialized in different ways. We will explain this with the
help of an example. Below is an example to declare a string with name as str and initialize it with
“CProgramming”.

1. char str[] = " CProgramming”;

2. char str[50] = " CProgramming";

PROGRAM b)
#include <stdio.h>
#include <string.h>

void swap(char *x, char *y) {


char temp;
temp = *x;
*x = *y;
*y = temp;
}

void generatePermutations(char *str, int start, int end) {


if (start == end) {
printf("%s\n", str); // Print the current permutation
} else {
for (int i = start; i <= end; i++) {
swap((str + start), (str + i)); // Swap characters
generatePermutations(str, start + 1, end); // Recur
swap((str + start), (str + i)); // Backtrack
}
}
}

int main() {
char str[100];
54 | P a g e
// Prompt user for input
printf("Enter a string of characters: ");
scanf("%s", str);

int length = strlen(str);


printf("All possible combinations of \"%s\":\n", str);
generatePermutations(str, 0, length - 1); // Generate permutations

return 0; // Exit successfully


}
OUTPUT
Enter a string of characters: ABC
All possible combinations of "ABC":
ABC
ACB
BAC
BCA
CAB
CBA

55 | P a g e
Experiment 11
To familiarize the students with structures in C
Title

Objectives 1Write a C program that defines a structure called Student to store the details of a student
including name, roll number, and marks in three subjects (Physics, Chemistry, and Mathematics).
The program should prompt the user to input the details of three students, store them in an array of
Student structures, and then print the details of all students.
2. Write a C program that defines a structure called Book to store the details of books including
title, author, and price. The program should then create an array of Book structures to store the
details of three books. After storing the details, the program should print the details of all books.
3. Write a C program that defines a structure called Employee to store the details of an employee
including name, ID, and
salary. The program should then create a pointer to an Employee structure and allocate memory
for it dynamically using
malloc(). After allocating memory, prompt the user to input the details of an employee using the
pointer, and then print the
details of the employee.
4. Write a C program that simulates a simple online shopping system. The program should include
the following
functionalities:
a. Add item to cart: Allow the user to add items to their shopping cart.
b. Remove item from cart: Allow the user to remove items from their shopping cart.
c. View cart: Display the items currently in the user’s shopping cart.
Ensure that each user has their own shopping cart, and use local variables to represent the items in
the cart.
5. Write a C program that defines a union called Data to represent a data structure that can store
either an integer or a
floating-point number. Additionally, define a structure called BitField to represent a data structure
that stores a set of bit-
fields including a flag, an integer value, and a floating-point value. Then, the program should
create variables of type Data
and BitField, initialize them with some values, and print their contents.
6: Write a C program that defines a typedef for a structure called Point to represent a point in 2D
space. The structure should
have two members: x and y, representing the coordinates of the point. Then, the program should
create a variable of type
Point and initialize it with some values. Finally, it should print the coordinates of the point.

56 | P a g e
Theory Structure is another user defined data type available in C that allows to combine data items of
different kinds. To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct statement is as
follows −

struct [structure tag] {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.

PROGRAM 1:
#include <stdio.h>

// Define the structure to hold student details


struct Student {
char name[50];
int rollNumber;
float physicsMarks;
float chemistryMarks;
float mathematicsMarks;
};

// Function prototypes
void inputStudentDetails(struct Student *student);
void printStudentDetails(struct Student student);

int main() {
struct Student students[3]; // Array to hold details of three students

// Input details for each student


for (int i = 0; i < 3; i++) {
printf("Enter details for student %d:\n", i + 1);
inputStudentDetails(&students[i]);
}

// Output details of all students


printf("\nDetails of students:\n");
for (int i = 0; i < 3; i++) {
printStudentDetails(students[i]);

57 | P a g e
}

return 0;
}

// Function to input student details


void inputStudentDetails(struct Student *student) {
printf("Name: ");
scanf(" %[^\n]", student->name); // Read string with spaces
printf("Roll Number: ");
scanf("%d", &student->rollNumber);
printf("Marks in Physics: ");
scanf("%f", &student->physicsMarks);
printf("Marks in Chemistry: ");
scanf("%f", &student->chemistryMarks);
printf("Marks in Mathematics: ");
scanf("%f", &student->mathematicsMarks);
}

// Function to print student details


void printStudentDetails(struct Student student) {
printf("Name: %s\n", student.name);
printf("Roll Number: %d\n", student.rollNumber);
printf("Marks in Physics: %.2f\n", student.physicsMarks);
printf("Marks in Chemistry: %.2f\n", student.chemistryMarks);
printf("Marks in Mathematics: %.2f\n", student.mathematicsMarks);
printf("-------------------------------\n");
}

OUTPUT :
Enter details for student 1:
Name: Amit
Roll Number: 12345
Marks in Physics: 70
Marks in Chemistry: 60
Marks in Mathematics: 50
Enter details for student 2:
Name: Ankur
Roll Number: 56789
Marks in Physics: 50
Marks in Chemistry: 80
Marks in Mathematics: 70
Enter details for student 3:
Name: Aakash

58 | P a g e
Roll Number: 56473
Marks in Physics: 90
Marks in Chemistry: 48
Marks in Mathematics: 57

Details of students:
Name: Amit
Roll Number: 12345
Marks in Physics: 70.00
Marks in Chemistry: 60.00
Marks in Mathematics: 50.00
-------------------------------
Name: Ankur
Roll Number: 56789
Marks in Physics: 50.00
Marks in Chemistry: 80.00
Marks in Mathematics: 70.00
-------------------------------
Name: Aakash
Roll Number: 56473
Marks in Physics: 90.00
Marks in Chemistry: 48.00
Marks in Mathematics: 57.00

PROGRAM 2:
#include <stdio.h>

// Define the Book structure


struct Book {
char title[100];
char author[100];
float price;
};

int main() {
// Create an array of Book structures
struct Book books[3];

// Input details for each book


for (int i = 0; i < 3; i++) {
printf("Enter details for book %d:\n", i + 1);
printf("Title: ");
getchar(); // Clear the newline character from previous input
fgets(books[i].title, sizeof(books[i].title), stdin);

59 | P a g e
books[i].title[strcspn(books[i].title, "\n")] = '\0'; // Remove newline character

printf("Author: ");
fgets(books[i].author, sizeof(books[i].author), stdin);
books[i].author[strcspn(books[i].author, "\n")] = '\0'; // Remove newline character

printf("Price: ");
scanf("%f", &books[i].price);
}

// Print details of all books


printf("\nDetails of the books:\n");
for (int i = 0; i < 3; i++) {
printf("Book %d:\n", i + 1);
printf("Title: %s\n", books[i].title);
printf("Author: %s\n", books[i].author);
printf("Price: %.2f\n", books[i].price);
}

return 0;
}
Enter details for book 1:
Title: The Catcher in the Rye
Author: J.D. Salinger
Price: 10.99
Enter details for book 2:
Title: To Kill a Mockingbird
Author: Harper Lee
Price: 12.49
Enter details for book 3:
Title: 1984
Author: George Orwell
Price: 14.99

Details of the books:


Book 1:
Title: The Catcher in the Rye
Author: J.D. Salinger
Price: 10.99
Book 2:
Title: To Kill a Mockingbird
Author: Harper Lee
Price: 12.49
Book 3:

60 | P a g e
Title: 1984
Author: George Orwell
Price: 14.99
Program 3:
#include <stdio.h>
#include <stdlib.h>

// Define the Employee structure


struct Employee {
char name[100];
int id;
float salary;
};

int main() {
// Create a pointer to Employee
struct Employee *emp;

// Allocate memory for one Employee structure


emp = (struct Employee *)malloc(sizeof(struct Employee));
if (emp == NULL) {
printf("Memory allocation failed!\n");
return 1; // Exit with error code
}

// Input details of the employee


printf("Enter employee details:\n");

printf("Name: ");
getchar(); // Clear the newline character from previous input
fgets(emp->name, sizeof(emp->name), stdin);
emp->name[strcspn(emp->name, "\n")] = '\0'; // Remove newline character

printf("ID: ");
scanf("%d", &emp->id);

printf("Salary: ");
scanf("%f", &emp->salary);

// Print details of the employee


printf("\nEmployee Details:\n");
printf("Name: %s\n", emp->name);
printf("ID: %d\n", emp->id);
printf("Salary: %.2f\n", emp->salary);

61 | P a g e
// Free the allocated memory
free(emp);

return 0;
}
OUTPUT :
Enter employee details:
Name: John Doe
ID: 12345
Salary: 55000.50

Employee Details:
Name: John Doe
ID: 12345
Salary: 55000.50\
Program 4:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_ITEMS 100


#define ITEM_NAME_LENGTH 50

// Structure to represent an item


struct Item {
char name[ITEM_NAME_LENGTH];
};

// Function prototypes
void addItem(struct Item cart[], int *count);
void removeItem(struct Item cart[], int *count);
void viewCart(struct Item cart[], int count);

int main() {
struct Item cart[MAX_ITEMS];
int itemCount = 0;
int choice;

do {
printf("\nOnline Shopping Cart System\n");
printf("1. Add item to cart\n");
printf("2. Remove item from cart\n");
printf("3. View cart\n");

62 | P a g e
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Clear newline from input buffer

switch (choice) {
case 1:
addItem(cart, &itemCount);
break;
case 2:
removeItem(cart, &itemCount);
break;
case 3:
viewCart(cart, itemCount);
break;
case 4:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);

return 0;
}

void addItem(struct Item cart[], int *count) {


if (*count >= MAX_ITEMS) {
printf("Cart is full! Cannot add more items.\n");
return;
}

printf("Enter the name of the item to add: ");


fgets(cart[*count].name, ITEM_NAME_LENGTH, stdin);
cart[*count].name[strcspn(cart[*count].name, "\n")] = '\0'; // Remove newline character
(*count)++;
printf("Item added to cart.\n");
}

void removeItem(struct Item cart[], int *count) {


if (*count == 0) {
printf("Cart is empty! No items to remove.\n");
return;
}

63 | P a g e
printf("Enter the name of the item to remove: ");
char itemName[ITEM_NAME_LENGTH];
fgets(itemName, ITEM_NAME_LENGTH, stdin);
itemName[strcspn(itemName, "\n")] = '\0'; // Remove newline character

for (int i = 0; i < *count; i++) {


if (strcmp(cart[i].name, itemName) == 0) {
// Shift items to remove the specified item
for (int j = i; j < *count - 1; j++) {
cart[j] = cart[j + 1];
}
(*count)--;
printf("Item removed from cart.\n");
return;
}
}

printf("Item not found in the cart.\n");


}

void viewCart(struct Item cart[], int count) {


if (count == 0) {
printf("Your cart is empty.\n");
return;
}

printf("Items in your cart:\n");


for (int i = 0; i < count; i++) {
printf("%d. %s\n", i + 1, cart[i].name);
}
}

64 | P a g e
OUTPUT :
Online Shopping Cart System
1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 1
Enter the name of the item to add: Apple
Item added to cart.

Online Shopping Cart System


1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 1
Enter the name of the item to add: Banana
Item added to cart.

Online Shopping Cart System


1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 3
Items in your cart:
1. Apple
2. Banana

Online Shopping Cart System


1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 2
Enter the name of the item to remove: Apple
Item removed from cart.

Online Shopping Cart System


1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 3

65 | P a g e
Items in your cart:
1. Banana

Online Shopping Cart System


1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 4
Exiting the program.
PROGRAM 5:
#include <stdio.h>

// Define a union called Data


union Data {
int intValue;
float floatValue;
};

// Define a structure called BitField


struct BitField {
unsigned int flag : 1; // 1 bit for flag
unsigned int intValue : 7; // 7 bits for integer value
unsigned int floatValue : 24; // 24 bits for float (simplified for illustration)
};

int main() {
// Initialize a variable of type Data
union Data data;
data.intValue = 42; // Assign an integer value
printf("Union Data (intValue): %d\n", data.intValue);

// Assign a floating-point value


data.floatValue = 3.14f; // Assign a float value
printf("Union Data (floatValue): %.2f\n", data.floatValue); // Prints the float value

// Initialize a variable of type BitField


struct BitField bitField;
bitField.flag = 1; // Set flag to 1 (true)
bitField.intValue = 5; // Assign integer value
bitField.floatValue = 1; // Simplified, just assigning a value for illustration

// Print contents of BitField


printf("\nStructure BitField:\n");

66 | P a g e
printf("Flag: %u\n", bitField.flag);
printf("Integer Value: %u\n", bitField.intValue);
printf("Floating-Point Value (simplified): %u\n", bitField.floatValue);

return 0;
}
OUTPUT :
Union Data (intValue): 42
Union Data (floatValue): 3.14

Structure BitField:
Flag: 1
Integer Value: 5
Floating-Point Value (simplified): 1

PROGRAM 6:
#include <stdio.h>

// Define a typedef for the structure Point


typedef struct {
float x; // X coordinate
float y; // Y coordinate
} Point;

int main() {
// Create a variable of type Point and initialize it
Point p1;
p1.x = 5.0f; // Assign value to x
p1.y = 10.0f; // Assign value to y

// Print the coordinates of the point


printf("Point coordinates:\n");
printf("X: %.2f\n", p1.x);
printf("Y: %.2f\n", p1.y);

return 0;
}
OUTPUT :
Point coordinates:
X: 5.00
Y: 10.00

67 | P a g e

You might also like