0% found this document useful (0 votes)
17 views90 pages

POP QUESTION BANK

The document provides definitions and algorithms for various programming concepts in C, including algorithms for calculating the area and perimeter of a circle, finding the largest of three numbers, and understanding flowcharts. It also covers basic structures of C programs, types of tokens, operators, data types, and examples of C programs for different computations. Additionally, it explains type conversion, formatted input/output functions, and conditional control statements used in C.

Uploaded by

Avani Shetty
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)
17 views90 pages

POP QUESTION BANK

The document provides definitions and algorithms for various programming concepts in C, including algorithms for calculating the area and perimeter of a circle, finding the largest of three numbers, and understanding flowcharts. It also covers basic structures of C programs, types of tokens, operators, data types, and examples of C programs for different computations. Additionally, it explains type conversion, formatted input/output functions, and conditional control statements used in C.

Uploaded by

Avani Shetty
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/ 90

MODULE 1

1. Define Algorithm. Write an algorithm to find the area and perimeter of a Circle.

Algorithm Definition:
An algorithm is a step-by-step procedure or set of rules to solve a specific problem or
perform a computation. It is a well-defined sequence of instructions that takes input,
processes it, and produces an output.

Algorithm to Find Area and Perimeter of a Circle:

1. Start.

2. Input the radius (r) of the circle.

3. Calculate the area using the formula:


Area = π * r * r
(where π is approximately 3.14159).

4. Calculate the perimeter (circumference) using the formula:


Perimeter = 2 * π * r.

5. Output the calculated Area and Perimeter.

6. Stop

Algorithm to Find the Largest of 3 Numbers:

1. Start.

2. Input three numbers: num1, num2, and num3.

3. Compare num1 and num2:

o If num1 > num2, store num1 in a temporary variable largest.

o Else, store num2 in largest.

4. Compare largest with num3:

o If num3 > largest, update largest to num3.

5. Output largest as the largest number.

6. Stop.

Compare Pseudocode with an Algorithm.


Pseudocode Algorithm

Informal way of writing code using plain Formal step-by-step procedure to solve a
English. problem.

Not tied to any programming language Can be implemented in any programming


syntax. language.

Focuses on logic and structure. Focuses on both logic and implementation.

Easier to understand for non-programmers. Requires technical understanding.

2. Define Flowchart. Explain with an example.

Flowchart Definition:
A flowchart is a graphical representation of an algorithm or process. It uses symbols like
rectangles, diamonds, and arrows to represent steps, decisions, and flow of control.

Example: Flowchart to Find the Largest of 3 Numbers

1. Start (Oval symbol).

2. Input three numbers (Rectangle symbol).

3. Compare numbers using decision symbols (Diamond symbol).

4. Display the largest number (Rectangle symbol).

5. Stop (Oval symbol).

Draw the Flowchart and Write a C Program to Compute Simple Interest.

Flowchart:

1. Start.

2. Input Principal (P), Rate (R), and Time (T).

3. Calculate Simple Interest (SI) using the formula:


SI = (P * R * T) / 100.

4. Output SI.

5. Stop.

C Program:
Copy

#include <stdio.h>

