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

pc(EEE)

The document is a question bank for the course 'Problem Solving Techniques Using C' at Mahendra Institute of Technology for the academic year 2024-2025. It covers various topics including computer fundamentals, algorithms, pseudocode, flowcharts, recursion, and iteration, along with detailed problem-solving strategies. Additionally, it provides examples of C programs and outlines the steps for creating and running programs.

Uploaded by

nneshank
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 views58 pages

pc(EEE)

The document is a question bank for the course 'Problem Solving Techniques Using C' at Mahendra Institute of Technology for the academic year 2024-2025. It covers various topics including computer fundamentals, algorithms, pseudocode, flowcharts, recursion, and iteration, along with detailed problem-solving strategies. Additionally, it provides examples of C programs and outlines the steps for creating and running programs.

Uploaded by

nneshank
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
You are on page 1/ 58

MAHENDRA INSTITUTE OF TECHNOLOGY

(AUTONOMOUS)

Mahendhirapuri, Mallasamudram,Namakkal- 637 503

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

QUESTION BANK

Academic Year : 2024-2025 (Odd Semester)

Year/Sem : I/I

Course Code &Title : CS2413001& Problem Solving Techniques Using C

Regulation : R2024

Prepared By Approved By
1. R.DURAIRAM AP/CSE
2. MEIYALAKAN.K AP/CSE (Dr. J. STANLY JAYAPRAKASH HOD/CSE)
UNIT-I

INTRODUCTION
Computers: Hardware – Software – Processor – Memory – I/O devices – Interface – Programming Languages
Problem Solving Aspects: Algorithms Pseudo code, Flowchart-Steps in Problem Solving – simple strategies for
developing algorithms (iteration, recursion) – Steps for Creating and Running programs -Illustrative problems:
Exchanging The Values – Find minimum in a list - Factorial Computation - Fibonacci Sequence.

Part-A (Five Questions)


BTL
S.No Questions CO
1 What are Computers? K1 Co1
Computers are electronic devices designed to process, store, and retrieve data. It
performs a wide range of tasks by following instructions from software programs. It
operates on the basic principle of the input-process-output cycle and is capable of
processing data at high speeds, enabling a wide range of functionalities across various
fields like science, business, education and entertainment.

2 Define Hardware, Software, and Processor. K1 Co1


Hardware :-A computer system is divided into two categories: Hardware and Software.
Hardware refers to the physical and visible components of the system such as a monitor,
CPU, keyboard and mouse.
Software:- Software refers to a set of instructions which enable the hardware to
perform a specific set of tasks.
Processor:-A processor, also known as a central processing unit (CPU), is a computer's
primary component that interprets, processes, and executes instructions.

3 What is meant by Algorithm and Pseudo code? Give example. K1 Co1


Algorithm:-An algorithm is a step-by-step set of instructions designed to perform a
specific task or solve a problem.
Example:- Algorithm to add two numbers.
1. Take two numbers as input.
2. Add the two numbers.
3. Display the result.
Pseudocode:-
Pseudocode is a way to describe an algorithm in a way that's easier for humans to
understand than programming code.
Pseudocode is an important part of designing an algorithm, it helps the programmer
in planning the solution to the problem as well as the reader in understanding the
approach to the problem.
Pseudocode is an intermediate state between algorithm and program that plays
supports the transition of the algorithm into the program.

Example:- Pseudocode to find the largest of two numbers.


1. Start
2. Input two numbers A and B
3. If A > B, then print A is larger
4. Else, print B is larger
5. End
4 Define flowchart? Why flowchart is required? K1 Co1
A flowchart is a visual representation of a process or algorithm. It uses various
shapes, such as ovals, rectangles, diamonds, and arrows, to illustrate the steps involved
in a procedure and the flow of control or information between these steps.
Why it is required?
1. Clarity and Understanding: Flowcharts simplify complex processes, making it
easier to visualize and understand the steps involved.
2. Effective Communication: They provide a clear visual representation that helps
communicate processes to team members and stakeholders, ensuring everyone is
aligned.(meaning- arranged in order or positioned correctly relative to each other.)

5 Define Recursion and Iteration. Give example. K2 Co1


Recursion:-
It is a programming technique where a function calls itself to solve a problem. This
approach breaks down a complex problem into smaller, more manageable sub-problems.

Iteration:-
Iteration is a way to repeat a set of instructions in a program until a certain condition is
met. It usually uses loops (like for or while) to execute the same code multiple times.
Part-B (Three Questions) (13 Marks)

S.No Questions BTL CO


Explain in detail about algorithm, pseudocode and flowchart for the following
1 with example program. K2 Co1
i) Product of two numbers.
ii) Swapping of two numbers.

i) Algorithm: Product of Two Numbers

Step 1:- Read two numbers, a and b.


Step 2:- Calculate the product:
Step 3:- Product = a * b
Step 4:- Display the result.

ii) Pseudocode for Product of Two Numbers

BEGIN
// Step 1: Declare variables
DECLARE a, b, product AS INTEGER

// Step 2: Input two numbers


PRINT "Enter the first number:"
READ a

PRINT "Enter the second number:"


READ b

// Step 3: Calculate the product


product = a * b

// Step 4: Output the result


PRINT "The product of", a, "and", b, "is", product
END

iii) Flowchart for Product of Two Numbers


C program for Product of two numbers:-

#include <stdio.h>
int main()
{
// Declare variables for the two numbers and the product
int num1, num2, product;
// Prompt the user for input
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
// Calculate the product
product = num1 * num2;
// Display the result
printf("The product of %d and %d is %d\n", num1, num2, product);
return 0;
}
Output:-

Enter the first number: 4


Enter the second number: 7
The product of 4 and 7 is 28

i) Algorithm for Swapping of two numbers:-

Step 1:- Input two variables, A and B, with their respective values.
Step 2:- Create a temporary variable, temp.
Step 3:- Assign the value of A to temp.
Step 4:- Assign the value of B to A.
Step 5:- Assign the value of temp (which holds the original value of A) to B.
Step 6:- The values of A and B have been swapped.

ii) Pseudocode for Swapping of two numbers: -

BEGIN
// Step 1: Input
PRINT "Enter first number (a):"
READ a
PRINT "Enter second number (b):"
READ b

// Step 2: Swap using a temporary variable


temp = a
a=b
b = temp

// Step 3: Output
PRINT "After swapping:"
PRINT "a =", a
PRINT "b =", b
END
iii) Flowchart for Swapping of two numbers: -

C program for Swapping of two numbers: -

#include <stdio.h>

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

// Input
printf("Enter first number (a): ");
scanf("%d", &a);
printf("Enter second number (b): ");
scanf("%d", &b);

// Swapping using a temporary variable


temp = a;
a = b;
b = temp;

// Output
printf("After swapping:\n");
printf("a = %d\n", a);
printf("b = %d\n", b);
return 0;
}
Output:-
Enter first number (a): 5
Enter second number (b): 10
After swapping: a = 10 b = 5
2. What are the steps in problem solving aspects. Explain in details. K2 Co1
A computer cannot solve a problem on its own. One has to provide step by step solutions of
the problem to the computer. In fact, the task of problem solving is not that of the
computer. It is the programmer who has to write down the solution to the problem in terms
of simple operations which the computer can understand and execute.

Problem Solving Chart

Problem-solving is a structured approach that can help you tackle challenges effectively.
Here are the key steps typically involved:

1. Identify the Problem

What to Do: Take time to articulate what the problem is. Avoid jumping to conclusions
based on assumptions.
How: Ask questions like: What is happening? Why is it a problem? Who is affected?
Outcome: A clear, concise statement of the problem that sets the stage for the rest of the
process.

2.Gather Information

What to Do: Collect data, facts, and insights related to the problem.
How: Use various sources such as reports, interviews, surveys, and observations. Engage
Outcome: A to
stakeholders comprehensive understanding of the context and factors influencing the
get different perspectives.
problem
Outcome: A comprehensive understanding of the context and factors influencing the
problem
3. Define Goals

What to Do: Establish what you want to achieve with your solution.
How: Set SMART goals (Specific, Measurable, Achievable, Relevant, Time-bound) to
guide your decision-making.
Outcome: A clear target that informs the evaluation of potential solutions.

4. Generate Alternatives

What to Do: Brainstorm a variety of possible solutions without filtering or judging them
initially.
How: Encourage creativity through group discussions, mind mapping, or individual
reflection. Consider even the most unconventional ideas.
Outcome: A diverse list of potential solutions that can be explored further.

5. Evaluate Alternatives

What to Do: Analyze the feasibility and implications of each potential solution.
How: Use criteria like cost, time, resources needed, and alignment with goals. Consider the
short-term and long-term impacts of each option.
Outcome: A clear understanding of the strengths and weaknesses of each alternative.

6. Choose a Solution

What to Do: Select the most suitable solution based on your evaluation.
How: Make the decision collaboratively if possible, ensuring that it is supported by those
who will implement it. Aim for consensus where feasible.
Outcome: A well-reasoned choice that has buy-in from stakeholders.

7. Implement the Solution

What to Do: Put the selected solution into action.


How: Create an action plan that outlines tasks, responsibilities, timelines, and required
resources. Communicate the plan to all involved parties.
Outcome: The solution is put into effect, with all necessary steps taken to ensure successful
implementation.

8. Monitor and Evaluate

What to Do: Assess how well the solution is working after implementation.
How: Use metrics and feedback to measure progress against the goals defined earlier.
Gather input from those affected by the solution.
Outcome: An understanding of the solution’s effectiveness and any necessary adjustments.

9. Reflect and Learn

What to Do: Review the entire problem-solving process to identify lessons learned.
How: Hold a debriefing session with stakeholders to discuss what went well, what didn’t,
and why. Document insights for future reference.
Outcome: Enhanced problem-solving skills and a refined approach for tackling future
challenges.
K2 Co1
3. What are the simple strategies for developing algorithms?

Developing an algorithm is a very important step in problem-solving. There are different


types of strategies that could be used to develop an algorithm to solve a problem. Two
of the most frequently used strategies are:

 Iteration
 Recursion

Iteration:-

Iteration is a programming concept that refers to the process of repeatedly executing


a block of code until a specified condition is met. It allows you to perform tasks
multiple times without having to write the same code over and over again. Common
iteration constructs include for, while, and do-while loops.

Key Points about Iteration:-

Repetition: Code inside the loop is executed multiple times.


Control Condition: Each iteration checks a condition that determines whether to
continue or stop.
Efficiency: Iteration can simplify code and improve efficiency by avoiding redundancy.

1. Using for Loop

Example: Calculate the sum of the first n natural numbers.

#include <stdio.h>

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

// Input: Read the number n from the user


printf("Enter a positive integer: ");
scanf("%d", &n);

// Calculate the sum using a for loop


for (int i = 1; i <= n; i++) {
sum += i;
}

// Output: Display the result


printf("The sum of the first %d natural numbers is: %d\n", n, sum);
return 0;
}
Output:-
Enter a positive integer: 10
The sum of the first 10 natural numbers is: 55
2. Using While loop

#include <stdio.h>
int main()
{
int i = 5; // Start from the first number divisible by 5
printf("Numbers from 1 to 100 that are divisible by 5:\n");
// Use a while loop to print numbers divisible by 5
while (i <= 100)
{
printf("%d ", i); // Print the number
i += 5; // Increment i by 5
}
printf("\n"); // New line for better output formatting
return 0;
}

Output:-

Numbers from 1 to 100 that are divisible by 5:


5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

3. Using do-while loop

#include <stdio.h>

int main() {
int i = 1; // Start from 1

printf("Numbers from 1 to 10:\n");

// Use a do-while loop to print numbers from 1 to 10


do {
printf("%d ", i); // Print the current number
i++; // Increment i
} while (i <= 10); // Continue until i is greater than 10

printf("\n"); // New line for better output formatting


return 0;
}
Output:-

Numbers from 1 to 10:


1 2 3 4 5 6 7 8 9 10

Recursion:-
It is a programming technique where a function calls itself to solve a problem. This
approach breaks down a complex problem into smaller, more manageable sub-problems,
each of which is a smaller instance of the original problem. A recursive function typically
has a base case to stop the recursion and prevent it from running indefinitely.

C Program for Factorial Using Recursion

#include <stdio.h>
// Function to calculate factorial recursively
int factorial(int n) {
// Base case: if n is 0 or 1, return 1
if (n == 0 || n == 1) {
return 1;
}
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
int main() {
int number;
// Input a number
printf("Enter a number: ");
scanf("%d", &number);

// Calculate factorial
int result = factorial(number);
// Output the result
printf("The factorial of %d is %d\n", number, result);
return 0;
} Output
Enter a positive integer: 5
The factorial of 5 is 120
Enter a positive integer: -3
Factorial is not defined for negative numbers.
Part-C (One Question) (15 Marks)

S.No Questions BTL CO


1 What are the steps for creating and running programs. K2 Co1

Creating and running programs involves several key steps that can be
categorized into planning, coding, testing, and execution. Here’s a detailed
breakdown:
1. Planning
 Define the Problem: Clearly articulate the problem you want to
solve or the task you want to automate.
 Requirements Analysis: Gather requirements, considering what
inputs are needed and what outputs are expected.
 Design: Outline the program's structure. This can include flowcharts,
pseudocode, or UML diagrams to visualize the logic and flow.
2. Setting Up the Environment
 Choose a Programming Language: Select an appropriate
programming language based on the project requirements and
personal proficiency.
 Install Necessary Tools: Set up a development environment, which
may include an Integrated Development Environment (IDE) or text
editor, compilers, and libraries.
3. Coding
 Write the Code: Implement the design using the chosen
programming language. Follow best practices for code structure,
naming conventions, and comments.
 Version Control: Use a version control system (e.g., Git) to manage
changes and collaborate with others.
4. Testing
 Debugging: Test individual components (unit testing) to ensure they
work as expected. Debug any errors that arise during testing.
 Integration Testing: Once individual components are tested,
integrate them and test the complete program to ensure all parts work
together.
 User Acceptance Testing: Gather feedback from users to validate
that the program meets requirements and performs as intended.
5. Execution
 Run the Program: Execute the program in the appropriate
environment (local, server, etc.). Monitor for any runtime errors or
performance issues.
 Deployment: If the program is intended for wider use, deploy it to
the target environment (e.g., web server, application store).
6. Maintenance
 Update and Optimize: Based on user feedback and performance
metrics, make necessary updates, bug fixes, and optimizations.
 Documentation: Document the code, user guides, and maintenance
procedures to assist future developers and users.

Conclusion
Creating and running a program is a systematic process that requires
careful planning, coding, testing, and maintenance. Each step is crucial to
ensure the program functions correctly and meets user needs. Proper
execution of these steps contributes to the overall quality and
effectiveness of software development.

Here’s a simple example of a C program that calculates the sum of two


integers provided by the user. This program demonstrates the steps of
creating, coding, and executing a program.

Example C Program: Sum of Two Integers

1. Planning
 Problem Statement: Create a program that takes two integers as
input and outputs their sum.
 Requirements:
o Input: Two integers.
o Output: The sum of the two integers.
Code
 Here’s the C code for the program:

#include <stdio.h>

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

// Prompt user for input


printf("Enter first integer: ");
scanf("%d", &num1);

printf("Enter second integer: ");


scanf("%d", &num2);

// Calculate the sum


sum = num1 + num2;

// Display the result


printf("The sum of %d and %d is %d\n", num1, num2, sum);

return 0;
}

