pc(EEE)
pc(EEE)
(AUTONOMOUS)
QUESTION BANK
Year/Sem : I/I
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.
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)
BEGIN
// Step 1: Declare variables
DECLARE a, b, product AS INTEGER
#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:-
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.
BEGIN
// Step 1: Input
PRINT "Enter first number (a):"
READ a
PRINT "Enter second number (b):"
READ b
// Step 3: Output
PRINT "After swapping:"
PRINT "a =", a
PRINT "b =", b
END
iii) Flowchart 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);
// 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 is a structured approach that can help you tackle challenges effectively.
Here are the key steps typically involved:
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.
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.
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?
Iteration
Recursion
Iteration:-
#include <stdio.h>
int main() {
int n, sum = 0;
#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:-
#include <stdio.h>
int main() {
int i = 1; // Start from 1
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.
#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)
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.
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;
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:
./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.
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.
// for loop
}
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.
STRUCTURE OF A C PROGRAM
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)
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.
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 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.
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:
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.
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,
int main() {
int arr[] = {30, 15, 25, 40, 20};
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
return 0;
}
Part-C (One Question) (15 Marks)
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.
// Function Prototype
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
return 0;
}
.
// Swap functions that swaps
// two values
{
int t;
t = x;
x = y;
y = t;
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
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b); // Actual Parameters
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;
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.
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];
};
In C, storage classes define the scope, visibility, and lifetime of variables and functions. The
four primary storage classes are:
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.
While declaring array, It creates a block of memory that can hold multiple
values of the same type.
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;
#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;
}
#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;
}
// Function body
}
#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.
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
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;
return 0;
}
These operations are essential for managing data efficiently in computer systems.
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.
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:
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:
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:
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
// 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;
}
To compile and run the program, use the following commands in the
terminal:
Expected Output:
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.
Syntax
or
Key Concepts:-
1. Parameters in main: The main function can take two parameters: int
argc and char *argv[].
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
Expected Output
Program Structure
1. Include Libraries:
2. Main Function:
3. Variable Initialization: