0% found this document useful (0 votes)
26 views

KCA 102

The document provides a comprehensive overview of various programming concepts, including the differences between compilers and interpreters, rules for declaring identifiers, and the distinction between actual and formal arguments. It also covers recursion, data structures, file handling, flowcharts, switch statements, and the differences between structures and arrays, along with examples of C programs for practical understanding. Additionally, it discusses primitive data types in C, operator precedence and associativity, and includes examples of bitwise operators.

Uploaded by

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

KCA 102

The document provides a comprehensive overview of various programming concepts, including the differences between compilers and interpreters, rules for declaring identifiers, and the distinction between actual and formal arguments. It also covers recursion, data structures, file handling, flowcharts, switch statements, and the differences between structures and arrays, along with examples of C programs for practical understanding. Additionally, it discusses primitive data types in C, operator precedence and associativity, and includes examples of bitwise operators.

Uploaded by

Dolly Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Question 1: Differentiate between compiler & interpreter.

Answer: A compiler and an interpreter are both used to translate high-level programming languages
into machine code, but they work differently.

Feature Compiler Interpreter


Execution Translates the entire program at Translates and executes code line by line.
once before execution.
Speed Faster because it translates the Slower since it translates while running.
code before execution.
Error Handling Shows all errors after Stops at the first error encountered.
compilation.
Output Generates an independent Does not produce a separate executable;
executable file. runs the code directly.
Examples C, C++, Java Python, JavaScript, PHP

Question 2: Describe rules of declaring identifiers.

Answer: An identifier is the name assigned to variables, functions, classes, or other program
elements. The following rules must be followed when declaring identifiers:

Rules of Declaring Identifiers:

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


2. Can contain letters, digits (0-9), and underscores.
3. Cannot be a keyword.
4. Case-sensitive. No special characters except _.

Question 3: Differentiate between actual argument and formal argument.

Answer: Actual arguments: Passed to functions during a function call. It is defined inside the function
call. Example: sum(5,10) Here 5 and 10 are actual arguments.

Formal arguments: Defined in function headers and receive values from actual arguments. It is
defined the function definition. Example: def sum(a,b) Here a and b are actual arguments.

Question 4: Predict how long the following loop runs?

for (int x = 1; x = 3; x++)

Answer4: The loop has an incorrect condition x = 3 (assignment, not comparison). It will run
infinitely if the compiler allows it.

Question 5: Write the data structure used in implementing recursion.

Answer: The data structure used in implementing recursion is the Stack.

Why is Stack Used?

Function Call Management: Each recursive function call is pushed onto the stack.
Stores Return Addresses: Keeps track of where each function should return after execution.

Stores Local Variables: Each call has its own copy of local variables stored on the stack.

Manages Execution Order: Functions execute in a Last-In-First-Out (LIFO) manner.

Question 6: There is a two-dimensional array of type integer. Write the statement to display

the base address of the array.

Answer To display the base address of a two-dimensional integer array in C, you can use the
following statement:

printf("%p", array);

or explicitly using the address-of operator:

printf("%p", &array);

Question 7: How is a null pointer created?

Answer: A null pointer in C is created by assigning NULL to a pointer variable.

Using NULL Macro:

int *ptr = NULL;

Question 8: On successful execution of the below code predict the result, if address of

variable ‘a’ is 210?

void main( ) {

float a, *b;

b = &a;

b = b+3;

printf (“%d”, b);

Answer: b + 3 increments the address by 3 float spaces.

If a is at address 210, and assuming float size = 4 bytes, the output is 210 + (3 * 4) = 222.

Question 9: Explain the use of rectangle() functions.

Answer: The rectangle() function is commonly used in graphics programming to draw a rectangle.

Syntax: void rectangle(int left, int top, int right, int bottom);
Question 10: Though we can write our program without File handling, what is the need of file
handling in C?

Answer: We can write programs in C without file handling, it is essential when we need to store,
retrieve, and manipulate data persistently. Without file handling, all data stored in variables is lost
when the program terminates because it is stored in RAM (volatile memory).

Need for File Handling:

1. To store data persistently beyond program execution.


2. Enables reading and writing to external files.

Question 11: What is the use of a flow chart? List out the symbols used in a flow chart. Draw a
flow chart to find whether the given year is a leap year or not.

Answer: A flowchart is a graphical representation of an algorithm or a process. It helps in:

1. Understanding the logic of a program before coding.


2. Identifying errors and improving efficiency.
3. Enhancing communication among team members.

Symbols Used in a Flowchart:

Symbol Name Purpose


Oval Start/End Represents the start or end of
the flowchart.
Diamond Decision Represents a decision-making
step (Yes/No conditions).
Rectangle Process Represents a process,
computation, or action.
Parallelogram Input/Output Represents input (e.g., reading
values) or output (e.g.,
displaying results).

Arrow Flowline Shows the flow of control from


one direction to another.
Flowchart to Check Leap Year:

A leap year is divisible by 4 but not by 100, except if it is also divisible by 400.

Logic:

1. Take the year as input.


2. If (year % 400 == 0) → It’s a leap year.
3. Else if (year % 100 == 0) → Not a leap year.
4. Else if (year % 4 == 0) → It’s a leap year.
5. Otherwise, it’s not a leap year.
6. Print the result.
Question12: How switch statement is different from else – if ladder?

Construct a program in C to print the bellow pattern.

**

***

****

*****

The number of lines to print to be entered by the user.

Answer: Switch: A control flow statement called a switch statement enables a program to compare
an expression to a set of potential constant values by managing many scenarios according to the
expression's value. When handling several potential scenarios, the switch statement makes the code
easier to comprehend and maintain.

Syntax of switch Statement

switch (expression) {

case value1:

break;

case value2:

break;

default:

If else:: Conditional control structure called if-else statements are used to allow the execution of a
particular code blocks on the basis that the given condition results in true of false. By running code in
this way i.e. selectively according to whether a certain condition is true or false, we can easily make
judgements.

if (condition) {

//code

else {

//code

}
Question 13: Illustrate the concept of recursion and base condition of recursion. Construct a

recursive function to find the factorial of an input number N..

Answer: Concept of Recursion and Base Condition:

Recursion: Recursion is a technique where a function calls itself to solve a problem. It divides a large
problem into smaller subproblems and repeats the process until it reaches a stopping condition.

Base Condition in Recursion

The base condition is a terminating condition that prevents infinite recursion. Without it, the
function would continue calling itself indefinitely, causing a stack overflow.

Example: Factorial Calculation Using Recursion

Factorial Formula:

N! = N *(N-1)*(N-2)* 1

Example:5! = 5 *4 *3 *2 *1 = 120

Program:

#include <stdio.h>

// Recursive function to calculate factorial

int factorial(int n) {

if (n == 0) // Base condition

return 1;

return n * factorial(n - 1); // Recursive call

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (num < 0)
printf("Factorial is not defined for negative numbers.");

else

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

return 0;

Question 14: How a structure is different from an array? Write a C program to store employee
details such as Empid, Name, Salary and Age for 50 employees and display the employee details
who are getting salary more than 15000.

Answer: Structure: A structure is a user defined data type that groups different data types. It can
hold multiple data types. Each member of the structure is stored separately in memory. Members
are accessed using dot operator. It is used for grouping related data of different types.

Array: An array is a collection of elements of the same data type stored sequentially. It stores only
one data type (e.g. all int or all float). All elements are stored in contiguous memory locations.
Elements are accessed using indexing( [] ). It is used for storing multiple values of the same type.

C Program to Store and Display Employee Details (Salary > 15000):

#include <stdio.h>

// Defining the structure for employee

struct Employee {

int empid;

char name[50];

float salary;

int age;

};

int main() {

struct Employee emp[50]; // Array of structure to store 50 employees

int i, n;
// Input: Number of employees

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

scanf("%d", &n);

// Input employee details

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

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

printf("Emp ID: ");

scanf("%d", &emp[i].empid);

printf("Name: ");

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

printf("Salary: ");

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

printf("Age: ");

scanf("%d", &emp[i].age);

// Display employees with salary > 15000

printf("\nEmployees with salary greater than 15000:\n");

printf("EmpID\tName\t\tSalary\t\tAge\n");

printf("--------------------------------------------------\n");

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

if (emp[i].salary > 15000) {

printf("%d\t%s\t\t%.2f\t\t%d\n", emp[i].empid, emp[i].name, emp[i].salary, emp[i].age);

}
return 0;

Question 15: Develop a C program to copy the contents of one file to another file. The file name
must be pass through command line arguments.

Answer: C Program: Copy File Contents Using Command-Line Arguments

#include <stdio.h>

#include <stdlib.h>

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

FILE *source, *target;

char ch;

// Check if correct number of arguments are passed

if (argc != 3) {

printf("Usage: %s <source_file> <destination_file>\n", argv[0]);

return 1;

// Open the source file in read mode

source = fopen(argv[1], "r");

if (source == NULL) {

printf("Error: Cannot open source file %s\n", argv[1]);

return 1;

// Open the destination file in write mode

target = fopen(argv[2], "w");


if (target == NULL) {

printf("Error: Cannot open target file %s\n", argv[2]);

fclose(source);

return 1;

// Copy contents character by character

while ((ch = fgetc(source)) != EOF) {

fputc(ch, target);

// Close the files

fclose(source);

fclose(target);

printf("File copied successfully from %s to %s\n", argv[1], argv[2]);

return 0;

Question 16: Explain the different data types supported by C language? Explain primitive data
types in terms of memory size, format specifier and range.

Answer: Different Data Types in C Language : C supports various data types that define the nature of
variables. They are categorized into:

 Primitive Data Types (Basic types): Primitive data types are the most basic data types that
are used for representing simple values such as integers, float, characters, etc.
 Derived Data Types (Arrays, Pointers, Functions) : The data types that are derived from the
primitive or built-in datatypes are referred to as Derived Data Types.
 User-Defined Data Types (Structures, Unions, Enums, Typedef) : The user-defined data types
are defined by the user himself.

1. Primitive Data Types in C: Primitive data types are fundamental types that store basic values like
numbers, characters, and floating points.

Following are some main primitive data types:


i. Integer Data Type
ii. Character Data Type
iii. Float Data Type
iv. Double Data Type
v. Void Data Type
a. Integer data type: The integer datatype in C is used to store the integer numbers. Octal
values, hexadecimal values, and decimal values can be stored in int data type in C.
Range: -2,147,483,648 to 2,147,483,647
Size: 4 bytes
Format Specifier: %d
b. Character data type: Character data type allows its variable to store only a single character.
Range: (-128 to 127) or (0 to 255)
Size: 1 byte
Format Specifier: %c
c. Float Data Type: In C programming, float data type is used to store floating point values.
Float in C is used to store decimal and exponential values.
Range: 1.2E-38 to 3.4E+38
Size: 4 bytes
Format Specifier: %f
d. Double Data Type: A Double data type in C is used to store decimal numbers (numbers with
floating point values) with double precision. It is used to define numeric values which hold
numbers with decimal values in C. Since double has more precision as compared to that float
then it is much more obvious that it occupies twice the memory occupied by the floating-
point type.
Range: 1.7E-308 to 1.7E+308
Size: 8 bytes
Format Specifier: %lf
e. Void Data Type: The void data type in C is used to specify that no value is present. It does not
provide a result value to its caller. It has no values and no operations.

Question 17: What do you mean by operator precedence and associativity? Explain all bitwise
AND, bit-wise OR and bit-wise XOR operators with suitable example.

Answer: Operator Precedence and Associativity in C: Operator precedence determines the order in
which operators are evaluated in an expression. Operators with higher precedence are evaluated
before those with lower precedence.

Example:

int result = 10 + 5 * 2;

printf("%d", result);

* (Multiplication) has higher precedence than +, so 5 * 2 is evaluated first.

result = 10 + 10 → Output: 20*


Operator Associativity: Associativity defines the direction in which operators of equal precedence
are evaluated. Most operators have left-to-right associativity, while some (e.g., assignment `=`) have
right-to-left associativity.

Example:

int x = 5, y = 3, z;

z = x - y + 2;

- and + have the same precedence and left-to-right associativity. So, x - y is evaluated first, then the
result is added to 2.

Bitwise Operators in C: C provides bitwise operators to manipulate individual bits of numbers.

Operator Name Symbol Function


AND Bitwise AND & Set bits to 1 if both bits
are 1.
OR Bitwise OR | The result of OR is 1 if
any of the two bits is 1.
XOR Bitwise XOR ^ The result of XOR is 1 if
the two bits are
different.

Example of Bitwise AND operator:

#include <stdio.h>

int main() {

int a = 5, b = 3; // Binary: a = 0101, b = 0011

int result = a & b;

printf("Bitwise AND: %d\n", result); // Output: 1 (0001)

return 0;

Example of bitwise operator:

#include <stdio.h>

int main() {

int a = 5, b = 3; // Binary: a = 0101, b = 0011

int result = a | b;

printf("Bitwise OR: %d\n", result); // Output: 7 (0111)


return 0;

Example of bitwise XOR:

#include <stdio.h>

int main() {

int a = 5, b = 3; // Binary: a = 0101, b = 0011

int result = a ^ b;

printf("Bitwise XOR: %d\n", result); // Output: 6 (0110)

return 0;

Question 18: Write a program to check the input number is an Armstrong number or not. 1

Answer: C Program to Check if a Number is an Armstrong Number:

An Armstrong number (also known as a narcissistic number) is a number in which the sum of its
digits raised to the power of the number of digits is equal to the original number.

Formula: For a 3-digit number `xyz`, it is an Armstrong number if:

xyz = x3 + y3 + z3

Example: 153 is an Armstrong number because:

13 + 53 + 33 = 1 + 125 + 27 = 153

C Program Implementation

#include <stdio.h>

#include <math.h>

int isArmstrong(int num) {

int originalNum, remainder, result = 0, digits = 0;

originalNum = num;

// Count the number of digits

int temp = num;

while (temp != 0) {
temp /= 10;

digits++;

// Calculate sum of digits raised to the power of digits

temp = num;

while (temp != 0) {

remainder = temp % 10;

result += pow(remainder, digits);

temp /= 10;

// Check if sum is equal to original number

return (result == originalNum);

int main() {

int num;

printf("Enter a number: ");

scanf("%d", &num);

if (isArmstrong(num))

printf("%d is an Armstrong number.\n", num);

else

printf("%d is not an Armstrong number.\n", num);

return 0;
}

Question 19: Identify the use of modular programming? Write a program by using user define
function to check given number is prime or not. Porotype of function should be like this int
is_prime(int).

Answer: Modular Programming in C: Modular programming is a technique in which a program is


divided into smaller, independent functions (modules). Each function performs a specific task,
making the code easy to understand, debug, and maintain.

Advantages of Modular Programming*

✔ Code Reusability – Functions can be used multiple times.

✔ Readability & Maintainability – Easy to read and modify.

✔ Error Isolation – Easier to debug issues in small functions.

✔ Team Collaboration – Different modules can be worked on separately.

C Program to Check if a Number is Prime (Using Modular Approach)

Function Prototype

int is_prime(int);

C Program Implementation

#include <stdio.h>

// Function to check if a number is prime

int is_prime(int num) {

if (num < 2) return 0; // Numbers less than 2 are not prime

for (int i = 2; i * i <= num; i++) { // Loop from 2 to sqrt(num)

if (num % i == 0)

return 0; // Not a prime number

return 1; // Prime number

int main() {
int num;

printf("Enter a number: ");

scanf("%d", &num);

if (is_prime(num))

printf("%d is a Prime number.\n", num);

else

printf("%d is NOT a Prime number.\n", num);

return 0;

Question 20: Illustrate the different ways to initialize a string during compile time as well as during
run time. Write a program to count the number of words and number of characters in an input
string.

Answer: Ways to Initialize a String in C: A string in C is a character array terminated by a null


character (\0).

1. Compile-Time Initialization (Hardcoded): Strings can be initialized during compilation in different


ways.

Method 1: Using Character Array

char str1[] = {'H', 'e', 'l', 'l', 'o', '\\0'}; // Explicit null termination

Method 2: Using Double Quotes (Recommended)

char str2[] = "Hello"; // Implicit null termination

Method 3: Using Pointer to String

char *str3 = "Hello"; // Stored in read-only memory

2. Run-Time Initialization (User Input): Strings can also be initialized at run-time using scanf() or
gets().

Method 1: Using scanf() (Single Word)

char str[100];
scanf("%s", str); // Takes input but stops at space

#Method 2: Using gets() (Multiple Words):

char str[100];

gets(str); // Reads the whole line

Method 3: Using fgets() (Safe Method)

char str[100];

fgets(str, 100, stdin); // Reads a full line safely

C Program to Count Words and Characters in a String

#include <stdio.h>

#include <string.h>

#include <ctype.h>

// Function to count words and characters in a string

void countWordsAndCharacters(char str[], int *wordCount, int *charCount) {

int i = 0;

*wordCount = 0;

*charCount = 0;

int inWord = 0;

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

if (!isspace(str[i])) { // Count non-space characters

(*charCount)++;

if (!inWord) {

(*wordCount)++;

inWord = 1;

} else {
inWord = 0;

i++;

int main() {

char str[200];

int words, characters;

// Taking string input from user

printf("Enter a string: ");

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

// Removing newline character if present

str[strcspn(str, "\\n")] = 0;

// Calling function to count words and characters

countWordsAndCharacters(str, &words, &characters);

// Displaying results

printf("Number of Words: %d\\n", words);

printf("Number of Characters (excluding spaces): %d\\n", characters);

return 0;

Question 21: Define a pointer. How do you declare and initialize a pointer? Write a program to add
the contents of an integer array using pointer.

Answer: A pointer in C is a variable that stores the memory address of another variable.
Pointers allow efficient memory access and manipulation.

Declaring and Initializing a Pointer

1. Declaration of a Pointer

data_type *pointer_name;

The asterisk (*) denotes a pointer.

2. Pointer Initialization

int a = 10;

int *ptr = &a; // Pointer stores the address of `a`

&a gives the address of a, which is stored in ptr.

C Program to Add the Contents of an Integer Array Using Pointer:

#include <stdio.h>

// Function to calculate sum using pointers

int sumArray(int *arr, int size) {

int sum = 0;

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

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

return sum;

int main() {

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

int size = sizeof(arr) / sizeof(arr[0]); // Calculate array size

int total = sumArray(arr, size); // Call function

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


return 0;

Question 22: Define scope, visibility, and lifetime of a variable. Explain in detail about all storage
classes supported in C language with reference to scope and lifetime, visibility, and default value.

Answer: Variables in C have three important characteristics:

1. Scope – Determines where a variable can be accessed in a program.

2. Visibility – Defines which parts of the program can use the variable.

3. Lifetime – Defines how long a variable remains in memory.

Storage Classes in C: C provides four storage classes that determine a variable’s scope, visibility,
lifetime, and default value.

1. Automatic (`auto`) Storage Class:

Scope: Local to the function/block.

Visibility: Only within the function/block where declared.

Lifetime: Exists until the function exits.

Default Value: Garbage value (uninitialized memory).

Example

#include <stdio.h>

void func() {

auto int x = 10; // Auto variable

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

int main() {

func();

// printf("%d", x); // Error: x is not accessible here

return 0;

}
2. Register (`register`) Storage Class:

Scope: Local to the function/block.

Visibility: Only within the function/block.

Lifetime: Exists until the function exits.

Default Value: Garbage value.

It is Stored in CPU registers instead of RAM for faster access.

Example

#include <stdio.h>

void func() {

register int x = 5; // Stored in CPU register

printf("Register variable x = %d\n", x);

int main() {

func();

return 0;

Output:

Register variable x = 5

3. Static (`static`) Storage Class

Scope: Local (if declared inside function) or Global.

Visibility: Only within the function (if local) or entire file (if global).

Lifetime: Exists throughout the program execution.

Default Value: Zero (0) if not initialized.

Special Feature: Retains its value across function calls.


Example: Static Variable in a Function

#include <stdio.h>

void counter() {

static int count = 0; // Retains value between calls

count++;

printf("Count = %d\n", count);

int main() {

counter();

counter();

counter();

return 0;

Output:

Count = 1

Count = 2

Count = 3

4. External (`extern`) Storage Class

Scope: Global.

Visibility: Available across multiple files.

Lifetime: Entire program execution.

Default Value: Zero (0) if not initialized.

Special Feature: Declared in one file but used in multiple files.

Example: Extern Variable Across Files

File 1: `file1.c`
#include <stdio.h>

int count = 10; // Global variable

void display() {

printf("Count = %d\n", count);

File 2: `file2.c`

#include <stdio.h>

extern int count; // Use external variable from file1.c

int main() {

printf("Extern Count = %d\n", count);

return 0;

Question 23: How a structure is different from union? Discuss the concept of nested structure.
Write a program for your illustration.

Answer: Structure: From above structure question

Union: It allocates memory equal to the largest number. It uses less memory but only one member
holds a value at a time. It is used when only one member is needed at a time.

Example of Structure vs. Union:

#include <stdio.h>

struct Employee {

int id;

float salary;

};
union Student {

int roll;

float marks;

};

int main() {

struct Employee emp = {101, 50000.5};

union Student stu;

stu.roll = 10; // Assigning to roll

printf("Student Roll: %d\n", stu.roll);

stu.marks = 90.5; // Assigning to marks (overwrites roll)

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

printf("Employee ID: %d, Salary: %.2f\n", emp.id, emp.salary);

return 0;

Output:

Student Roll: 10

Student Marks: 90.50

Employee ID: 101, Salary: 50000.50

Nested Structure in C: A nested structure is a structure inside another structure. It is used to


organize comples data. Its inner structure acts as a member of the outer structure.

C Program Demonstrating Nested Structure

#include <stdio.h>
// Defining a nested structure

struct Address {

char city[30];

char state[30];

int pin;

};

// Outer structure containing an Address structure

struct Employee {

int id;

char name[50];

float salary;

struct Address address; // Nested structure

};

int main() {

struct Employee emp;

// Input Employee Details

printf("Enter Employee ID: ");

scanf("%d", &emp.id);

printf("Enter Employee Name: ");

scanf("%s", emp.name);

printf("Enter Employee Salary: ");

scanf("%f", &emp.salary);

printf("Enter City: ");


scanf("%s", emp.address.city);

printf("Enter State: ");

scanf("%s", emp.address.state);

printf("Enter PIN Code: ");

scanf("%d", &emp.address.pin);

// Displaying Employee Details

printf("\nEmployee Details:\n");

printf("ID: %d\nName: %s\nSalary: %.2f\n", emp.id, emp.name, emp.salary);

printf("Address: %s, %s - %d\n", emp.address.city, emp.address.state, emp.address.pin);

return 0;

Example Output:

Enter Employee ID: 101

Enter Employee Name: John

Enter Employee Salary: 55000

Enter City: NewYork

Enter State: NY

Enter PIN Code: 10001

Employee Details:

ID: 101

Name: John

Salary: 55000.00

Address: NewYork, NY - 10001

Question 24: What are the drawbacks of static memory allocation? Write a program to allocate
space dynamically to store N numbers. Find the sum and average of these numbers.
Answer: Static memory allocation means allocating memory at compile-time using arrays. However,
it has several limitations:

Drawbacks of Static Memory Allocation in C:

1. Fixed Size – Memory is allocated before execution, so the size cannot change dynamically.

2. Memory Waste – If the allocated memory is more than required, it results in wasted space.

3. Memory Shortage – If the allocated memory is less than required, it cannot be extended**.

4. Stack Overflow Risk– Large static arrays may cause stack overflow for big programs.

5. Limited Flexibility – Cannot free or reallocate memory dynamically.

Dynamic Memory Allocation in C

Dynamic memory allocation overcomes these issues by using heap memory via:

- `malloc()` – Allocates memory but does not initialize it.

- `calloc()` – Allocates and initializes memory to zero.

- `realloc()` – Resizes previously allocated memory.

- `free()` – Deallocates memory.

C Program for Dynamic Memory Allocation:

#include <stdio.h>

#include <stdlib.h> // Required for malloc() and free()

int main() {

int *arr;

int n, i;

float sum = 0, avg;

// Taking input for number of elements

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

scanf("%d", &n);

// Dynamic memory allocation using malloc


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

// Checking if memory allocation was successful

if (arr == NULL) {

printf("Memory allocation failed!\n");

return 1; // Exit the program

// Taking input for array elements

printf("Enter %d numbers: ", n);

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

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

sum += arr[i]; // Calculate sum

// Calculate average

avg = sum / n;

// Display results

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

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

// Free allocated memory

free(arr);

return 0;

}
Example Output:

Enter the number of elements: 5

Enter 5 numbers: 10 20 30 40 50

Sum = 150.00

Average = 30.00

Question 25: What is the use of initgraph() function? Write a program to display 50 concentric
circles.

Answer: Use of `initgraph()` Function in C Graphics: The initgraph() function is used in C graphics
programming (Turbo C/C++ or Borland Graphics Interface). It initializes the graphics system by
loading the graphics driver.

Syntax

void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);

Parameters:

1. graphdriver – Specifies the graphics driver (e.g., `DETECT` for auto-detection).

2. graphmode – Sets the graphics mode (`getmaxx()` and `getmaxy()` return screen dimensions).

3. pathtodriver – The path where BGI graphics driver files are stored (`""` if in the same directory).

Example of initgraph()

#include <graphics.h>

#include <conio.h>

int main() {

int gd = DETECT, gm;

initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

circle(200, 200, 50); // Draw a circle at (200,200) with radius 50

getch(); // Wait for user input

closegraph(); // Close graphics mode

return 0;
}

C Program to Display 50 Concentric Circles:

#include <graphics.h>

#include <conio.h>

int main() {

int gd = DETECT, gm, i;

// Initialize graphics mode

initgraph(&gd, &gm, "C:\\Turboc3\\BGI");

// Center of the circles

int x = getmaxx() / 2; // Center X

int y = getmaxy() / 2; // Center Y

// Draw 50 concentric circles

for (i = 10; i <= 500; i += 10) {

circle(x, y, i); // Draw circles increasing in radius

getch(); // Wait for user input

closegraph(); // Close graphics mode

return 0;

Expected Output

A **series of 50 concentric circles**, centered on the screen, increasing in size.

Question 26: Explain the features of C.


Answer: The most important feature of C:

1. It is simple and efficient.


2. Execution is very fast.
3. It Supports modular programming
4. It has very Rich library support
5. It Supports pointers and memory management
6. It is Portable and widely used.

Question 27: Explain the types of constant used in C.

Answer: Types of Constants in C: In C programming, constants are fixed values that do not change
during program execution. Constants can be categorized into the following types:

1. Integer Constants: It represent whole numbers (positive, negative, or zero). It cannot have a
decimal point.

2. Floating-Point Constants: It represent real numbers with fractional values.

3. Character Constants: A single character enclosed in single quotes (` `).

4. String Constants: A sequence of characters enclosed in double quotes (" "). It always ends with a
null character (\0).

5. Enumeration Constants (`enum`): It defines a set of named integer constants. It improves


readability and maintainability.

enum Days {SUNDAY, MONDAY, TUESDAY};

enum Days today = MONDAY; // MONDAY = 1

Question 28: Explain the advantages of recursion.

Answer: Advantages of Recursion:

 Simplifies code for problems like factorial and Fibonacci.


 Reduces the need for loops.
 Uses function stack efficiently

Question 29: Explain formatted I/O functions.

Answer: Formatted Input/Output (I/O) functions in C allow structured input and output operations
with specific formatting rules. These functions are primarily:

i. printf() - For formatted output.


ii. scanf() - For formatted input.

printf() - Formatted Output Function: It is used to display output with format specifiers.

Syntax: printf(“ “);


Common Format Specifiers:

Forma Description Example Output


t
%d Integer Printf(“%d”,10); = 10
%f Float Printf(“%f”, 12.5) = 12.5
%c Character Printf(“%c”, ‘A’) = A
%s String Printf(“%s”, “Hello”) = Hello

scanf() – Formatted Input Function: It is Used to read input from the user with format specifiers.

Syntax: scanf(“format”, &variable);

Question 30: Explain how the pointer variable declared and initialized.

Answer: A pointer in C is a variable that stores the memory address of another variable.

1. Declaring a pointer: The Asterisk(*) symbol is used to declare a pointer.


Syntax: data_type *pointer_name;
e.g. int *ptr; // Declares a pointer to an integer

2. Intializing a pointer: A pointer is initialized by storing the address of a variable using the
address-of (&) operator.

e.g. int x = 10; // Integer variable

int *ptr = &x; // Pointer stores address of x

Question 31: Specify the use of Enumerated data type.

Answer: An Enumerated Data Type (enum) in C is used to assign meaningful names to integral
constants. It improves code readability and maintainability by allowing programmers to use
symbolic names instead of numbers.

Declaring and Syntax:

enum EnumName {constant1, constant2, constant3, ...};

e,g, enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};

Question 32: Explain the fseek() function.

Answer: The fseek() function in C is used to move the file pointer to a specific position in a file. It
allows random access to file contents, meaning you can read or write at any position instead of
sequentially processing the file.

Syntax:

int fseek(FILE *file, long offset, int origin);

Parameters:
file → Pointer to the file (FILE *).

offset → Number of bytes to move (positive or negative).

origin → Specifies the position from where the movement starts.

Question 33: How a high level programming language is useful for a systematic development
ofprograms? Explain.

Answer: High-level programming languages (e.g., C, Python, Java) provide structured, efficient, and
readable ways to develop programs systematically. They abstract low-level hardware details,
making programming easier and more productive.

Advantages of High-Level Programming Languages for Systematic Development:

1. Code Readability and Maintainability: High-level languages use human-readable syntax (if, for,
while), making programs easier to write, read, and debug.

2. Structured and Modular Programming: It supports functions and modular programming, making
large programs easier to manage.

3. Platform Independence and Portability: High-level languages are not dependent on a specific
machine. A C program written on Windows can be compiled and run on Linux/Mac with minimal
modifications.

4. Easier Debugging and Error Handling: High-level languages provide error messages and debugging
tools, making development faster.

5. Faster Development Time: High-level languages reduce manual memory management (e.g.,
Python manages memory automatically). Built-in libraries and functions simplify complex tasks.

Question 34: Explain the difference between for, while and do-while loops.

Answer: A For loop is used when the number of iterations is known. A While loop runs as long as a
condition is true. A Do-While loop runs at least once and then continues if a condition is true.

For loop: The for loop is used when you know in advance how many times you want to execute the
block of code. It iterates over a sequence (e.g., a list, tuple, string, or range) and executes the block
of code for each item in the sequence.

Syntax: for (initialization; condition; increment/decrement) {

// Code to be executed repeatedly

While loop: The while loop is used when you don’t know in advance how many times you want to
execute the block of code. It continues to execute as long as the specified condition is true.

Syntax: while (condition){

# Code to be executed while the condition is true


}

Do while loop: The do-while loop is similar to the while loop, but with one key difference: it
guarantees that the block of code will execute at least once before checking the condition.

Syntax:

do {

// body of do-while loop

} while (condition);

Question 35: Write a program to concatenate two strings without using standard library function.

Answer: Program

#include <stdio.h>

// Function to concatenate two strings

void concatenate(char str1[], char str2[]) {

int i = 0, j = 0;

// Move to the end of the first string

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

i++;

// Append second string to first string

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

str1[i] = str2[j];

i++;

j++;

// Null-terminate the concatenated string


str1[i] = '\0';

int main() {

char str1[100], str2[50]; // Sufficient space to store concatenated result

// Taking input for both strings

printf("Enter first string: ");

gets(str1); // Using gets() for full-line input

printf("Enter second string: ");

gets(str2);

// Concatenating the strings

concatenate(str1, str2);

// Displaying the result

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

return 0;

Question 36: Explain the local and external variables. Explain different storage classes used in C.

Answer: Local Variables

 Declared inside a function or a block.

 Accessible only within that function/block.

 Memory is allocated when the function is called and deallocated when it returns.

 Cannot be accessed outside the function where they are declared.

e.g.
#include <stdio.h>

void func() {

int x = 10; // Local variable

printf("Value of x inside function: %d\n", x);

int main() {

func();

// printf("%d", x); // Error: x is not accessible here

return 0;

External Variables

 Declared outside any function (globally).

 Accessible from any function in the same or other files (using extern).

 Memory is allocated when the program starts and remains allocated until the program
terminates.

e.g.,

#include <stdio.h>

int x = 100; // External (global) variable

void func() {

printf("Value of x inside function: %d\n", x);

int main() {

func();
printf("Value of x in main: %d\n", x);

return 0;

Question 37: Explain the following graphics functions supported by C language:

(i) initgraph()

(ii) rectangle()

(iii) line()

Answer: The line() function is commonly used in graphics programming to draw a straight line
between two points

Syntax: void line(int x1, int y1, int x2, int y2);

Parameters:

 x1, y1: Starting point of the line.

 x2, y2: Ending point of the line.

e.g,

#include <graphics.h>

#include <conio.h>

int main() {

int gd = DETECT, gm;

initgraph(&gd, &gm, "");

line(50, 50, 200, 200); // Draws a diagonal line

getch();

closegraph();

return 0;

Question 38: Define an Algorithm. Write the characteristics of a good algorithm.


Answer: An algorithm is a finite set of well-defined instructions used to solve a problem or perform
a specific task. It takes input, processes it using logical steps, and produces an output.

A well-designed algorithm should have the following characteristics:

1. Well-Defined Inputs and Outputs

o The algorithm should clearly specify the input values it requires.

o It must also define what output it will produce.

Example:

o Input: Two numbers, a = 5 and b = 3

o Output: Their sum, 8

2. Finiteness

o The algorithm must terminate after a finite number of steps.

o It should not enter an infinite loop.

3. Definiteness (Unambiguous Instructions)

o Each step must be clearly defined and unambiguous.

o There should be no confusion about what each step does.

Bad Example:

o "Check if the number is small." (What does "small" mean?)

Good Example:

o "Check if the number is less than 10."

4. Effectiveness (Practical and Feasible)

o The steps should be simple enough to be executed in a reasonable time.

o The algorithm should not use unnecessary or impractical operations.

Question 39: Explain the following with proper example:

(i) break

(ii) continue

(iii) goto
Answer: (i) break: The break statement is used to terminate the loop or statement in which it is
present. After that, the control will pass to the statements that are present after the break
statement, if available.

e.g, #include <stdio.h>

int main() {

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

if (i == 3) {

break; // Exits the loop when i equals 3

printf("%d ", i);

return 0;

(ii) continue: continue statement used to skip over the execution part of the loop on a certain
condition. After that, it transfers the control to the beginning of the loop. It skips its following
statements and continues with the next iteration of the loop.

e.g,

#include <stdio.h>

int main() {

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

if (i == 3) {

continue; // Skips the iteration when i equals 3

printf("%d ", i);

return 0;

}
(iii) goto: Goto statement is used to transfer control to the labeled statement. The label is the valid
identifier and is placed just before the statement from where the control is transferred.

e.g,

#include <stdio.h>

int main() {

int x = 1;

if (x == 1) {

goto skip; // Jumps to the "skip" label

printf("This will not be printed.\n");

skip:

printf("Jumped to the label!\n");

return 0;

Question 40: Write a program to accept elements of an array from user and sort and display them
in ascending order.

Answer: Program:

#include <stdio.h>

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

int temp;

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

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


if (arr[j] > arr[j + 1]) { // Swap if the element is greater than next

temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

int main() {

int n;

// Taking input for array size

printf("Enter number of elements: ");

scanf("%d", &n);

int arr[n];

// Taking array elements from user

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

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

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

// Sorting the array

bubbleSort(arr, n);
// Displaying the sorted array

printf("Sorted array in ascending order:\n");

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

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

return 0;

Question 41: Explain the following functions of dynamic memory allocation:

(i) malloc()

(ii) calloc()

(iii) realloc()

(iv) free()

Answer: Dynamic memory allocation allows programs to allocate memory at runtime using the
heap. The following functions from <stdlib.h> are used for dynamic memory management:

(i) malloc():The “malloc” or “memory allocation” method in C is used to dynamically


allocate a single large block of memory with the specified size. It returns a pointer of
type void which can be cast into a pointer of any form. It doesn’t Initialize memory at
execution time so that it has initialized each block with the default garbage value
initially.
ptr = (cast-type*) malloc(byte-size)
For Example:
(ii) Calloc(): “calloc” or “contiguous allocation” method in C is used to dynamically allocate
the specified number of blocks of memory of the specified type.
For example:
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
(iii) realloc(): “realloc” or “re-allocation” method in C is used to dynamically change the
memory allocation of a previously allocated memory. In other words, if the memory
previously allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory.
Syntax: ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
(iv) free():“free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence
the free() method is used, whenever the dynamic memory allocation takes place. It
helps to reduce wastage of memory by freeing it.
Syntax:
free(ptr);

Question 42: Discuss about the following operators in C language with example.

(i) Bitwise operators

(ii) Increment and decrement operators

(iii) Logical operators

Answer: (ii) Increment Operator: These operators increase or decrease the value of a variable by 1.

Types of Increment/Decrement Operators

Operator Name Example Effect

++x Pre-increment int y = ++x; First increases x, then assigns to y.

x++ Post-increment int y = x++; First assigns x to y, then increases x.

--x Pre-decrement int y = --x; First decreases x, then assigns to y.

x-- Post-decrement int y = x--; First assigns x to y, then decreases x.

e.g,

#include <stdio.h>

int main() {

int x = 5, y;

y = ++x; // Pre-increment: x is now 6, y is assigned 6

printf("Pre-increment: x = %d, y = %d\n", x, y);

x = 5; // Reset x

y = x++; // Post-increment: y is assigned 5, then x becomes 6

printf("Post-increment: x = %d, y = %d\n", x, y);


x = 5; // Reset x

y = --x; // Pre-decrement: x is now 4, y is assigned 4

printf("Pre-decrement: x = %d, y = %d\n", x, y);

x = 5; // Reset x

y = x--; // Post-decrement: y is assigned 5, then x becomes 4

printf("Post-decrement: x = %d, y = %d\n", x, y);

return 0;

(iii) Logical Operator: Logical operators are used for Boolean (true/false) operations, mainly in
conditional statements.

Logical Operators in C

Operator Name Example (a=5, b=3) Result

&& AND (a > 0) && (b > 0) 1 (true)

` ` OR

! NOT !(a > 0) 0 (false)

e.g,

#include <stdio.h>

int main() {

int a = 5, b = -3;

printf("(a > 0) && (b > 0) = %d\n", (a > 0) && (b > 0)); // AND

printf("(a > 0) || (b > 0) = %d\n", (a > 0) || (b > 0)); // OR

printf("!(a > 0) = %d\n", !(a > 0)); // NOT

return 0;
}

Question 43: What is type conversion? Explain two types of conversion with suitable examples.

Answer: Type conversion is the process of converting a variable from one data type to another in C.
It happens in two ways:

1. Implicit Type Conversion (Automatic Type Conversion)

2. Explicit Type Conversion (Type Casting)

1. Implicit Type Conversion (Automatic Type Conversion)

Also known as type promotion, implicit conversion occurs automatically when:

 A smaller data type is converted into a larger data type.

 Data is promoted during arithmetic operations.

Rules of Implicit Type Conversion:

 Lower to higher data type conversion occurs automatically.

 Integer values can be promoted to float, double, etc.

 char → int → float → double (Promotion order).

e.g.

#include <stdio.h>

int main() {

int a = 5;

float b = 2.5;

float result = a + b; // 'a' (int) is converted to float automatically

printf("Result: %f\n", result);

return 0;

Explicit Type Conversion (Type Casting)

Also known as type casting, explicit conversion is forced by the programmer using the cast operator
((type)).
Syntax:

(type) expression;

e.g.

#include <stdio.h>

int main() {

int a = 10, b = 3;

float result;

result = (float)a / b; // Type casting 'a' to float

printf("Result: %f\n", result);

return 0;

Question 44: How to declare and initialize a Two-dimensional array? Discuss with examples.

Answer: A two-dimensional (2D) array is an array of arrays. It represents data in rows and columns,
like a table.

1. Declaring a 2D Array

Syntax:

data_type array_name[rows][columns];

data_type → Type of elements (int, float, char, etc.).

rows → Number of rows.

columns → Number of columns.

e.g.

int matrix[3][3]; // Declares a 3x3 integer array

A 2D array can be initialized in multiple ways:

(A) Compile-time Initialization

We assign values during declaration


Method 1: Row-wise Initialization

int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

 First row: {1, 2, 3}

 Second row: {4, 5, 6}

Method 2: Without Braces

int matrix[2][3] = {1, 2, 3, 4, 5, 6};

Run-time Initialization (User Input)

We take user input using loops.

Example: Taking Input and Displaying a 2D Array

e.g.

#include <stdio.h>

int main() {

int matrix[2][3];

// Taking input

printf("Enter 6 elements for a 2x3 matrix:\n");

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

for (int j = 0; j < 3; j++) { // Columns

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

// Displaying the matrix

printf("Matrix:\n");

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

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


printf("%d ", matrix[i][j]);

printf("\n"); // New line after each row

return 0;

Question 45: Explain the following:

(i) Nested structures

(ii) Array of structures

Answer: (ii) Array of structure: An array of structures stores multiple structure variables of the same
type in an array.

Syntax:

struct StructName arrayName[size];

e.g.,

#include <stdio.h>

struct Student {

char name[20];

int roll_no;

float marks;

};

int main() {

struct Student students[3] = {

{"Alice", 101, 88.5},

{"Bob", 102, 76.0},

{"Charlie", 103, 92.0}


};

// Displaying student details

printf("Student Details:\n");

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

printf("Name: %s, Roll No: %d, Marks: %.2f\n",

students[i].name, students[i].roll_no, students[i].marks);

return 0;

Output:

Student Details:

Name: Alice, Roll No: 101, Marks: 88.50

Name: Bob, Roll No: 102, Marks: 76.00

Name: Charlie, Roll No: 103, Marks: 92.00

Question 46: Explain different categories of pre-processor directives used in C.

Answer: Preprocessor directives in C start with # and are processed before compilation. They are
used to include files, define macros, and control compilation flow.

Categories of Preprocessor Directives

There are four main categories of preprocessor directives:

1. Macro Definition (#define)

2. File Inclusion (#include)

3. Conditional Compilation (#ifdef, #ifndef, #if, #else, #endif)

4. Other Directives (#pragma, #undef)

Macro Definition (#define)

 Used to define constants or macros.


 Replaces occurrences of a name with a value before compilation.
e.g.,

#include <stdio.h>

#define PI 3.14159 // Defining a constant

int main() {

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

return 0;

File Inclusion (#include)

 Used to include header files.


 Two types:
1. Standard Library Headers (#include <stdio.h>)
2. User-defined Headers (#include "myfile.h")

e.g.

#include <stdio.h>

int main() {

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

return 0;

Conditional Compilation (#ifdef, #ifndef, #if, #else, #endif)

 Used to compile specific code based on conditions.


 Useful for platform-specific or debug code.

#include <stdio.h>
#define DEBUG // Define DEBUG mode

int main() {

#ifdef DEBUG

printf("Debug mode enabled\n");

#else

printf("Normal mode\n");

#endif

return 0;

Question 47: How keywords are different from identifiers?

Answer: Keywords: Keywords are reserved words in C that have a predefined meaning and cannot
be used as variable names. They are used for programming constructs such as loops, conditions, and
data types. Some of the keywords are int, float, char, etc.

Identifiers: Identifiers are user-defined names for variables, functions, arrays, structures, etc. They
must be unique and follow naming rules.

Question 48: Determine the value of the following logical expression if a = 5, b = 10

i. a>b && a < b


ii. a>b && a > b

Answer: Logical Operators Used:

1. && (Logical AND)

o Returns true (1) if both conditions are true.

o Returns false (0) if any one condition is false.

Expression 1: a > b && a < b

Step-by-step evaluation:

a > b && a < b

5 > 10 && 5 < 10

false (0) && true (1)


 Since one condition is false (a > b is false),

 Logical AND (&&) results in false (0).

Final Value: 0

Expression 2: a > b && a > b

Step-by-step evaluation:

a > b && a > b

5 > 10 && 5 > 10

false (0) && false (0)

 Since both conditions are false,

 Logical AND (&&) results in false (0).

Final Value: 0

Question 49: What will be the output of the following code?

void main()

int a, b *p;

a = 10;

p=&a; b = *p +20

printf(“%d”, b);

Answer: Errors in the Code

1. Incorrect Pointer Declaration:

int a, b *p;

o Here, b is declared as an int, but p is meant to be a pointer.

o Correction:

int a, *p, b;

 Now, p is correctly declared as a pointer.

2. Missing ; after b = *p + 20
b = *p + 20

o Correction:

b = *p + 20;

3. Wrong Double Quotes in printf()

printf(“%d”, b);

o The double quotes are not standard ASCII.

o Correction:

printf("%d", b);

Corrected code:

#include <stdio.h>

int main() // Use 'int main()' instead of 'void main()'

int a, *p, b; // Corrected pointer declaration

a = 10;

p = &a; // Pointer stores address of 'a'

b = *p + 20; // Dereferencing pointer 'p' to get value of 'a'

printf("%d", b); // Output 'b'

return 0; // Return 0 for proper program termination

Output: 30

Question 50: An array is declared as int a [100]; If the base address of the array is 5000, what will
be the address of a[59]. ( Consider 16 bit machine architecture)

Answer: Finding the Address of a[59] in an Array

Given Information:

 Array declaration:
c

CopyEdit

int a[100];

 Base address = 5000

 Machine architecture = 16-bit

 Size of an int in a 16-bit system = 2 bytes

 We need to find the address of a[59].

Formula for Address Calculation

Address of a[i]=Base Address+(i×Size of data type)\text{Address of } a[i] = \text{Base Address} + (i \


times \text{Size of data type})Address of a[i]=Base Address+(i×Size of data type)

where:

 i = Index of the element (59 in this case).

 Size of int = 2 bytes.

 Base Address = 5000.

Calculation for a[59]

Address of a[59]=5000+(59×2)\text{Address of } a[59] = 5000 + (59 \times


2)Address of a[59]=5000+(59×2) =5000+118= 5000 + 118=5000+118 =5118= 5118=5118

Final Answer: The address of a[59] is 5118 in a 16-bit system.

Question 51: Difference between dot operator and -> operator to access structure objects.

Answer: The feof() function is used to check whether the file pointer to a stream is pointing to the
end of the file or not. It returns a non-zero value if the end is reached, otherwise, it returns 0.

Syntax: feof(fptr);

Parameters

 fptr: Pointer to a file stream to read the data from.

Return Value

 Returns a non-zero value (usually 1) if the end of the file is reached.

 Otherwise, it returns 0.
Question 52: Write an algorithm to find the roots of quadratic equation.

Answer: Algorithm to Find the Roots of a Quadratic Equation

A quadratic equation is in the form:

ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0

where a, b, and c are coefficients, and the roots (x values) are found using the quadratic formula:

x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac

Algorithm

Step 1: Start

Step 2: Input the coefficients a, b, and c.

Step 3: Compute the discriminant:

D=b2−4acD = b^2 - 4acD=b2−4ac

Step 4: Check the value of D:

 Case 1 (D > 0): Two real and distinct roots x1=−b+D2a,x2=−b−D2ax_1 = \frac{-b + \sqrt{D}}
{2a}, \quad x_2 = \frac{-b - \sqrt{D}}{2a}x1=2a−b+D,x2=2a−b−D

 Case 2 (D == 0): Two real and equal roots x=−b2ax = \frac{-b}{2a}x=2a−b

 Case 3 (D < 0): Complex (imaginary) roots x1=−b2a+−Di2a,x2=−b2a−−Di2ax_1 = \frac{-b}{2a}


+ \frac{\sqrt{-D}i}{2a}, \quad x_2 = \frac{-b}{2a} - \frac{\sqrt{-D}i}{2a}x1=2a−b+2a−Di,x2
=2a−b−2a−Di

Step 5: Display the roots.

Step 6: Stop.

Question 53: How entry controlled loop is different from exit controlled loop? Write a program to
print the pattern

2 3

4 5 6

7 8 9 10

Answer: entry-controlled loop is for and while and exit controlled loop is do while

C program to print the pattern:


#include <stdio.h>

int main() {

int num = 1; // Starting number

for (int i = 1; i <= 4; i++) { // Controls number of rows

for (int j = 1; j <= i; j++) { // Controls number of columns per row

printf("%d\t", num);

num++; // Increment number

printf("\n"); // Move to next line

return 0;

Question 54: What do you mean by function prototype? How call by value is different from call by
reference? Illustrate call by reference with a suitable example.

Answer: A function prototype in C is a declaration of a function that tells the compiler about:

1. The function name.

2. The return type.

3. The parameters (number and type).

It appears before the main() function or in a header file.

Syntax:

return_type function_name(parameter_type1, parameter_type2, ...);

Example of Function Prototype:

#include <stdio.h>

// Function prototype

int add(int, int);


int main() {

int sum = add(5, 10);

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

return 0;

// Function definition

int add(int a, int b) {

return a + b;

Benefits of Function Prototypes:

Enables function calls before definition.


Checks for correct number and type of arguments.
Improves code readability and modularity.

Difference Between Call by Value and Call by Reference

Feature Call by Value Call by Reference

Function receives a copy of the actual Function receives a reference


Definition
argument. (address) to the actual argument.

Modification of ❌ Changes inside the function do not ✅ Changes inside the function affect
Original Value affect the original variable. the original variable.

Memory Usage Uses more memory (copies values). Uses less memory (passes addresses).

Function Parameter
Uses normal variables as parameters. Uses pointers as parameters.
Type

Example void fun(int x); void fun(int *x);

Illustration of Call by Reference

Example: Swapping Two Numbers Using Call by Reference

#include <stdio.h>

// Function prototype
void swap(int *x, int *y);

int main() {

int a = 5, b = 10;

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

swap(&a, &b); // Passing addresses

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

return 0;

// Function definition (Call by Reference)

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

int temp = *x;

*x = *y;

*y = temp;

Output:

Before swapping: a = 5, b = 10 After swapping: a = 10, b = 5

Question 55: Write a program to implement the menus based basic calculator using switch case.

Answer: #include <stdio.h>

int main() {

int choice;

float num1, num2, result;


while (1) { // Infinite loop to keep the calculator running

// Display Menu

printf("\n===== BASIC CALCULATOR =====\n");

printf("1. Addition (+)\n");

printf("2. Subtraction (-)\n");

printf("3. Multiplication (*)\n");

printf("4. Division (/)\n");

printf("5. Modulus (%%)\n");

printf("6. Exit\n");

printf("Enter your choice (1-6): ");

scanf("%d", &choice);

// Exit if user selects option 6

if (choice == 6) {

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

break;

// Taking input numbers

printf("Enter two numbers: ");

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

// Performing operations using switch-case

switch (choice) {

case 1:

result = num1 + num2;

printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result);


break;

case 2:

result = num1 - num2;

printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result);

break;

case 3:

result = num1 * num2;

printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result);

break;

case 4:

if (num2 == 0) {

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

} else {

result = num1 / num2;

printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result);

break;

case 5:

if ((int)num2 == 0) {

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

} else {

printf("Result: %d %% %d = %d\n", (int)num1, (int)num2, (int)num1 % (int)num2);

break;

default:

printf("Invalid choice! Please enter a valid option (1-6).\n");

}
}

return 0;

You might also like