3. Testing

Compile the Code: To compile the program, save the code in a file
named sum.c and use a C compiler, like gcc:

gcc sum.c -o sum

Run the Program: Execute the compiled program:

./sum

Example Interaction:
Enter first integer: 5
Enter second integer: 10
The sum of 5 and 10 is 15

4. Execution
 The program takes user input, processes it, and outputs the result.
Ensure you check for proper input handling (e.g., entering non-
integer values), which can be included in more complex versions.
5. Maintenance
 If needed, you can later extend the program to handle more
complex operations, such as subtracting, multiplying, or dividing
the numbers.

Conclusion
This example illustrates the steps involved in creating a simple C
program, from planning and coding to testing and execution.
UNIT II
BASICS OF C PROGRAMMING
Introduction to C programming – Header files – Structure of a C program – compilation and
linking processes – Constants, Variables – Data Types – Expressions-, Expression
Evaluation, Type conversion Statements – operators – Input and Output operations –
Decision Making and Branching – Looping statements- Programming Examples.

Part-A ( Five Questions)

S.No Questions BTL CO


1 What is a header file? K1 CO2
A header file is a source file that has the .h extension. Header files
contain the function prototypes or function declaration, whereas the
source code contains the constants, macros, system-wide global
variables. Whenever we require the definition of a function, then we
simply include that header file in which function is declared.

2 Define datatypes? K1 CO2


data types define the type of data a variable can hold, as well as the
associated operations that can be performed on that data. They specify
how much space in memory will be allocated for variables and what
kind of values they can store.
3 Define constants and list its types K1 CO2
Constants: Fixed values that do not change during the execution of a
program.
Types of Constants in C:
1.Integer Constants: Numeric constants without decimal points, such as
10, -5, or 0.
2.Floating-point Constants: Numeric constants with decimal points,
such as 3.14 or
-0.5.
3.Character Constants: Single characters enclosed within single
quotes, such as 'A' or '7'.
4.String Constants: Sequences of characters enclosed within double
quotes, such as
"Hello" or "123".
5.Enumeration Constants: User-defined constants created using the
enum keyword, such as enum Weekday {MON, TUE, WED, THU, FRI,
SAT, SUN};.
6.Symbolic Constants: Named constants defined using the #define
preprocessor directive, such as #define PI 3.14159.
4 What is Expression? K1 CO2
Expression is a combination of variables, constants, operators, and
function calls that produce a value. Expressions are fundamental
building blocks in C, used for performing computations, assigning
values, or making decisions in a program.

5 Explain short notes on keywords in c language? K2 CO2


 Keywords in C are reserved words with predefined
meanings, used for various purposes such as declaring
variables, defining control structures, specifying data types, and
managing memory.
 They are case-sensitive and standardized across all