int main() {

float P, R, T, SI;

printf("Enter Principal, Rate, and Time: ");

scanf("%f %f %f", &P, &R, &T);

SI = (P * R * T) / 100;

printf("Simple Interest = %.2f", SI);

return 0;

3. Explain the Basic Structure of a C Program with an Example.

Basic Structure of a C Program:

1. Preprocessor Directives:
Include header files (e.g., #include <stdio.h>).

2. Main Function:
Entry point of the program (int main()).

3. Variable Declarations:
Declare variables (e.g., int a, b;).

4. Executable Statements:
Perform operations (e.g., a = 10; b = 20;).

5. Return Statement:
End the program (return 0;).

Example:

#include <stdio.h> // Preprocessor Directive

int main() { // Main Function

int a = 10, b = 20; // Variable Declarations

printf("Sum = %d", a + b); // Executable Statement


return 0; // Return Statement

4. What is a Token? What are the Different Types of Tokens Available in C Language?

Token Definition:
A token is the smallest individual unit in a C program. It can be a keyword, identifier,
constant, string, operator, or symbol.

Types of Tokens in C:

1. Keywords (e.g., int, return).

2. Identifiers (e.g., variable names like num1).

3. Constants (e.g., 10, 3.14).

4. Strings (e.g., "Hello").

5. Operators (e.g., +, -, *).

6. Special Symbols (e.g., ;, {}).

5. Write and Explain the Basic Concepts of a C Program.

Basic Concepts of a C Program:

1. Variables:
Used to store data (e.g., int a = 10;).

2. Data Types:
Define the type of data (e.g., int, float, char).

3. Operators:
Perform operations (e.g., +, -, *).

4. Control Structures:
Manage program flow (e.g., if, for, while).

5. Functions:
Reusable blocks of code (e.g., printf(), scanf()).

6. Arrays:
Store multiple values of the same type.

7. Pointers:
Store memory addresses.
6. What is an Identifier (Variable)? What are the Rules to Construct Identifiers?

Identifier Definition:
An identifier is a name given to a variable, function, or other user-defined items. It must be
unique and follow specific rules.

Rules for Constructing Identifiers:

1. Must start with a letter (A-Z, a-z) or underscore (_).

2. Can contain letters, digits (0-9), and underscores.

3. Cannot contain special characters (e.g., +, #).

4. Cannot be a keyword (e.g., int, return).

Valid/Invalid Identifiers:

1. num2 - Valid.

2. $num1 - Invalid (starts with $).

3. +add - Invalid (contains +).

4. a_2 - Valid.

5. 199_space - Invalid (starts with a digit).

6. _apple - Valid.

7. #12 - Invalid (contains #).

What is a Variable? List the Restrictions on Variable Names.

Variable Definition:
A variable is a named memory location used to store data that can be modified during
program execution.

Restrictions on Variable Names:

1. Cannot start with a digit.

2. Cannot contain spaces or special characters (except _).

3. Cannot be a keyword.

4. Must be unique within its scope.


Define Variable. Explain the Rules for Constructing Variables in C Language.

Variable Definition:
A variable is a container for storing data values. It has a name, type, and value.

Rules for Constructing Variables:

1. Must start with a letter or underscore.

2. Can contain letters, digits, and underscores.

3. Cannot contain special characters or spaces.

4. Must be unique within its scope.

Define:

1. Variable:
A named memory location used to store data.

2. Constant:
A value that cannot be changed during program execution (e.g., const int a = 10;).

3. Associativity:
Determines the order in which operators of the same precedence are evaluated (e.g.,
left-to-right for +).

4. Precedence:
Determines the order in which operators are evaluated (e.g., * has higher
precedence than +).

7. Explain with Example, the Various Constants Available in C Language

Constants in C:
Constants are fixed values that do not change during program execution. They can be of
different types:

1. Integer Constants:
Whole numbers without fractional parts.
Example: 10, -5, 0.

2. Floating-Point Constants:
Numbers with fractional parts.
Example: 3.14, -0.5, 2.0.
3. Character Constants:
Single characters enclosed in single quotes.
Example: 'A', '1', '$'.

4. String Constants:
Sequence of characters enclosed in double quotes.
Example: "Hello", "C Programming".

5. Escape Sequence Constants:


Special characters starting with a backslash (\).
Example: \n (newline), \t (tab), \\ (backslash).

8. List All the Operators Used in C. Give Examples

Operators in C:

1. Arithmetic Operators: +, -, *, /, %.

2. Relational Operators: ==, !=, >, <, >=, <=.

3. Logical Operators: &&, ||, !.

4. Assignment Operators: =, +=, -=, *=, /=.

5. Increment/Decrement Operators: ++, --.

6. Bitwise Operators: &, |, ^, ~, <<, >>.

7. Conditional (Ternary) Operator: ? :.

8. Special Operators: sizeof(), , (comma operator).

Explain Any Five Operators Used in C Language

1. Arithmetic Operator (+):


Adds two numbers.
Example: int sum = 5 + 3; // sum = 8.

2. Relational Operator (>):


Compares two values.
Example: if (a > b) { /* code */ }.

3. Logical Operator (&&):


Logical AND. Returns true if both conditions are true.
Example: if (a > 0 && b > 0) { /* code */ }.
4. Assignment Operator (=):
Assigns a value to a variable.
Example: int x = 10;.

5. Increment Operator (++):


Increases the value of a variable by 1.
Example: int a = 5; a++; // a = 6.

What is an Operator? List and Explain Various Types of Operators

Operator Definition:
An operator is a symbol that performs operations on operands (variables or values).

Types of Operators:

1. Arithmetic Operators: Perform mathematical operations.

2. Relational Operators: Compare two values.

3. Logical Operators: Combine multiple conditions.

4. Assignment Operators: Assign values to variables.

5. Bitwise Operators: Perform operations on binary digits.

6. Conditional Operator: Shorthand for if-else.

Explain the Following Operators in C Language:

1. Relational Operators:
Used to compare two values.
Example: if (a == b) { /* code */ }.

2. Logical Operators:
Used to combine multiple conditions.
Example: if (a > 0 && b > 0) { /* code */ }.

3. Conditional Operator (? :):


Shorthand for if-else.
Example: int max = (a > b) ? a : b;.

9. What is an Assignment Statement? Give the General Form of an Assignment Statement

Assignment Statement:
An assignment statement assigns a value to a variable.
General Form:
variable = expression;
Example: int x = 10;.

10. What are Basic Data Types Available in C? Write the Significance of Each Data Type

Basic Data Types in C:

1. int: Stores integers.


Example: int age = 25;.

2. float: Stores single-precision floating-point numbers.


Example: float pi = 3.14;.

3. double: Stores double-precision floating-point numbers.


Example: double distance = 123.456;.

4. char: Stores single characters.


Example: char grade = 'A';.

Significance:

• int: Used for whole numbers.

• float and double: Used for decimal numbers.

• char: Used for characters.

Write a C Program that Computes the Size of int, float, double, and char Variables

Copy

#include <stdio.h>

int main() {

printf("Size of int: %lu bytes\n", sizeof(int));

printf("Size of float: %lu bytes\n", sizeof(float));

printf("Size of double: %lu bytes\n", sizeof(double));

printf("Size of char: %lu bytes\n", sizeof(char));

return 0;

}
11. What is Type Conversion? Explain Two Types of Conversion with Examples

Type Conversion:
The process of converting one data type to another.

1. Implicit Conversion:
Automatically performed by the compiler.
Example: int a = 10; float b = a;.

2. Explicit Conversion:
Manually performed by the programmer using casting.
Example: float a = 10.5; int b = (int)a;.

12. What are the Formatted Input and Output Functions? Explain with Examples

Formatted Input/Output Functions:

1. printf():
Used to display output.
Example: printf("Hello, World!");.

2. scanf():
Used to take input.
Example: scanf("%d", &num);.

Write the Guidelines to Use scanf() and printf() Functions in C Language

1. printf() Guidelines:

o Use format specifiers (e.g., %d, %f, %c).

o Example: printf("Number: %d", num);.

2. scanf() Guidelines:

o Use & before variable names (except for strings).

o Example: scanf("%d", &num);.

What is the Purpose of scanf() and printf() Statements?

1. scanf():
Used to read input from the user.
2. printf():
Used to display output to the user.

13. Write a C Program to Find the Area and Perimeter of a Circle

Copy

#include <stdio.h>

#define PI 3.14159

int main() {

float radius, area, perimeter;

printf("Enter the radius of the circle: ");

scanf("%f", &radius);

area = PI * radius * radius;

perimeter = 2 * PI * radius;

printf("Area of the circle = %.2f\n", area);

printf("Perimeter of the circle = %.2f\n", perimeter);

return 0;

14. Write a Program in C to Print the Numbers from 4 to 9 and Their Squares

Copy

#include <stdio.h>

int main() {
printf("Number\tSquare\n");

for (int i = 4; i <= 9; i++) {

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

return 0;

15. Write a C Program to Find the Area and Perimeter of a Rectangle

Copy

#include <stdio.h>

int main() {

float length, width, area, perimeter;

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

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

area = length * width;

perimeter = 2 * (length + width);

printf("Area of the rectangle = %.2f\n", area);

printf("Perimeter of the rectangle = %.2f\n", perimeter);

return 0;

16. Write a C Program Which Takes as Input p, t, r. Compute the Simple Interest and
Display the Result

c
Copy

#include <stdio.h>

int main() {

float p, t, r, simple_interest;

printf("Enter principal (p), time (t), and rate (r): ");

scanf("%f %f %f", &p, &t, &r);

simple_interest = (p * t * r) / 100;

printf("Simple Interest = %.2f\n", simple_interest);

return 0;

17. Write a C Program to Find the Area of a Triangle When We Know the Lengths of
All Three of Its Sides

Copy

#include <stdio.h>

#include <math.h>

int main() {

float a, b, c, s, area;

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

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

s = (a + b + c) / 2; // Semi-perimeter

area = sqrt(s * (s - a) * (s - b) * (s - c)); // Heron's formula

printf("Area of the triangle = %.2f\n", area);


return 0;

18. Write a C Program to Find the Largest of Three Numbers Using Ternary Operator

Copy

#include <stdio.h>

int main() {

int a, b, c, largest;

printf("Enter three numbers: ");

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

largest = (a > b) ? (a > c ? a : c) : (b > c ? b : c);

printf("The largest number is: %d\n", largest);

return 0;

MODULE 2
1. List All Conditional Control Statements Used in C. Explain Any Two with Syntax and
Example

Conditional Control Statements in C:

1. if statement

2. if-else statement

3. nested if statement

4. else-if ladder
5. switch statement

a) if Statement:

Syntax:

Copy

if (condition) {

// Code to execute if condition is true

Example:

Copy

#include <stdio.h>

int main() {

int num = 10;

if (num > 0) {

printf("Number is positive.");

return 0;

b) if-else Statement:

Syntax:

Copy

if (condition) {

// Code to execute if condition is true

} else {
// Code to execute if condition is false

Example:

Copy

#include <stdio.h>

int main() {

int num = -5;

if (num > 0) {

printf("Number is positive.");

} else {

printf("Number is not positive.");

return 0;

2. Write a C Program that Reads from the User an Arithmetic Operator and Two
Operands, Perform the Corresponding Arithmetic Operation on the Operands Using
Switch Statement

Copy

#include <stdio.h>

int main() {

char operator;

float num1, num2;

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

scanf("%c", &operator);

printf("Enter two operands: ");

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


switch (operator) {

case '+':

printf("%.2f + %.2f = %.2f", num1, num2, num1 + num2);

break;

case '-':

printf("%.2f - %.2f = %.2f", num1, num2, num1 - num2);

break;

case '*':

printf("%.2f * %.2f = %.2f", num1, num2, num1 * num2);

break;

case '/':

if (num2 != 0)

printf("%.2f / %.2f = %.2f", num1, num2, num1 / num2);

else

printf("Error! Division by zero.");

break;

default:

printf("Error! Invalid operator.");

return 0;

3. Implement a C Program to Find the Reverse of an Integer Number and Check


Whether It is Palindrome or Not

Copy

#include <stdio.h>
int main() {

int num, reversed = 0, remainder, original;

printf("Enter an integer: ");

scanf("%d", &num);

original = num;

while (num != 0) {

remainder = num % 10;

reversed = reversed * 10 + remainder;

num /= 10;

if (original == reversed)

printf("%d is a palindrome.", original);

else

printf("%d is not a palindrome.", original);

return 0;

4. What are Unconditional Control Statements? Explain Any Two with Syntax and
Example

Unconditional Control Statements:

1. break

2. continue

3. goto

4. return
a) break Statement:

Syntax:

Copy

break;

Example:

Copy

#include <stdio.h>

int main() {

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

if (i == 5)

break;

printf("%d ", i);

return 0;

b) continue Statement:

Syntax:

Copy

continue;

Example:

Copy

#include <stdio.h>

int main() {
for (int i = 1; i <= 10; i++) {

if (i == 5)

continue;

printf("%d ", i);

return 0;

5. Write a C Program to Find the Biggest of Three Numbers

Copy

#include <stdio.h>

int main() {

int a, b, c;

printf("Enter three numbers: ");

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

if (a > b && a > c)

printf("%d is the largest.", a);

else if (b > a && b > c)

printf("%d is the largest.", b);

else

printf("%d is the largest.", c);

return 0;

6. Explain Switch Statement with Syntax and Example


Syntax:

Copy

switch (expression) {

case constant1:

// Code to execute if expression == constant1

break;

case constant2:

// Code to execute if expression == constant2

break;

default:

// Code to execute if no case matches

Example:

Copy

#include <stdio.h>

int main() {

int day = 3;

switch (day) {

case 1: printf("Monday"); break;

case 2: printf("Tuesday"); break;

case 3: printf("Wednesday"); break;

default: printf("Invalid day.");

return 0;

}
7. List the Differences Between While Loop and Do-While Loop. Write a C Program to
Find the Sum of Natural Numbers from 1 to N Using For Loop

Differences:

While Loop Do-While Loop

Checks condition before execution. Checks condition after execution.

May not execute at all. Executes at least once.

C Program:

Copy

#include <stdio.h>

int main() {

int n, sum = 0;

printf("Enter a positive integer: ");

scanf("%d", &n);

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

sum += i;

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

return 0;

8. Write a C Program to Find the Factorial of a Number Using Do-While, Where the
Number N is Entered by the User

Copy

#include <stdio.h>
int main() {

int n, factorial = 1;

printf("Enter a positive integer: ");

scanf("%d", &n);

int i = 1;

do {

factorial *= i;

i++;

} while (i <= n);

printf("Factorial of %d = %d", n, factorial);

return 0;

9. What is Two-Way Selection Statement? Explain if, if-else, and Cascaded if-else with
Examples

Two-Way Selection Statement:


A decision-making statement that chooses between two paths based on a condition.

a) if Statement:

Example:

Copy

if (age >= 18) {

printf("You are eligible to vote.");

b) if-else Statement:
Example:

Copy

if (age >= 18) {

printf("You are eligible to vote.");

} else {

printf("You are not eligible to vote.");

c) Cascaded if-else Statement:

Example:

Copy

if (marks >= 90) {

printf("Grade: A");

} else if (marks >= 80) {

printf("Grade: B");

} else if (marks >= 70) {

printf("Grade: C");

} else {

printf("Grade: D");

10. Write a C Program that Takes from User an Arithmetic Operator (+, -, *, or /) and
Two Operands. Perform Corresponding Arithmetic Operation on the Operands Using
Switch Statement

Copy

#include <stdio.h>
int main() {

char operator;

float num1, num2;

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

scanf("%c", &operator);

printf("Enter two operands: ");

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

switch (operator) {

case '+':

printf("%.2f + %.2f = %.2f", num1, num2, num1 + num2);

break;

case '-':

printf("%.2f - %.2f = %.2f", num1, num2, num1 - num2);

break;

case '*':

printf("%.2f * %.2f = %.2f", num1, num2, num1 * num2);

break;

case '/':

if (num2 != 0)

printf("%.2f / %.2f = %.2f", num1, num2, num1 / num2);

else

printf("Error! Division by zero.");

break;

default:

printf("Error! Invalid operator.");

return 0;
}

11. Explain with Example, the Meaning of Statement and Block in a C Program

Statement:
A statement is a single instruction in a C program that performs a specific task. It ends
with a semicolon (;).

Example:

Copy

int a = 10; // Statement

printf("Hello"); // Statement

Block:
A block is a group of statements enclosed in curly braces {}. It is treated as a single unit.

Example:

Copy

int a = 10;

printf("%d", a);

12. Write a C Program to Demonstrate the Use of Unconditional goto Statement

Copy

#include <stdio.h>

int main() {

int num;

printf("Enter a positive number: ");

scanf("%d", &num);
if (num <= 0) {

goto end; // Jump to label 'end'

printf("You entered a positive number: %d", num);

return 0;

end:

printf("Invalid input! Number must be positive.");

return 0;

13. Explain with Syntax, if, if-else, and Nested if-else Statements in C Program

a) if Statement:

Syntax:

Copy

if (condition) {

// Code to execute if condition is true

Example:

Copy

if (age >= 18) {

printf("You are eligible to vote.");

b) if-else Statement:
Syntax:

Copy

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false

Example:

Copy

if (marks >= 40) {

printf("Passed.");

} else {

printf("Failed.");

c) Nested if-else Statement:

Syntax:

Copy

if (condition1) {

// Code to execute if condition1 is true

} else if (condition2) {

// Code to execute if condition2 is true

} else {

// Code to execute if all conditions are false

Example:
c

Copy

if (marks >= 90) {

printf("Grade: A");

} else if (marks >= 80) {

printf("Grade: B");

} else {

printf("Grade: C");

14. Explain with Syntax, the Different Loops Used in C Program

a) for Loop:

Syntax:

Copy

for (initialization; condition; update) {

// Code to execute

Example:

Copy

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

printf("%d ", i);

b) while Loop:

Syntax:

Copy
while (condition) {

// Code to execute

Example:

Copy

int i = 1;

while (i <= 5) {

printf("%d ", i);

i++;

c) do-while Loop:

Syntax:

Copy

do {

// Code to execute

} while (condition);

Example:

Copy

int i = 1;

do {

printf("%d ", i);

i++;

} while (i <= 5);


15. Write a Program in C to Find the Sum of n Natural Numbers Without Using Any
Loops

Copy

#include <stdio.h>

int main() {

int n, sum;

printf("Enter a positive integer: ");

scanf("%d", &n);

sum = n * (n + 1) / 2; // Formula for sum of first n natural numbers

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

return 0;

16. Write a C Program that Takes Three Coefficients (a, b, and c) of a Quadratic
Equation (ax^2 + bx + c) as Input and Compute All Possible Roots and Print Them with
Appropriate Messages

Copy

#include <stdio.h>

#include <math.h>

int main() {

float a, b, c, discriminant, root1, root2;

printf("Enter coefficients a, b, and c: ");

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

discriminant = b * b - 4 * a * c;
if (discriminant > 0) {

root1 = (-b + sqrt(discriminant)) / (2 * a);

root2 = (-b - sqrt(discriminant)) / (2 * a);

printf("Roots are real and different: %.2f and %.2f", root1, root2);

} else if (discriminant == 0) {

root1 = -b / (2 * a);

printf("Roots are real and same: %.2f", root1);

} else {

float realPart = -b / (2 * a);

float imaginaryPart = sqrt(-discriminant) / (2 * a);

printf("Roots are complex: %.2f + %.2fi and %.2f - %.2fi", realPart, imaginaryPart,
realPart, imaginaryPart);

return 0;

17. Show How break and continue Statements Are Used in a C Program, with Example

a) break Statement:

Example:

Copy

#include <stdio.h>

int main() {

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

if (i == 5)

break; // Exit the loop when i == 5

printf("%d ", i);


}

return 0;

b) continue Statement:

Example:

Copy

#include <stdio.h>

int main() {

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

if (i == 5)

continue; // Skip the rest of the loop when i == 5

printf("%d ", i);

return 0;

18. Explain with Examples Formatted Input/Output Statements in C

a) printf():

Example:

Copy

printf("Hello, World!\n");

printf("Number: %d\n", 10);

printf("Float: %.2f\n", 3.14);

b) scanf():

Example:

c
Copy

int num;

printf("Enter a number: ");

scanf("%d", &num);

19. Write a C Program to Find GCD of Two Numbers Using Ternary Operator and For
Loop

Copy

#include <stdio.h>

int main() {

int num1, num2, gcd;

printf("Enter two numbers: ");

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

for (int i = 1; i <= num1 && i <= num2; i++) {

gcd = (num1 % i == 0 && num2 % i == 0) ? i : gcd;

printf("GCD = %d", gcd);

return 0;

20. Write a Calculator Program in C Language to Do Simple Operations Like Addition,


Subtraction, Multiplication, and Division. Use Switch Statement in Your Program

Copy

#include <stdio.h>

int main() {
char operator;

float num1, num2;

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

scanf("%c", &operator);

printf("Enter two operands: ");

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

switch (operator) {

case '+':

printf("%.2f + %.2f = %.2f", num1, num2, num1 + num2);

break;

case '-':

printf("%.2f - %.2f = %.2f", num1, num2, num1 - num2);

break;

case '*':

printf("%.2f * %.2f = %.2f", num1, num2, num1 * num2);

break;

case '/':

if (num2 != 0)

printf("%.2f / %.2f = %.2f", num1, num2, num1 / num2);

else

printf("Error! Division by zero.");

break;

default:

printf("Error! Invalid operator.");

return 0;

}
21. What is Dangling Else Problem? Explain How to Handle It in C Programming

Dangling Else Problem:


It occurs when an else statement is ambiguously associated with an if statement due to
improper indentation or missing braces.

Example:

Copy

if (condition1)

if (condition2)

printf("Condition2 is true");

else

printf("Condition1 is false"); // This else belongs to the inner if

Solution:
Use braces {} to explicitly define the scope of if and else.

Corrected Code:

Copy

if (condition1) {

if (condition2) {

printf("Condition2 is true");

} else {

printf("Condition1 is false");

MODULE 3
1. What is an Array? Explain the Declaration and Initialization of One-Dimensional and
Two-Dimensional Arrays with an Example

Array Definition:
An array is a collection of elements of the same data type stored in contiguous memory
locations. It allows storing multiple values under a single variable name.

a) One-Dimensional Array:

Declaration:

Copy

data_type array_name[size];

Example: int numbers[5];

Initialization:

Copy

data_type array_name[size] = {value1, value2, ..., valueN};

Example: int numbers[5] = {10, 20, 30, 40, 50};

b) Two-Dimensional Array:

Declaration:

Copy

data_type array_name[row_size][column_size];

Example: int matrix[3][3];

Initialization:

Copy

data_type array_name[row_size][column_size] = {

{value11, value12, ...},


{value21, value22, ...},

...

};

Example: int matrix[2][2] = {{1, 2}, {3, 4}};

2. Write a C Program to Read N Integers into an Array A and to Find the (i) Sum of Odd
Numbers, (ii) Sum of Even Numbers, (iii) Average of All Numbers

Copy

#include <stdio.h>

int main() {

int n, sum_odd = 0, sum_even = 0, total_sum = 0;

float average;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

total_sum += A[i];

if (A[i] % 2 == 0)

sum_even += A[i];

else

sum_odd += A[i];

}
average = (float)total_sum / n;

printf("Sum of odd numbers: %d\n", sum_odd);

printf("Sum of even numbers: %d\n", sum_even);

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

return 0;

3. Write a C Program to Search an Element Using Linear and Binary Techniques

a) Linear Search:

Copy

#include <stdio.h>

int main() {

int n, key, found = 0;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

printf("Enter the element to search: ");

scanf("%d", &key);
for (int i = 0; i < n; i++) {

if (A[i] == key) {

printf("Element found at index %d\n", i);

found = 1;

break;

if (!found)

printf("Element not found.\n");

return 0;

b) Binary Search:

Copy

#include <stdio.h>

int main() {

int n, key, low, high, mid, found = 0;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers in ascending order:\n", n);

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

scanf("%d", &A[i]);
}

printf("Enter the element to search: ");

scanf("%d", &key);

low = 0;

high = n - 1;

while (low <= high) {

mid = (low + high) / 2;

if (A[mid] == key) {

printf("Element found at index %d\n", mid);

found = 1;

break;

} else if (A[mid] < key) {

low = mid + 1;

} else {

high = mid - 1;

if (!found)

printf("Element not found.\n");

return 0;

4. Write a C Program for (i) Bubble Sort (ii) Linear Search


a) Bubble Sort:

Copy

#include <stdio.h>

int main() {

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

// Bubble Sort

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

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

if (A[j] > A[j + 1]) {

int temp = A[j];

A[j] = A[j + 1];

A[j + 1] = temp;

printf("Sorted array:\n");
for (int i = 0; i < n; i++) {

printf("%d ", A[i]);

return 0;

b) Linear Search:

Copy

#include <stdio.h>

int main() {

int n, key, found = 0;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

printf("Enter the element to search: ");

scanf("%d", &key);

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

if (A[i] == key) {

printf("Element found at index %d\n", i);


found = 1;

break;

if (!found)

printf("Element not found.\n");

return 0;

5. Write a C Program to Find the Sum and Average of N Integer Numbers

Copy

#include <stdio.h>

int main() {

int n, sum = 0;

float average;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

sum += A[i];

}
average = (float)sum / n;

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

printf("Average = %.2f\n", average);

return 0;

6. Write a C Program to Find the Largest Element in an Array

Copy

#include <stdio.h>

int main() {

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

int largest = A[0];

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

if (A[i] > largest) {


largest = A[i];

printf("Largest element = %d\n", largest);

return 0;

7. Write a C Program to Find the Greatest Number from a Two-Dimensional Array

Copy

#include <stdio.h>

int main() {

int rows, cols;

printf("Enter the number of rows and columns: ");

scanf("%d %d", &rows, &cols);

int A[rows][cols];

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

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

for (int j = 0; j < cols; j++) {

scanf("%d", &A[i][j]);

int greatest = A[0][0];


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

for (int j = 0; j < cols; j++) {

if (A[i][j] > greatest) {

greatest = A[i][j];

printf("Greatest number = %d\n", greatest);

return 0;

8. Write a C Program to Sort the Elements by Passing Array as Function Argument

Copy

#include <stdio.h>

// Function to sort an array using Bubble Sort

void bubbleSort(int A[], int n) {

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

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

if (A[j] > A[j + 1]) {

int temp = A[j];

A[j] = A[j + 1];

A[j + 1] = temp;

}
}

int main() {

int n;

printf("Enter the number of elements: ");

scanf("%d", &n);

int A[n];

printf("Enter %d integers:\n", n);

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

scanf("%d", &A[i]);

bubbleSort(A, n);

printf("Sorted array:\n");

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

printf("%d ", A[i]);

return 0;

9. Define String. How String is Declared and Initialized? Explain String Input/Output
Functions with an Example

String Definition:
A string is a sequence of characters stored in contiguous memory locations, terminated
by a null character (\0).
Declaration and Initialization:

Copy

char str[] = "Hello"; // Initialization

char str[10]; // Declaration

String Input/Output Functions:

1. scanf(): Reads a string from the user.

Copy

char str[100];

scanf("%s", str); // Reads a single word

2. gets(): Reads a line of text (unsafe, avoid using).

Copy

char str[100];

gets(str); // Reads a line

3. fgets(): Safely reads a line of text.

Copy

char str[100];

fgets(str, sizeof(str), stdin); // Reads a line

4. printf(): Prints a string.

Copy

printf("String: %s\n", str);

Example:

Copy
#include <stdio.h>

int main() {

char str[100];

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

printf("You entered: %s", str);

return 0;

10. What is a String? Write a C Program that Reads a Sentence and Prints the
Frequency of Each of the Vowels and Total Count of Consonants

String Definition:
A string is a sequence of characters terminated by a null character (\0).

C Program:

Copy

#include <stdio.h>

#include <ctype.h>

int main() {

char str[100];

int vowels[5] = {0}, consonants = 0; // a, e, i, o, u

printf("Enter a sentence: ");

fgets(str, sizeof(str), stdin);

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

char ch = tolower(str[i]);

if (ch == 'a') vowels[0]++;

else if (ch == 'e') vowels[1]++;


else if (ch == 'i') vowels[2]++;

else if (ch == 'o') vowels[3]++;

else if (ch == 'u') vowels[4]++;

else if (isalpha(ch)) consonants++;

printf("Frequency of vowels:\n");

printf("a: %d\n", vowels[0]);

printf("e: %d\n", vowels[1]);

printf("i: %d\n", vowels[2]);

printf("o: %d\n", vowels[3]);

printf("u: %d\n", vowels[4]);

printf("Total consonants: %d\n", consonants);

return 0;

11. Write a C Program to Eliminate Multiple Spaces from a Sentence and Make It Single

Copy

#include <stdio.h>

int main() {

char str[100], result[100];

int i = 0, j = 0;

printf("Enter a sentence: ");

fgets(str, sizeof(str), stdin);


while (str[i] != '\0') {

if (str[i] != ' ' || (i > 0 && str[i - 1] != ' ')) {

result[j++] = str[i];

i++;

result[j] = '\0';

printf("Modified sentence: %s\n", result);

return 0;

12. Explain with Syntax and Example, the Different String Manipulation Library
Functions

Common String Functions:

1. strlen(): Returns the length of a string.

Copy

size_t strlen(const char *str);

Example:

Copy

char str[] = "Hello";

printf("Length: %zu\n", strlen(str)); // Output: 5

2. strcpy(): Copies a string.

Copy

char *strcpy(char *dest, const char *src);


Example:

Copy

char src[] = "Hello";

char dest[10];

strcpy(dest, src);

printf("Copied string: %s\n", dest); // Output: Hello

3. strcat(): Concatenates two strings.

Copy

char *strcat(char *dest, const char *src);

Example:

Copy

char str1[20] = "Hello";

char str2[] = " World";

strcat(str1, str2);

printf("Concatenated string: %s\n", str1); // Output: Hello World

4. strcmp(): Compares two strings.

Copy

int strcmp(const char *str1, const char *str2);

Example:

Copy

char str1[] = "Hello";

char str2[] = "World";

if (strcmp(str1, str2) == 0)
printf("Strings are equal.\n");

else

printf("Strings are not equal.\n");

13. Define String. List Out All String Manipulation Functions. Explain Any Two with
Example

String Definition:
A string is a sequence of characters terminated by a null character (\0).

Common String Functions:

1. strlen()

2. strcpy()

3. strcat()

4. strcmp()

5. strchr()

6. strstr()

7. strrev()

Example of strlen() and strcpy():

Copy

#include <stdio.h>

#include <string.h>

int main() {

char str1[] = "Hello";

char str2[10];

printf("Length of str1: %zu\n", strlen(str1)); // Output: 5

strcpy(str2, str1);

printf("Copied string: %s\n", str2); // Output: Hello


return 0;

14. Write a C Program to Implement String Copy Operation STRCOPY(str1, str2)


Without Using Library Function

Copy

#include <stdio.h>

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

int i = 0;

while (src[i] != '\0') {

dest[i] = src[i];

i++;

dest[i] = '\0';

int main() {

char str1[] = "Hello";

char str2[10];

STRCOPY(str2, str1);

printf("Copied string: %s\n", str2); // Output: Hello

return 0;

15. Write a Program to Replace Each Constant in a String with the Next One Except
Letters 'z', 'Z', 'a', 'A'
c

Copy

#include <stdio.h>

int main() {

char str[] = "Programming in C is fun";

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

if ((str[i] >= 'b' && str[i] <= 'y') || (str[i] >= 'B' && str[i] <= 'Y')) {

str[i]++;

printf("Modified string: %s\n", str); // Output: Qsphsannjoh jo D jt gvo

return 0;

16. Write a C Program to Concatenate Two Strings Without Using Built-in


Function strcat()

Copy

#include <stdio.h>

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

int i = 0, j = 0;

while (dest[i] != '\0') i++;

while (src[j] != '\0') {

dest[i++] = src[j++];

dest[i] = '\0';

}
int main() {

char str1[20] = "Hello";

char str2[] = " World";

CONCAT(str1, str2);

printf("Concatenated string: %s\n", str1); // Output: Hello World

return 0;

17. Explain with Example (i) Character String (ii) String Literal (iii) Storage Classes

a) Character String:

A sequence of characters stored in an array.

Copy

char str[] = "Hello";

b) String Literal:

A string constant enclosed in double quotes.

Copy

printf("Hello");

c) Storage Classes:

1. auto: Default storage class for local variables.

2. static: Retains value between function calls.

3. extern: Declares a global variable.

4. register: Suggests storing in a CPU register.


18. How String is Declared and Initialized? Explain Any Four String Manipulation
Functions with Examples

Declaration and Initialization:

Copy

char str[] = "Hello";

Functions:

1. strlen()

2. strcpy()

3. strcat()

4. strcmp()

Examples:

Copy

#include <stdio.h>

#include <string.h>

int main() {

char str1[] = "Hello";

char str2[10];

printf("Length: %zu\n", strlen(str1)); // Output: 5

strcpy(str2, str1); // Copy

strcat(str1, " World"); // Concatenate

printf("Comparison: %d\n", strcmp(str1, str2)); // Compare

return 0;

}
19. Write a C Program to Check Whether the Given String is Palindrome or Not Without
Using In-Built Function

Copy

#include <stdio.h>

#include <string.h>

int main() {

char str[100];

int i, len, flag = 1;

printf("Enter a string: ");

fgets(str, sizeof(str), stdin);

len = strlen(str) - 1; // Exclude newline character

for (i = 0; i < len / 2; i++) {

if (str[i] != str[len - i - 1]) {

flag = 0;

break;

if (flag)

printf("The string is a palindrome.\n");

else

printf("The string is not a palindrome.\n");

return 0;

}
20. Write a C Program to Search a Name in a Given List Using Binary Search Technique

Copy

#include <stdio.h>

#include <string.h>

int main() {

char names[][20] = {"Alice", "Bob", "Charlie", "David", "Eve"};

int n = 5;

char key[20];

int low = 0, high = n - 1, mid, found = 0;

printf("Enter the name to search: ");

scanf("%s", key);

while (low <= high) {

mid = (low + high) / 2;

if (strcmp(names[mid], key) == 0) {

printf("Name found at index %d\n", mid);

found = 1;

break;

} else if (strcmp(names[mid], key) < 0) {

low = mid + 1;

} else {

high = mid - 1;

}
if (!found)

printf("Name not found.\n");

return 0;

MODULE 4
1. What is a Function? Explain the Difference Between User-Defined and Library Functions

Function Definition:
A function is a block of code that performs a specific task. It can take inputs, process them,
and return a result.

Difference Between User-Defined and Library Functions:

User-Defined Functions Library Functions

Created by the programmer. Predefined in C libraries.

Must be declared and defined before use. Already declared and defined in headers.

Example: int add(int a, int b) { return a + b; } Example: printf(), scanf(), strlen()

2. Explain the Different Elements of User-Defined Functions in Detail

Elements of User-Defined Functions:

1. Function Declaration (Prototype):


Specifies the function's name, return type, and parameters.

Copy

int add(int a, int b); // Declaration

2. Function Definition:
Implements the function's logic.

c
Copy

int add(int a, int b) { // Definition

return a + b;

3. Function Call:
Invokes the function to execute its code.

Copy

int result = add(5, 10); // Call

3. What is a Function? Write a Function to Find the Sum of Two Numbers

Function Definition:

Copy

#include <stdio.h>

// Function to find the sum of two numbers

int add(int a, int b) {

return a + b;

int main() {

int num1 = 5, num2 = 10;

int sum = add(num1, num2); // Function call

printf("Sum = %d\n", sum); // Output: 15

return 0;

}
4. Explain Two Categories/Types of Argument Passing Techniques, with Examples

a) Call by Value:

• A copy of the argument is passed to the function.

• Changes made to the parameter do not affect the original argument.

Example:

Copy

#include <stdio.h>

void increment(int x) {

x++;

printf("Inside function: %d\n", x); // Output: 6

int main() {

int num = 5;

increment(num); // Call by value

printf("Outside function: %d\n", num); // Output: 5

return 0;

b) Call by Reference:

• The address of the argument is passed to the function.

• Changes made to the parameter affect the original argument.

Example:

Copy

#include <stdio.h>

void increment(int *x) {

(*x)++;
printf("Inside function: %d\n", *x); // Output: 6

int main() {

int num = 5;

increment(&num); // Call by reference

printf("Outside function: %d\n", num); // Output: 6

return 0;

5. Explain the Classification of User-Defined Functions

Based on Parameters and Return Type:

1. Functions with No Arguments and No Return Value:

Copy

void greet() {

printf("Hello, World!\n");

2. Functions with Arguments and No Return Value:

Copy

void printSum(int a, int b) {

printf("Sum = %d\n", a + b);

3. Functions with No Arguments and Return Value:

Copy

int getNumber() {
return 10;

4. Functions with Arguments and Return Value:

Copy

int add(int a, int b) {

return a + b;

6. Write a C Function isprime(num) that Accepts an Integer Argument and Returns 1 if the
Argument is a Prime or 0 Otherwise. Write a Program that Invokes this Function to
Generate Prime Numbers Between the Given Ranges

Copy

#include <stdio.h>

// Function to check if a number is prime

int isprime(int num) {

if (num <= 1) return 0; // 0 and 1 are not prime

for (int i = 2; i * i <= num; i++) {

if (num % i == 0) return 0; // Not prime

return 1; // Prime

int main() {

int start, end;

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


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

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

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

if (isprime(i)) {

printf("%d ", i);

return 0;

7. Write a program in C using functions to swap two numbers using global variables and
call by reference concept.

Using Global Variables:

Copy

#include <stdio.h>

int a, b; // Global variables

void swap() {

int temp = a;

a = b;

b = temp;

int main() {

printf("Enter two numbers: ");


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

printf("Before swap: a = %d, b = %d\n", a, b);

swap();

printf("After swap: a = %d, b = %d\n", a, b);

return 0;

Using Call by Reference:

Copy

#include <stdio.h>

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

int temp = *x;

*x = *y;

*y = temp;

int main() {

int a, b;

printf("Enter two numbers: ");

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

printf("Before swap: a = %d, b = %d\n", a, b);

swap(&a, &b);

printf("After swap: a = %d, b = %d\n", a, b);

return 0;

8. What are actual parameters and formal parameters? Illustrate with an example.
• Actual Parameters: These are the values or variables passed to a function when it is
called.

• Formal Parameters: These are the variables defined in the function definition to
receive the values of the actual parameters.

Example:

Copy

#include <stdio.h>

void add(int x, int y) { // x and y are formal parameters

printf("Sum = %d\n", x + y);

int main() {

int a = 5, b = 10;

add(a, b); // a and b are actual parameters

return 0;

9. Write a C program to find the factorial of a number using functions.

Copy

#include <stdio.h>

int factorial(int n) {

int fact = 1;

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

fact *= i;

}
return fact;

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

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

return 0;

10. Write a program to find GCD and LCM of two numbers using functions.

Copy

#include <stdio.h>

int gcd(int a, int b) {

while (b != 0) {

int temp = b;

b = a % b;

a = temp;

return a;

int lcm(int a, int b) {

return (a * b) / gcd(a, b);

}
int main() {

int num1, num2;

printf("Enter two numbers: ");

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

printf("GCD = %d\n", gcd(num1, num2));

printf("LCM = %d\n", lcm(num1, num2));

return 0;

11. Give the scope and lifetime of the following:

1. External Variable: Scope is global, lifetime is the entire program execution.

2. Static Variable: Scope is local to the block, lifetime is the entire program execution.

3. Automatic Variable: Scope is local to the block, lifetime is within the block.

4. Register Variable: Scope is local to the block, lifetime is within the block (stored in
CPU registers).

12. What are the three possibilities of defining a user-defined function in C?

1. Function Declaration: Prototype declaration (e.g., int add(int, int);).

2. Function Definition: Actual implementation of the function.

3. Function Call: Invoking the function in the program.

13. What is Recursion? Write a C program to compute polynomial coefficient nCr using
recursion.

Recursion:

Recursion is a process where a function calls itself directly or indirectly.

Program to compute nCr:

Copy
#include <stdio.h>

int factorial(int n) {

if (n == 0 || n == 1) return 1;

return n * factorial(n - 1);

int nCr(int n, int r) {

return factorial(n) / (factorial(r) * factorial(n - r));

int main() {

int n, r;

printf("Enter n and r: ");

scanf("%d %d", &n, &r);

printf("nCr = %d\n", nCr(n, r));

return 0;

14. Define recursion. Write a C recursive function for multiplying two integers.

Recursive Multiplication:

Copy

#include <stdio.h>

int multiply(int m, int n) {

if (n == 0) return 0;

return m + multiply(m, n - 1);


}

int main() {

int a, b;

printf("Enter two numbers: ");

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

printf("Product = %d\n", multiply(a, b));

return 0;

15. Write a C program to check if a number is prime or not using recursion.

Copy

#include <stdio.h>

int isPrime(int n, int i) {

if (i == 1) return 1; // Base case

if (n % i == 0) return 0; // Not prime

return isPrime(n, i - 1);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (isPrime(num, num / 2))

printf("%d is prime.\n", num);

else
printf("%d is not prime.\n", num);

return 0;

16. Write a C program to find the factorial of a number using recursion.

Copy

#include <stdio.h>

int factorial(int n) {

if (n == 0 || n == 1) return 1;

return n * factorial(n - 1);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

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

return 0;

17. Explain recursion and write a program to find the nth term of the Fibonacci series.

Recursion:

Recursion is a technique where a function calls itself to solve smaller instances of the same
problem.

Fibonacci Series:

c
Copy

#include <stdio.h>

int fibonacci(int n) {

if (n <= 1) return n;

return fibonacci(n - 1) + fibonacci(n - 2);

int main() {

int n;

printf("Enter the term number: ");

scanf("%d", &n);

printf("Fibonacci term %d is %d\n", n, fibonacci(n));

return 0;

MODULE 5
1. What is a Structure? Explain the C Syntax of Structure Declaration with an Example

Structure is a user-defined data type in C that allows you to combine data items of different
kinds. Structures are used to represent a record.

Syntax:

Copy

struct structure_name {

data_type member1;

data_type member2;

...
};

Example:

Copy

#include <stdio.h>

struct Student {

int roll_no;

char name[50];

float marks;

char grade;

};

int main() {

struct Student s1;

s1.roll_no = 1;

strcpy(s1.name, "John Doe");

s1.marks = 95.5;

s1.grade = 'A';

printf("Roll No: %d\n", s1.roll_no);

printf("Name: %s\n", s1.name);

printf("Marks: %.2f\n", s1.marks);

printf("Grade: %c\n", s1.grade);

return 0;

2. Explain Array of Structure and Structure within a Structure with an Example


Array of Structure:
An array of structures is an array in which each element is a structure.

Example:

Copy

struct Student {

int roll_no;

char name[50];

float marks;

char grade;

};

struct Student students[10]; // Array of 10 students

Structure within a Structure:


A structure can contain another structure as its member.

Example:

Copy

struct Date {

int day;

int month;

int year;

};

struct Student {

int roll_no;

char name[50];

struct Date dob;

float marks;
char grade;

};

3. Write a C Program to Maintain a Record of 'n' Students' Details Using an Array of


Structures

Copy

#include <stdio.h>

#include <string.h>

struct Student {

int roll_no;

char name[50];

float marks;

char grade;

};

int main() {

int n, i;

char search_name[50];

printf("Enter the number of students: ");

scanf("%d", &n);

struct Student students[n];

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

printf("Enter details for student %d:\n", i + 1);

printf("Roll No: ");


scanf("%d", &students[i].roll_no);

printf("Name: ");

scanf("%s", students[i].name);

printf("Marks: ");

scanf("%f", &students[i].marks);

printf("Grade: ");

scanf(" %c", &students[i].grade);

printf("Enter the name of the student to search: ");

scanf("%s", search_name);

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

if (strcmp(students[i].name, search_name) == 0) {

printf("Marks of %s: %.2f\n", students[i].name, students[i].marks);

break;

if (i == n) {

printf("Student not found.\n");

return 0;

4. Write a C Program to Pass Structure Variable as Function Argument

Copy
#include <stdio.h>

struct Student {

int roll_no;

char name[50];

float marks;

char grade;

};

void printStudent(struct Student s) {

printf("Roll No: %d\n", s.roll_no);

printf("Name: %s\n", s.name);

printf("Marks: %.2f\n", s.marks);

printf("Grade: %c\n", s.grade);

int main() {

struct Student s1 = {1, "John Doe", 95.5, 'A'};

printStudent(s1);

return 0;

5. Write a C Program to Store and Print Name, USN, Subject, and IA Marks of Students
Using Structure

Copy

#include <stdio.h>

struct Student {
char name[50];

char usn[20];

char subject[50];

float ia_marks;

};

int main() {

struct Student s1 = {"John Doe", "1MS21CS001", "C Programming", 45.5};

printf("Name: %s\n", s1.name);

printf("USN: %s\n", s1.usn);

printf("Subject: %s\n", s1.subject);

printf("IA Marks: %.2f\n", s1.ia_marks);

return 0;

6. Explain the Difference Between Array and Structures

• Array:

o An array is a collection of elements of the same data type.

o Elements are accessed using an index.

o Arrays are used to store multiple values of the same type.

• Structure:

o A structure is a collection of elements of different data types.

o Elements are accessed using the dot operator (.).

o Structures are used to represent a record with multiple fields.

7. Explain with Example How to Create a Structure Using 'typedef'

typedef is used to create an alias for a data type, including structures.

Example:
c

Copy

#include <stdio.h>

typedef struct {

int roll_no;

char name[50];

float marks;

char grade;

} Student;

int main() {

Student s1 = {1, "John Doe", 95.5, 'A'};

printf("Roll No: %d\n", s1.roll_no);

printf("Name: %s\n", s1.name);

printf("Marks: %.2f\n", s1.marks);

printf("Grade: %c\n", s1.grade);

return 0;

8. Write a Program to Maintain a Record of 'n' Employee Details Using an Array of


Structures

Copy

#include <stdio.h>

struct Employee {
int id;

char name[50];

float salary;

};

int main() {

int n, i;

printf("Enter the number of employees: ");

scanf("%d", &n);

struct Employee employees[n];

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

printf("Enter details for employee %d:\n", i + 1);

printf("ID: ");

scanf("%d", &employees[i].id);

printf("Name: ");

scanf("%s", employees[i].name);

printf("Salary: ");

scanf("%f", &employees[i].salary);

printf("Employees with salary above 5000:\n");

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

if (employees[i].salary > 5000) {

printf("ID: %d, Name: %s, Salary: %.2f\n", employees[i].id, employees[i].name,


employees[i].salary);
}

return 0;

9. What is a Pointer? Explain How the Pointer Variable is Declared and Initialized

Pointer is a variable that stores the memory address of another variable.

Declaration:

Copy

data_type *pointer_name;

Initialization:

Copy

int a = 10;

int *p = &a; // p now holds the address of a

Example:

Copy

#include <stdio.h>

int main() {

int a = 10;

int *p = &a;

printf("Value of a: %d\n", a);

printf("Address of a: %p\n", &a);

printf("Value of p: %p\n", p);


printf("Value pointed by p: %d\n", *p);

return 0;

10. Explain the Array of Pointers with Example or Explain How Pointers and Arrays Are
Related with Example

Array of Pointers:
An array of pointers is an array where each element is a pointer to a variable of a specific
type. This is commonly used to store strings or dynamically allocated memory.

Example:

Copy

#include <stdio.h>

int main() {

char *names[] = {"Alice", "Bob", "Charlie", "David"}; // Array of pointers to strings

int i;

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

printf("Name %d: %s\n", i + 1, names[i]);

return 0;

Relationship Between Pointers and Arrays:


In C, arrays and pointers are closely related. The name of an array is essentially a pointer to
its first element. You can use pointer arithmetic to access array elements.

Example:

c
Copy

#include <stdio.h>

int main() {

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

int *ptr = arr; // Pointer to the first element of the array

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

printf("Element %d: %d\n", i + 1, *(ptr + i)); // Accessing array elements using pointer

return 0;

11. What is a Pointer? Write a C Program to Find the Sum and Mean of All Elements in an
Array Using Pointer

Pointer:
A pointer is a variable that stores the memory address of another variable.

Program:

Copy

#include <stdio.h>

int main() {

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

int n = sizeof(arr) / sizeof(arr[0]);

int *ptr = arr; // Pointer to the first element of the array

int sum = 0;

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

sum += *(ptr + i); // Accessing array elements using pointer

mean = (float)sum / n;

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

printf("Mean of elements: %.2f\n", mean);

return 0;

12. Write a C Program to Swap Two Numbers Using Call by Address (Pointers or Reference)
Method

Program:

Copy

#include <stdio.h>

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

int temp = *a;

*a = *b;

*b = temp;

int main() {

int x = 10, y = 20;


printf("Before swapping: x = %d, y = %d\n", x, y);

swap(&x, &y); // Passing addresses of x and y

printf("After swapping: x = %d, y = %d\n", x, y);

return 0;

13. Write a C Program Using Pointers to Compute the Sum, Mean, and Standard Deviation
of All Elements Stored in an Array of 'n' Real Numbers

Program:

Copy

#include <stdio.h>

#include <math.h>

int main() {

float arr[] = {10.5, 20.3, 30.2, 40.1, 50.4};

int n = sizeof(arr) / sizeof(arr[0]);

float *ptr = arr; // Pointer to the first element of the array

float sum = 0, mean, variance = 0, std_deviation;

// Calculate sum

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

sum += *(ptr + i);

// Calculate mean
mean = sum / n;

// Calculate variance

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

variance += pow(*(ptr + i) - mean, 2);

variance /= n;

// Calculate standard deviation

std_deviation = sqrt(variance);

printf("Sum: %.2f\n", sum);

printf("Mean: %.2f\n", mean);

printf("Standard Deviation: %.2f\n", std_deviation);

return 0;

14. What is a Pointer? Give the Advantages and Disadvantages of Pointer Data Type

Pointer:
A pointer is a variable that stores the memory address of another variable. It allows direct
access to memory locations, enabling dynamic memory allocation, efficient array handling,
and more.

Advantages of Pointers:

1. Dynamic Memory Allocation: Pointers allow programs to allocate memory


dynamically using functions like malloc, calloc, and realloc.

2. Efficient Array Handling: Pointers provide efficient access to array elements using
pointer arithmetic.

3. Function Arguments: Pointers allow functions to modify the actual arguments


passed to them (call by reference).
4. Data Structures: Pointers are essential for implementing complex data structures like
linked lists, trees, and graphs.

5. Performance: Pointers can improve performance by reducing the overhead of


copying large data structures.

Disadvantages of Pointers:

1. Complexity: Pointers can make programs harder to read and debug.

2. Memory Leaks: Improper use of pointers can lead to memory leaks if dynamically
allocated memory is not freed.

3. Dangling Pointers: Pointers can become invalid if they point to memory that has
been deallocated.

4. Security Risks: Pointers can lead to security vulnerabilities like buffer overflows if not
handled carefully.

5. Null Pointer Dereferencing: Dereferencing a null or uninitialized pointer can cause


program crashes.

Example of Pointer Usage:

Copy

#include <stdio.h>

int main() {

int a = 10;

int *p = &a; // Pointer to variable a

printf("Value of a: %d\n", a);

printf("Address of a: %p\n", &a);

printf("Value of p: %p\n", p);

printf("Value pointed by p: %d\n", *p);

return 0;

You might also like