implementations of the language, ensuring consistency and
portability of C code.
Part-B( Three Questions) ( 13 Marks)
S.No Questions BTL CO
Develop the decision making statements and looping statements in c with an
1 example K3 CO2
Decision-Making Statements in C:
Decision-making statements in C allow the program to choose between different
courses of action based on certain conditions. The primary decision-making
statements in C are:
if Statement: Executes a block of code if a specified condition is true.
if-else Statement: Executes one block of code if the condition is true and another
block if the condition is false.
nested if-else Statement: Contains if-else statements inside another if or else block.
Example of Decision-Making Statements:
#include <stdio.h>
int main() {
int num = 10;
// if statement
if (num > 0) {
printf("%d is positive.\n", num);
}
// if-else statement
if (num % 2 == 0) {
printf("%d is even.\n", num);
} else {
printf("%d is odd.\n", num);
}
// nested if-else statement
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
Looping Statements in C:
Looping statements in C allow the execution of a block of code repeatedly until a
specified condition is met. The primary looping statements in C are:

while Loop: Executes a block of code as long as the specified condition is true.

do-while Loop: Similar to the while loop, but the condition is checked after the
execution of the block of code, ensuring that the block is executed at least once.

for Loop: Executes a block of code for a specified number of times, with an
initialization, condition, and increment/decrement expression.

Example of Looping Statements:


#include <stdio.h>
int main() {
// while loop
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
printf("\n");
// do-while loop
int j = 1;
do {
printf("%d ", j);
j++;
} while (j <= 5);
printf("\n");

// for loop

for (int k = 1; k <= 5; k++) {

printf("%d ", k);

}
printf("\n");
return 0;
}
These decision-making and looping statements provide control flow mechanisms in
C programs, allowing them to make decisions and execute repetitive tasks
efficiently.
Explain in detail about different types operators used in c with necessary
2 program? K2 CO2
Operators in C:
Operators in C are symbols that instruct the compiler to perform specific operations
on one or more operands. They are classified into several types based on their
functionality and usage:
Arithmetic Operators: Used to perform mathematical operations like addition,
subtraction, multiplication, division, and modulus.
Relational Operators: Used to compare values and determine the relationship
between them. They return a Boolean value (true or false).
Logical Operators: Used to perform logical operations on Boolean operands. They
are typically used in control statements to make decisions based on multiple
conditions.
Assignment Operators: Used to assign values to variables. They can also perform
arithmetic or bitwise operations simultaneously with assignment.
Bitwise Operators: Used to perform bit-level operations on operands. They
manipulate individual bits of operands.
Increment and Decrement Operators: Used to increase or decrease the value of a
variable by one.
Conditional (Ternary) Operator: An operator that takes three operands and
evaluates a condition. It returns one of two values based on the result of the
condition.
Comma Operator: Used to separate multiple expressions. It evaluates each
expression and returns the value of the last expression.
sizeof Operator: Used to determine the size of a data type or a variable in bytes.
Address (&) and Dereference (*) Operators: Used for pointer operations. '&'
returns the address of a variable, while '*' is used to access the value at a given
address.
Let's illustrate some of these operators with examples:
#include <stdio.h>
int main() {
// Arithmetic operators int a =
10, b = 5; printf("Arithmetic
Operators:\n");
printf("a + b = %d\n", a + b); // Addition
printf("a - b = %d\n", a - b); // Subtraction
printf("a * b = %d\n", a * b); // Multiplication
printf("a / b = %d\n", a / b); // Division
printf("a %% b = %d\n", a % b); // Modulus
// Relational operators int x = 10,
y = 20; printf("\nRelational
Operators:\n");
printf("x > y is %d\n", x > y); // Greater than
printf("x < y is %d\n", x < y); // Less than
printf("x == y is %d\n", x == y); // Equal to
printf("x != y is %d\n", x != y); // Not equal to
// Logical operators
int p = 1, q = 0;
printf("\nLogical Operators:\n");
printf("p && q is %d\n", p && q); // Logical AND
printf("p || q is %d\n", p || q); // Logical OR
printf("!p is %d\n", !p); // Logical NOT
// Assignment operators
int num = 10;
num += 5; // Equivalent to num = num + 5
printf("\nAssignment Operator:\n");
printf("num = %d\n", num);
// Increment and Decrement operators
int count = 5;
printf("\nIncrement and Decrement Operators:\n");
printf("count++ is %d\n", count++); // Post-increment
printf("++count is %d\n", ++count); // Pre-increment
// Ternary operator
int age = 20;
char* result = (age >= 18) ? "Adult" : "Minor";
printf("\nTernary Operator:\n");
printf("Result: %s\n", result);
// Comma operator
int i, j;
for (i = 0, j = 5; i < 5; i++, j--) {
printf("%d + %d = %d\n", i, j, i + j);
}
// sizeof operator
printf("\nSizeof Operator:\n");
printf("Size of int: %lu bytes\n", sizeof(int));
// Address and Dereference operators
int var = 10;
int* ptr = &var; // Address of operator
printf("\nAddress and Dereference Operators:\n");
printf("Value of var: %d\n", *ptr); // Dereference operator
return 0;
}
This program demonstrates various types of operators in C, along with examples
illustrating their usage and functionality. Understanding operators is essential for
effective programming in C, as they are fundamental for performing computations,
making decisions, and manipulating data.

Explain in detail about the Structure of a C Program.


3 K2 CO2

STRUCTURE OF A C PROGRAM

1. Header Files Inclusion: The first and foremost component is the


inclusion of the Header files in a C program.
A header file is a file with extension .h which contains C function
declarations and macro definitions to be shared between several
source files. Some of C Header files:
 stddef.h–Defines several useful types and macros.
 stdint.h–Defines exact width integer types.
 stdio.h–Define score input and output functions
 stdlib.h–Defines numeric conversion functions,
pseudo-random network generator, memory allocation
 string.h–Defines string handling functions
 math.h–Defines common mathematical functions

Syntax to include a header file in C:


#include

Mahendra Institute of Technology- Dept of CSE –PROBLEM SOLVING TECHNIQUES IN C Page 18


2. Main Method Declaration:The next part of a C program is to
declare the main() function. The syntax to declare the main
function is:

Syntax to Declare main method:


int main()
{}

3. VariableDeclaration:Itreferstothevariablesthataretobeusedinthefunction,t
he variables are to be declared before any operation in the function.

Example:
int main()
{
int a;
.
4. Body: Body of a function in C program, refers to the operations that are
.
performed in the functions. It can be anything like manipulations, searching,
sorting, printing, etc.

Example:

int main()
{
int a;
printf("%d",a);
.
5. Return
. Statement:The return statement refers to the returning of the values
from a function. This return statement and return value depend upon the
return type of the function. For example, if the return type is void, then there
will be no return statement. In any other case, there will be a return statement
and the return value will be of the type of the specified return type.

Example:
int main()
{
int a;
printf("%d",a);
return0;
}
Writing first program:
Following is first program in C
#include <stdio.h>
int main()
{
intnumber1,number2,sum;
printf("Enter two integers:");
scanf("%d%d",&number1,&number2);
//calculating sum
sum= number1+number2;
printf("%d+%d=%d",number1,n
umber2,sum); return 0;
}
Part-C (One Question) ( 15 Marks)

S.No Questions BTL CO


1 Classify about data types with appropriate C programs K2 CO2
Here's an enumeration of different data types in C along with appropriate C programs
demonstrating their usage:
Int Data Type: Used to store integer values.
#include <stdio.h>
int main() {
int num = 10;
printf("Integer Value: %d\n", num);
return 0;
}
Char Data Type: Used to store single characters.
#include <stdio.h>
int main() {
char ch = 'A';
printf("Character Value: %c\n", ch);
return 0;
}
Float Data Type: Used to store single-precision floating-point values.
#include <stdio.h>
int main() {
float num = 3.14;
printf("Float Value: %f\n", num);
return 0;
}
Double Data Type: Used to store double-precision floating-point values.
#include <stdio.h>
int main() {
double num = 3.14159;
printf("Double Value: %lf\n", num);
return 0;
}
Short Data Type: Used to declare short integers.
#include <stdio.h>
int main()
{
short num = 100;
printf("Short Integer Value: %d\n", num);
return 0;
}
long Data Type: Used to declare long integers.
#include <stdio.h>
int main() {
long num = 1000000;
printf("Long Integer Value: %ld\n", num);
return 0;
}
Unsigned Data Type: Used to declare unsigned integers.
#include <stdio.h>
int main() {
unsigned int num = 50;
printf("Unsigned Integer Value: %u\n", num);
return 0;
}
Array Data Type: A collection of elements of the same data type.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("Array Element at Index 3: %d\n", arr[3]);
return 0;
}
Pointer Data Type: A variable that stores the memory address of another variable.
#include <stdio.h>
int main() {
int num = 10;
int *ptr = &num;
printf("Value at Memory Address: %d\n", *ptr);
return 0;
}
Struct Data Type: A collection of variables of different data types under a single
name.
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person person1 = {"John", 25};
printf("Name: %s, Age: %d\n", person1.name, person1.age);
return 0;
}
These programs demonstrate the usage of different data types in C, showcasing
their capabilities and how they can be utilized in programming.
UNIT III
ARRAYS AND STRINGS

Arrays: Introduction – One-Dimensional Arrays – Two and multi-Dimensional Arrays - Strings: Operations
of Strings. Function – definition of function – Declaration of function – Function prototype – Types of
functions- user defined functions – Pass by value – Pass by reference – Recursion - Programming
Examples.

Part-A (Five Questions)

S.No Questions BTL CO


1 Different between array and strings. K1 Co3
Array Strings
An array is a collection of similar data
A string is a sequence of characters
types such as integers, character
Array are mutable, which means you can A string is immutable which means you
modify their values at any time cannot modify its values after they are
created
Memory allocation in the array, Stores It stores characters in separate memory l
values in contiguous memory locations
An array can hold any of the data types A string can hold only a char data type

2 Define Strings. K1 Co3


The group of characters, digit and symbols enclosed within quotes is called as String (or)
character Arrays. Strings are always terminated with ‘\0’ (NULL) character. The compiler
automatically adds ‘\0’ at the end of the strings

Example: char name[]={‘C’,’O’,’L’,’L’,’E’,’G’,’E’,’\0’};


3 What is the use of „\0‟ and „%s‟? K2 Co3
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of
integer 0(zero) as it refers to nothing In C language it is generally used to mark an end of
a string.
It's a format specifies that is used for strings. And also you can use it for characters in
place of '%c'... Arin Bagul %s tells print f that the corresponding argument is to be
treated as a string (in C terms, a 0-terminated sequence of char ); the type of the
corresponding argument must be char *
4 Discuss the role of strev ()? K1 Co3
Strrev () is a function in C used to reverse the characters in a string, effectively flipping
the order of the characters from the end to the beginning.
5 Write a c program to find largest of n elements stored in an array. K1 Co3
#include<stdio.h>
void main()
{
int i,n,a[10],big;
printf(“enter number of array elements\n”);
scanf(“%d”,&n);
printf(“enter array elements\n”);
big=a[0];
for(i=0;i<n;i++)
{
big=a[i];
}
printf(“the biggest element in an array is %d\n”,big);
}

Part-B (Three Questions) (13 Marks)

S. C
Questions BTL
No O
Co
1 Explain about the Arrays and String its manipulation in detail. K1
3
Arrays
An array in C is a fixed-size collection of similar data items stored in contiguous memory
locations. It can be used to store the collection of primitive data types such as int, char,
float, etc., and also derived and user-defined data types such as pointers, structures, etc.

Properties of Array

The array contains the following properties.


Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data
element.
Initialization of C Array

The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List which we
will learn later.
String
The string can be defined as the one-dimensional array of characters terminated by a null
('\0'). The character array or the string is used to manipulate text such as word or sentences.
Each character in the array occupies one byte of memory, and the last character must always
be 0. The termination character ('\0') is important in a string since it is the only way to
identify where the string ends. When we define a string as char s[10], the character s[10] is
implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Let's see the example of declaring string by char array in C language.
char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

While declaring string, size is not mandatory. So we can write the above code as given
below:
char ch[]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

We can also define the string by the string literal in C language. For example:
char ch[]="javatpoint";

In such case, '\0' will be appended at the end of the string by the compiler.
Traversing String

Traversing the string is one of the most important aspects in any of the programming
languages. We may need to manipulate a very large text which can be done by traversing the
text. Traversing string is somewhat different from the traversing an integer array. We need to
know the length of the array to traverse an integer array, whereas we may use the null
character in the case of string to identify the end the string and terminate the loop.

Hence, there are two ways to traverse a string.


By using the length of string
By using the null character.

Let's discuss each one of them.

Accepting string as the input

Till now, we have used scanf to accept the input from the user. However, it can also be used
in the case of strings but with a different scenario. Consider the below code which stores the
string while space is encountered.
#include<stdio.h>
void main ()
{
char s[20];
printf("Enter the string?");
scanf("%s",s);
printf("You entered %s",s);
}

Output
Enter the string? java point is the best
You entered java point
o The compiler doesn't perform bounds checking on the character array. Hence, there
can be a case where the length of the string can exceed the dimension of the character
array which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined in a
header file string.h. The gets() is capable of receiving only one string at a time.
Discuss about the runtime initialization of a one dimensional arrays. K2 Co
2
3
An array with one dimension has one subscript. In C(1D), a one-dimensional array is one
that is shown as either one row or one column.
The vectors are one-dimensional arrays.
In other words, as shown in the following figure, it can be represented as a single dimension,
either width or height:

Declaration of an Array in One Dimension in C

The declaration of a one-dimensional array in C is:


Syntax
data type> array name[size];
Memory is allocated for the size elements. In a 1D array, the first element's subscript is 0 and
the size of the last element's subscript is -1. The size of a 1D array must remain consistent.
For instance:
char str[100], int rollno[100],
The compiler sets aside or allocates memory to store the complete array when it is specified.
y[5J is the sixth element since in C, subscripts always begin with 0 and increase by 1.
Instead of using a fixed integer quantity, it can be more convenient to express an array size
in terms of a symbolic constant.
This makes it simpler to change an array-using programme because any references to the

Mahendra Institute of Technology- Dept of CSE –PROBLEM SOLVING TECHNIQUES IN C Page 27


maximum array size (for example, in for loops and array definitions) can be changed by
simply altering the symbolic constant's value.
For instance:
#define SIZE 100.
charr string [SIZE];
Assume we have the array int score[7] depicted in the diagram below:

The first element's address serves as the array's name, while the offset serves as the
subscript.
Score's base address or starting address is 1000 (also known as score[0address), ]'s and the
size of an int is 2 bytes. The address of the third element (score([2]) will be 1004, and so on,
with the address of the second element (score([1]) being 1002).
Therefore,
The total array size in bytes is = The sum of the array's size and the datatype's size.
Example:
int a[40]; 402 bytes total, or 80 bytes. 50 bytes for character b; 501 total bytes.
double sal[20]; total bytes are (20*8), or 160 bytes.
The formula is: base address + (subscript * size of datatype) to get the address of any
element in an array.
For instance, let's say the base address of A is 1000 (int A[40]). To obtain the address of
A[5] element, multiply 1000 by (5*2) to get 1010.

Initializing One Dimensional Array in C

One-dimensional arrays can be initialized in C both during compilation and during runtime.
Initialization at Compile Time:
When an array is declared, it can be initialized. This is also referred to as initialization at
build time.
When an array is declared, its elements can be initialized in the same manner as regular
variables. Initializing an array often has the following form or syntax:
(a) Initializing all designated memory locations:
When an array's initial values are known before it is declared, it can be initialized. Data
objects of type int, char, etc. can be used to initialize array elements.
Examples:
int a[5]={1,2,3,4,5};
The compiler reserves 5 contiguous memory spaces for the variable a during compilation,

Mahendra Institute of Technology- Dept of CSE –PROBLEM SOLVING TECHNIQUES IN C Page 28


and all of these areas are initialized as indicated in the picture below.

(b) Partial Array Initialization:


The C programming language supports partial array initialization. if the array's size is
smaller than the amount of values that need to be initialized.
The elements will then be initialized to zero automatically in the case of a numeric array and
to space in the case of a non-numeric array.
For instance, int a[5]=0;

(c) Initialization without Size:


Take into account both the initialization and the declaration.
Example:
char b[]='C', 'O', 'M', 'P', 'U', 'T', 'E', 'R‟
Even though the precise amount of elements to be used in array b is not stated in this
declaration. The total number of initial values supplied will be used to determine the array
size. As a result, the array size will be automatically set to 8.
The initialization of the array b is depicted in the figure below:

Run Time Initialization:


An array may get explicit run-time initialization. Large arrays are typically initialized using
this method.
For instance, an array can be initialized with scanf().
int x[2]; scanf(“%d%d”,&x[0], &x[1], );
With the values entered via the keyboard, the aforementioned statements will initialize the
elements of the array.

Write a C Program To Sort An Array In Ascending Order Using Bubble Sort. K1 Co


3
3
#include <stdio.h>

int main() {
int arr[] = {30, 15, 25, 40, 20};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

printf("Original array: ");


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

// Sort the array using bubble sort


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;
}
}
}

printf("Sorted array (ascending): ");


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

return 0;
}
Part-C (One Question) (15 Marks)

S.No Questions BTL CO

Co3
1 Write down the example for Pass by value – Pass by reference and its difference. K2
Call By Value in C
In call by value method of parameter passing, the values of actual parameters are copied
to the function’s formal parameters.
 There are two copies of parameters stored in different memory locations.
 One is the original copy and the other is the function copy.
 Any changes made inside functions are not reflected in the actual parameters of the
caller.

// C program to illustrate call by value


#include <stdio.h>

// Function Prototype

void swapx(int x, int y);

// Main function

int main()
{
int a = 10, b = 20;

// Pass by Values

swapx(a, b); // Actual Parameters

printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;
}

.
// Swap functions that swaps

// two values

void swapx(int x, int y) // Formal Parameters

{
int t;

t = x;
x = y;
y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);

Output
Inside Function:
x = 20 y = 10
In the Caller:
a = 10 b = 20

Thus actual values of a and b remain unchanged even after exchanging the values of x and y
in the function

Call by Reference in C
In call by reference method of parameter passing, the address of the actual parameters is
passed to the function as the formal parameters. In C, we use pointers to achieve call-by-
reference.

 Both the actual and formal parameters refer to the same locations.
 Any changes made inside the function are actually reflected in the actual parameters
of the caller
Example of Call by Reference

// C program to illustrate Call by Reference


#include <stdio.h>

// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b); // Actual Parameters

printf("na Inside the Caller:\= %d b = %d\n", a, b);

return 0;
}
// Function to swap two variables
// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;

t = *x;
*x = *y;
*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);


}

Output
Inside the Function:
x = 20 y = 10
Inside the Caller:
a = 20 b = 10
UNIT-IV
POINTERS AND STRUCTURES

Pointers - Definition – Initialization - Pointer variables, Pointer arithmetic, Pointers to Pointers, Pointers
with Arrays, Pointers with Functions- Introduction to Structure – structure definition – Structure
declaration – Structure within a structure-Structures fusion with Arrays- Unions – Storage classes.

Part-A (Five Questions)

S.No Questions BTL CO


1 What is a Pointer? How a variable is declared to the pointer? K1 Co4
Pointer is a variable which holds the address of another
variable. Pointer Declaration:
datatype *variable-name;
2 What is pointer arithmetic? Explain it. K1 Co4

s pointer arithmetic? Explain it.


 When we increment (ptr++) or decrement (ptr--) a pointer, it moves by the size of
hat is pointer
the dataarithmetWhat is For
type it points to. pointer arithmetic?
example, if ptr is Explain
a pointerit.
to an int, incrementing ptr
moves the pointer to the next integer in memory.
ic? Explain it.
 The actual movement is based on the size of the data type:
o ptr++ moves to ptr + sizeof(data_type)
o ptr-- moves to ptr - sizeof(data_type)

Example
int arr[] = {10, 20, 30};
int *ptr = arr; // points to arr[0]
ptr++; // now points to arr[1]
int arr[] = {10, 20, 30};
int *ptr1 = &arr[0];
*ptr2 = &arr[2];
int diff = ptr2 - ptr1; // diff is 2, because ptr2 is 2 elements ahead of ptr1
3 Write about unions? K1 Co4
union is a special data structure that allows different data types to be stored in the same
memory location, but only one of the members can be accessed at any given time. The size
of the union is determined by the size of its largest member, and all members share the same
memory space. This is different from a struct, where each member has its own memory
location.
union UnionName {
dataType1 member1;
dataType2 member2;

};
union Data {
int i;
float f;
char str[20];
};
union is a special data structure that allows different data types to be stored in the same
memory location, but only one of the members can be accessed at any given time. The size
of the union is determined by the size of its largest member, and all members share the same
memory space. This is different from a struct, where each member has its own memory
location.

union UnionName {
dataType1 member1;
dataType2 member2;

};
union Data {
int i;
float f;
char str[20];
};

4 What are the storage classes? K1 Co4


Static is the default storage class for global variables. The two variables below (count
and road) both have a static storage class.

In C, storage classes define the scope, visibility, and lifetime of variables and functions. The
four primary storage classes are:

1. auto: The default storage class for local variables.


2. extern: Extends the visibility of variables/functions to the entire program.
3. static: Retains the variable value between function calls and restricts the
visibility of variables/functions to the current file.
4. Register: Suggests to the compiler that the variable should be stored in a CPU
register.
5 What is meant by pointer to pointer? K1 Co4
A pointer to pointer (also known as a double pointer) in C is a pointer that stores the address
of another pointer. This means it's a pointer that points to a memory location where another
pointer is stored, and that second pointer in turn points to the actual data.
int **ptr; // ptr is a pointer to a pointer to an integer
#include <stdio.h>
int main() {
int value = 10;
int *p = &value; // p points to value
int **pp = &p; // pp points to p
printf("Value: %d\n", value); // Output: 10
printf("Value via *p: %d\n", *p); // Output: 10 (p points to value)
printf("Value via **pp: %d\n", **pp); // Output: 10 (pp points to p, which points to
value)
return 0;
}
Part-B (Three Questions) (13 Marks)

S.NO Questions BTL CO

1 Describe in detail about the Pointers and explain about pointer with K2 CO4
arrays.
Pointers are one of the core components of the C programming language. A
pointer can be used to store the memory address of other variables,
functions, or even other pointers. The use of pointers allows low-level
memory access, dynamic memory allocation, and many other functionality
in C.
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the
pointer variable. We generally use the ( & ) addressof operator to get the
memory address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in
the memory address specified in the pointer. We use the same ( * )
dereferencing operator that we used in the pointer declaration.

Pointer with arrays

While declaring array, It creates a block of memory that can hold multiple
values of the same type.

int arr[5] = {10, 20, 30, 40, 50};

A pointer is a variable that holds the address of another variable. For arrays,
we can use pointers to refer to the elements in the array.
int *ptr;

The name of the array acts as a pointer to its first element.

ptr = arr; // Now ptr points to the first element of arr


Accessing Array Elements Using Pointers

we can access array elements using pointer arithmetic:

#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of arr
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, *(ptr + i)); // Accessing using pointer
}
return 0;
}

Modifying Array Elements Using Pointers

we can also modify the elements of an array through a pointer:

#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
*(ptr + i) += 5; // Increment each element by 5
}
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, arr[i]); // Print modified elements
}
return 0;
}

2 Explain about pointer with functions K2 CO4


 Pointers can be passed to functions, allowing the function to modify
the actual memory content or handle dynamic memory.

In C programming, pointers can be passed as function arguments to allow a


function to directly modify the original variable (instead of working on a
copy of the variable). This is called pass by reference, as opposed to pass
by value where only a copy of the variable is passed to the function.

 The function parameters are declared as pointers.


 dereferenced pointers are used in the function body.
 When the function is called ,the addresses are passed as
actual arguments.

By passing a pointer to a function, the function can:


1. Modify the value of the variable being pointed to.
2. Avoid creating large copies of data structures (e.g., arrays),
improving performance.

void functionName(dataType *pointerVariable) {

// Function body
}

Example-Exchanging two numbers.


#include <stdio.h>
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 5, b = 10;
printf("Before swap: a = %d, b = %d\n", a, b);
swap(&a, &b); // Pass addresses of a and b
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
3 Explain in detail about structures fusion with arrays. K2 CO4

An array of structures in C can be defined as the collection of multiple


structures variables where each variable contains information about different
entities. The array of structures in C are used to store information about
multiple entities of different data types. The array of structures is also known
as the collection of structures.

#include<stdio.h>
struct marks
{
int sub1;
int sub2;
int sub3;
int total;
};
void main()
{
int i;
struct marks student[3]={{66,77,88},{86,75,63},{65,55,64}};
struct marks total;
for(i=0;i<=2;i++)
{
student[i].total=student[i].sub1+student[i].sub2+student[i].sub3;
total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub2+student[i].sub2;
total.sub3=total.sub3+student[i].sub3;
total.total=total.total+student[i].total;
}
printf(“student total\n\n”);
for(i=0;i<=2;i++)
{
printf(“student[%d] %d\n”,i+1,student[i].total);
printf(“\n SUBJECT TOTAL\n\n”);
printf(“%s%d\n%s%d\n%s%d\n”,”subject1”,total.sub1,”subject2”,total.sub2,
”subject3”,total.sub3);
printf(“\n grand total=%d”,total.total);
}
Output
student total
student[1] 231
student[2] 224
student[3] 184

subject
subject 1 217
subject 2 207
subject 3 215
Part-C (One Question) (15 Marks)
S.NO Questions BTL CO

1 How will you declare and define Structure. Explain in detail about structure K2 CO4
within structure.

Structure Declaration and Definition

A structure allows to group different types of data together under a single


name, making it easier to manage related information.

Define the structure with the struct keyword, followed by the structure name
and its members enclosed in curly braces.

struct Person {
char name[50]; // Member to store name
int age; // Member to store age
float height; // Member to store height
};
Creating Structure Variables

After defining the structure, we can create variables of that type.


struct Person person1; // Declare a variable of type struct Person

Accessing Structure Member

We can access the members of the structure using the dot operator (.).

Example:
#include <stdio.h>
#include <string.h>

int main() {
// Declare and initialize a structure variable
struct Person person1;

// Assign values to the structure members


strcpy(person1.name, "Alice");
person1.age = 30;
person1.height = 5.5;

// Print the values


printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n", person1.height);

return 0;
}

STRUCTURE WITHIN STRUCTURE


In C, a structure within structure is a structure that contains another structure as
a member. This allows to create more complex data types that can represent
more intricate relationships between data.

Here's how to define and use a nested structure in C:

1. Define the Inner Structure: Start by defining the inner structure.


2. Define the Outer Structure: Include the inner structure as a member of
the outer structure.

Example- Printing student details


#include <stdio.h>

// Declaration of the address structure


struct address {
int houseNo;
char street[50];
char city[50];
};
// Declaration of the student structure
struct student {
char name[50];
int rollNo;
struct address addr; // Nested structure
};
int main() {
struct student stud;
// Input student details
printf("Enter student's name: ");
scanf("%s", stud.name);
printf("Enter roll number: ");
scanf("%d", &stud.rollNo);
printf("Enter house number: ");
scanf("%d", &stud.addr.houseNo);
printf("Enter street name: ");
scanf("%s", stud.addr.street);
printf("Enter city: ");
scanf("%s", stud.addr.city);
// Display student details
printf("\nStudent Details:\n");
printf("Name: %s\n", stud.name);
printf("Roll No: %d\n", stud.rollNo);
printf("Address: %d, %s, %s\n", stud.addr.houseNo, stud.addr.street,
stud.addr.city);
return 0;
}
OUTPUT:
Student Details:
Name:Priya
Roll no:1234
Address:12,kumaran street,Chennai.
Unit-V FILE PROCESSING
Files: File modes – File functions – Types of file processing: Sequential access, Random access –
Text and binary files - Command line arguments – C Preprocessor directives: Macros – Definition
– Types of Macros - Creating and implementing user defined header files.

Part-A ( Five Questions)


S.No Questions BTL CO
1 Define File and list out the types of file operations K2 Co5
A file is a collection of data or information that is stored on a storage device and can be
accessed and manipulated by a computer program. Files are used to hold various types of
data, such as documents, images, and executable programs.
Types of File Operations:
1. Create: Establishing a new file.
2. Open: Accessing an existing file for reading or writing.
3. Read: Retrieving data from a file.
4. Write: Saving data to a file.
5. Close: Terminating access to a file, ensuring all changes are saved.
6. Delete: Removing a file from storage.

These operations are essential for managing data efficiently in computer systems.

2 What is file mode in C? K1 Co5


In C, file mode specifies how a file is accessed when opened, defining the operations that
can be performed (read, write, or append). Common file modes include:
1. "r": Open for reading (file must exist).
2. "w": Open for writing (creates a new file or truncates existing).
3. "a": Open for appending (data added to the end).
4. "r+": Open for reading and writing (file must exist).
5. "w+": Open for reading and writing (creates a new file or truncates existing).

3 what is file function in c? K1 Co5


File functions in C are a set of standard library functions that facilitate file handling
operations, allowing programmers to create, read, write, and manipulate files. They
are part of the <stdio.h> library and include:
1. fopen(): Opens a file and returns a pointer to it.
2. fclose(): Closes an opened file.
3. fprintf(): Writes formatted data to a file.
4. fscanf(): Reads formatted data from a file.
5. fgets(): Reads a string from a file.
6. fputs(): Writes a string to a file.
7. fread(): Reads binary data from a file.
8. fwrite(): Writes binary data to a file.
These functions enable efficient file operations in C programming, making it easier to
handle input and output for both text and binary files.

4 What is meant by file processing in c and its types. K1 Co5


File processing in C refers to the operations performed on files to read, write, and
manipulate data stored in them. It allows programs to handle persistent data, enabling
users to save information and retrieve it later.
Types of File Processing:
1. Text File Processing:
o Definition: Involves reading from and writing to files that contain human-
readable characters.
o Functions Used:
 fopen(): To open a file.
 fprintf(): To write formatted data.
 fscanf(): To read formatted data.
 fgets(), fputs(): For reading and writing strings.
o Example Use: Storing user input or configuration settings.

2. Binary File Processing:


o Definition: Involves handling files that contain binary data, which may not be
human-readable.
o Functions Used:
 fopen(): To open a file.
 fread(): To read binary data.
 fwrite(): To write binary data.

o Example Use: Storing images, audio files, or complex data structures.

Define Command line arguments.


5 K1 Co5
Command line arguments in C are parameters that are passed to a program during
its execution from the command line interface. They enable users to provide input to
the program without modifying the source code.
Definition:
In C, command line arguments are received by the main function in the following
format:
int main (int argc, char *argv[])
 argc: An integer representing the number of command line arguments, including the
program name.
 argv: An array of strings (character pointers) containing the actual arguments.
Part-B( Three Questions) ( 13 Marks)

S.NO Questions BTL CO

1 Explain in detail about the types of file processing in C with suitable K2 CO5
example
In C, file processing is categorized mainly into two types: Text
File Processing and Binary File Processing. Each type has its
own methods and use cases.
1. Text File Processing
Definition: Text file processing refers to the handling of files that
store data in a human-readable format. These files consist of
characters organized in lines, where each line ends with a
newline character. Text files can be easily opened, edited, and
read by text editors.
Characteristics:
 Data is stored as plain text.

 Each line is typically terminated with a newline character


(\n).

Text files are easier to manipulate and view, making them
suitable for configuration files, logs, and data interchange formats
like CSV.
Common Functions:
 fopen(): Opens a file in a specified mode (e.g., read, write).

 fprintf(): Writes formatted output to a file.


 fscanf(): Reads formatted input from a file.
 fgets(): Reads a line or a string from a file.
 fputs(): Writes a string to a file.
 fclose(): Closes the file to release resources.
Example Program: -
#include <stdio.h>
int main() {
// Writing to a text file
FILE *file = fopen("example.txt", "w");
if (file) {
fprintf(file, "Hello, World!\n");
fprintf(file, "This is a text file example.\n");
fclose(file);
}
char buffer[100];
file = fopen("example.txt", "r");
if (file) {
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer); // Print each line
}fclose(file);
}
return 0;
}
Output:
Hello, World!
This is a text file example.
2. Binary File Processing
Definition: Binary file processing involves handling files that store
data in a format that
is not human-readable. Data is stored in its raw binary form, making it
more efficient for
complex data types, such as images, audio files, or structured data like
arrays and records.
Characteristics:
 Data is stored as a sequence of bytes.
 Binary files cannot be easily viewed or edited using standard text
editors.
 More efficient for large datasets or complex data structures since no
conversion to/from
text is required.
Common Functions:
 fopen(): Opens a file in binary mode (e.g., "wb" for writing, "rb" for
reading).
 fread(): Reads raw binary data from a file into memory.
 fwrite(): Writes raw binary data from memory to a file.
 fclose(): Closes the file to release resources.
Example Program:-
#include <stdio.h>
struct Data {
int id;
float value;
};
int main() {
// Writing to a binary file
FILE *file = fopen("data.bin", "wb");
struct Data d = {1, 23.45};
fwrite(&d, sizeof(struct Data), 1, file);
fclose(file);
// Reading from a binary file
struct Data readData;
file = fopen("data.bin", "rb");
fread(&readData, sizeof(struct Data), 1, file);
printf("ID: %d, Value: %.2f\n", readData.id, readData.value);
fclose(file);
return 0;
}
Output:
ID: 1, Value: 23.45
2 What are the various File access methods in C? Explain. K2 CO5
file access methods define how data is read from and written to files. The
primary file access methods are:
1. Sequential Access
Definition: In sequential access, data is processed in a linear fashion,
meaning that the program reads or writes records one after the other,
starting from the beginning of the file to the end.
Characteristics:
 Linear Processing: The file pointer moves from the
beginning to the end of the file without skipping any data.
 Simplicity: Easy to implement and understand, making it
suitable for straightforward applications.
 Ideal for Logs: Often used for log files or configuration files
where the order of data is important.
Example Program: -
#include <stdio.h>
int main() {
// Open a text file for reading
FILE *file = fopen("example.txt", "r");
char buffer[100];
// Read and print each line sequentially
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer);
}
// Close the file
fclose(file);
return 0;
}
3 How do you define and use macros in C, and how can you create a K2 CO5
user-defined header file to implement these macros?
Defining and Using Macros in C

In C programming, macros are powerful tools that allow you to


define reusable code snippets. Macros are defined using the #define
preprocessor directive and can be categorized into two main types:
object-like macros and function-like macros.

1. Object-like Macros
Definition:
Object-like macros are essentially constant definitions in C. They
allow you to define identifiers that will be replaced by specified
values throughout your code. They do not take any parameters.
Characteristics:

 Simplicity: They are straightforward and are primarily used to define


constants or simple values.
 Text Replacement: The preprocessor replaces occurrences of the
macro name in the code with the defined value before compilation.
 No Type Checking: Since they are replaced as plain text, there is no
type checking involved; this can sometimes lead to unintended
consequences if not used carefully.
Purpose:
 Code Readability: They help make the code more readable. For
instance, using #define PI 3.14 instead of directly using 3.14
enhances clarity.
 Easier Maintenance: If the value of the constant needs to change,
you only need to modify it in one place.
 Avoid Magic Numbers: They eliminate "magic numbers" from
code, making it clear what certain numbers represent.

Example:

#include <stdio.h>
#define PI 3.14 // Object-like macro defining PI
#define MAX_BUFFER_SIZE 1024 // Defining a constant for
buffer size
int main() {
printf("Value of PI: %.2f\n", PI);
printf("Max buffer size: %d\n", MAX_BUFFER_SIZE);
return 0;
}

Output:

Value of PI: 3.14


Max buffer size: 1024

2. Function-like Macros

Definition:
Function-like macros allow you to create macros that take arguments
and perform operations based on those arguments. They are similar
to functions but are expanded by the preprocessor rather than called
during runtime.

Characteristics:

 Parameter Passing: They accept parameters, making them flexible


and allowing you to perform operations on different inputs.
 Textual Substitution: The parameters in the macro are replaced with
their corresponding values wherever the macro is invoked.
 No Type Safety: Like object-like macros, they lack type checking,
which can lead to issues if not used carefully.
Purpose:
 Code Reusability: They promote code reuse, allowing you to write a
single definition that can handle various input values.
 Performance: Since they are expanded inline during preprocessing,
they can sometimes lead to performance improvements over function
calls, especially in tight loops or performance-critical code.
 Simplification of Complex Operations: They can simplify
operations that would otherwise require longer function definitions.

Example: -

#include <stdio.h>
#define SQUARE(x) ((x) * (x)) // Function-like macro to calculate
square
int main() {
int num = 5;
int square_of_num = SQUARE(num); // Calls the SQUARE
macro
printf("Square of %d: %d\n", num, square_of_num);
// Demonstrating with a different argument
printf("Square of 10: %d\n", SQUARE(10));
return 0;
}

Output:

Square of 5: 25
Square of 10: 100

Creating a User-Defined Header File for Macros:-

To organize your macros, you can create a user-defined header file.


This is useful for maintaining clean code, especially in larger
projects.
Steps to Create a Header File:

1. Create a header file: Name it mymacros.h.


2. Define your macros: Include object-like and function-like
macros in this header.
3. Include the header file: Use #include to include your header
file in your C source file.

Example: (Create the Header File (mymacros.h)

// mymacros.h
#ifndef MYMACROS_H
#define MYMACROS_H

#define PI 3.14
#define SQUARE(x) ((x) * (x))

#endif // MYMACROS_H
Example Usage in a C Program (Create the C Source File
(main.c)

// main.c
#include <stdio.h>
#include "mymacros.h"

int main() {
float radius = 5.0;
float area = PI * radius * radius;
printf("Area of the circle: %.2f\n", area);

int num = 4;
printf("Square of %d: %d\n", num, SQUARE(num));

return 0;
}

Compiling and Running the Program:-

To compile and run the program, use the following commands in the
terminal:

gcc main.c -o main


./main

Expected Output:

Area of the circle: 78.50


Square of 4: 16

Explanation of the Output

 Area Calculation: The program calculates the area of a circle with a


radius of 5.0 using the PI macro, resulting in an area of
approximately 78.50.

 Square Calculation: It calculates the square of 4 using the SQUARE


macro, resulting in 16.

This example demonstrates how to use the macros defined in mymacros.h


effectively in a C program, leading to meaningful output
Part-C (One Question) (15 Marks)

S.NO Questions BTL CO

1 Explain in detail about Command Line Argument with example program K2 CO5
 Command line arguments are a way to pass additional
information to a program when it is executed from the command
line interface (CLI). This allows users to provide inputs without
having to modify the source code of the program.

 This is done through the command line interface, and the


arguments can be accessed within the program using the main
function parameters.

 To pass command-line arguments, we typically define main()


with two arguments: the first argument is the number of
command-line arguments and the second is a list of command-
line arguments.

Syntax

int main(int argc, char *argv[]) { /* ... */ }

or

int main(int argc, char **argv) { /* ... */ }

Key Concepts:-

1. Parameters in main: The main function can take two parameters: int
argc and char *argv[].

 argc (argument count): An integer that represents the number of


command line arguments passed, including the program name.
 argv (argument vector): An array of strings (character pointers)
that holds the actual arguments.

2. Accessing Arguments: You can access the command line arguments


using the argv array. The first element (argv[0]) is always the name of
the program, and subsequent elements are the arguments.
Properties of Command Line Arguments in C

1) They are passed to the main() function.


2) They are parameters/arguments supplied to the program when it
is invoked.
3) They are used to control programs from outside instead of hard
coding those values inside the code.
4) argv[argc] is a NULL pointer.
5) argv[0] holds the name of the program.
6) argv[1] points to the first command line argument and
argv[argc-1] points to the last argument.

Example Program: Sum of Command Line Arguments

Here’s a simple C program that takes command line arguments representing


numbers and calculates their sum.

Program: sum_args.c

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int sum = 0;
// Check if at least one argument is provided
if (argc < 2) {
printf("Please provide numbers as command line arguments.\n");
return 1;
}
// Iterate through the arguments starting from argv[1]
for (int i = 1; i < argc; i++) {
// Convert each argument to an integer and add to sum
sum += atoi(argv[i]);
}
// Print the sum of the numbers
printf("The sum of the provided numbers is: %d\n", sum);
return 0;
}
How to Compile and Run the Program
1. Save the code in a file named sum_args.c.
2. Open your command line interface (Terminal on macOS/Linux or
Command Prompt/PowerShell on Windows).
3. Navigate to the directory where the file is saved.
4. Compile the program using a C compiler (like gcc):
gcc -o sum_args sum_args.c

5. Run the program with some numbers as arguments:


./sum_args 5 10 15

Expected Output

When you run the command above, you should see:


The sum of the provided numbers is: 30

 Here’s a point-by-point explanation of the program sum_args.c:

Program Structure

1. Include Libraries:

 #include <stdio.h>: For input/output functions.


 #include <stdlib.h>: For utility functions like atoi.

2. Main Function:

 int main(int argc, char *argv[]): Entry point of the


program.
 argc: Counts the number of command line arguments.
 argv[]: Array of strings holding the actual arguments.

3. Variable Initialization:

 int sum = 0;: Initializes a variable to store the sum of the


numbers.

4. Argument Count Check:


 if (argc < 2): Checks if at least one number is provided
(besides the program name).
 If true, it prints an error message and exits with return
1;.
5. Loop Through Arguments:
 for (int i = 1; i < argc; i++): Loops through each
argument starting from argv[1].
6. Convert and Add:
 sum += atoi(argv[i]);: Converts each string argument to an
integer and adds it to sum.
7. Output the Result:
 printf("The sum of the provided numbers is: %d\n",
sum);: Displays the total sum to the user.
8. Return Statement:
 return 0;: Indicates successful execution of the program.

You might also like