0% found this document useful (0 votes)
10 views41 pages

C Language All Important Questions

The document outlines important programming concepts in C, including algorithms, data types, control statements, arrays, recursion, dynamic memory allocation, structures, and file handling. It provides definitions, examples, and differences between various programming constructs, such as break vs continue, while vs do-while loops, and structures vs unions. Additionally, it includes sample C programs for practical applications like palindrome checking, string merging, and matrix addition.

Uploaded by

sarshad81323
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)
10 views41 pages

C Language All Important Questions

The document outlines important programming concepts in C, including algorithms, data types, control statements, arrays, recursion, dynamic memory allocation, structures, and file handling. It provides definitions, examples, and differences between various programming constructs, such as break vs continue, while vs do-while loops, and structures vs unions. Additionally, it includes sample C programs for practical applications like palindrome checking, string merging, and matrix addition.

Uploaded by

sarshad81323
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/ 41

Programming in C important questions

1. Discuss features of Algorithm.

An algorithm is a step-by-step procedure to solve a problem. Features:

1. Finiteness: It must terminate after a finite number of steps.

2. Definiteness: Each step must be clear and unambiguous.

3. Input: Zero or more inputs are provided.

4. Output: At least one output is produced.

5. Effectiveness: Steps should be basic enough to be carried out.

2. Explain various basic datatypes in C with examples.

int: for integers (e.g., int a = 10;)

float: for floating-point numbers (e.g., float b = 3.14;)

char: for characters (e.g., char ch = 'A';)

double: for double-precision float (e.g., double d = 45.6789;)

void: used for functions with no return type.

3. Differentiate between Break and Continue statements with Example.

Feature Break Continue

Use Exits loop Skips current iteration


Example if(i==3) break; if(i==3) continue;

for(int i=1;i<=5;i++){
if(i==3) break;
printf("%d ",i);
}

Output: 1 2

for(int i=1;i<=5;i++){
if(i==3) continue;
printf("%d ",i);
}

Output: 1 2 4 5

4. Write differences between while and do-while statements with examples.

Feature while loop do-while loop

Execution Condition checked first Body executed first


Syntax while(condition){} do{} while(condition);

Example:

int i=0;
while(i<3){
printf("%d ", i);
i++;
}

int i=0;
do {
printf("%d ", i);
i++;
} while(i<3);

5. Explain character handling functions with examples.


Functions in <ctype.h>:

isalpha(c) – checks if character is alphabet

isdigit(c) – checks if character is digit

toupper(c) – converts to uppercase

tolower(c) – converts to lowercase

Example:
char ch = 'a';
printf("%c", toupper(ch)); // Output: A

6. Explain one-dimensional arrays

A one-dimensional array is a collection of similar data elements stored under a


common name and indexed by a single subscript.

Syntax:

datatype array_name[size];

Example:

int marks[5] = {90, 85, 78, 92, 88};

Accessing elements:

printf("%d", marks[2]); // Output: 78

Memory Representation:

Stored in contiguous memory locations.

If marks[0] is at address 2000, marks[1] will be at 2004 (for int size 4 bytes), and so
on.

7. Write a recursion function to calculate factorial of a given number

Recursion is a process in which a function calls itself.

Factorial using recursion:

int factorial(int n) {
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

Example Call:

int result = factorial(5); // Output: 120

8. Explain dynamic memory allocation mechanisms


Dynamic memory allocation in C is done using four functions in <stdlib.h>:

1. malloc() – allocates memory, returns void*

2. calloc() – allocates and initializes to 0

3. realloc() – resizes the previously allocated memory

4. free() – deallocates memory

Example:

int *ptr;
ptr = (int*) malloc(5 * sizeof(int));
if(ptr == NULL) {
printf("Memory not allocated");
} else {
// use memory
free(ptr); // release memory
}

9. Write differences between structures and unions

Feature Structure Union

Memory Each member has separate memory All members share same memory
Size Sum of all members Size of the largest member
Example Use Employee data Multiple data in same location

Structure Example:

struct student {
int id;
float marks;
};

Union Example:

union data {
int i;
float f;
};
10. Explain various modes of opening files in C

C provides different file modes used with fopen():

Mode Meaning

"r" Open for reading


"w" Open for writing (creates new or clears)
"a" Open for appending
"r+" Open for read & write
"w+" Open for read & write (clears file)
"a+" Read & write, appends if file exists

Example:

FILE *fp;
fp = fopen("data.txt", "r");
if(fp == NULL)
printf("File not found");
else
fclose(fp);

11. Explain structure of a C Program

C program has the following structure:

1. Header Files Inclusion

#include <stdio.h>

2. Global Declarations

int x = 10;

3. Main Function

int main() {
// code
return 0;
}

4. User-defined Functions
void greet() {
printf("Hello");
}

12. List out C Tokens and explain with suitable examples

C Tokens are the smallest elements in a program:

1. Keywords – int, return, if, while

2. Identifiers – sum, total

3. Constants – 10, 'A'

4. Operators – +, -, *, ==

5. Special Symbols – {}, ;, #, ()

6. Strings – "Hello"

13. Discuss in detail about decision making statements in C

C provides decision-making statements like:

1. if

if(a > b) printf("A is greater");

2. if-else

if(a > b) printf("A");


else printf("B");

3. else-if Ladder

if(a > b) {...}


else if(a == b) {...}
else {...}
4. switch

switch(choice) {
case 1: printf("One"); break;
default: printf("Invalid");
}

14. Write a C Program for given number is palindrome or not

#include <stdio.h>
int main() {
int n, rev = 0, temp, rem;
printf("Enter a number: ");
scanf("%d", &n);
temp = n;
while(n != 0) {
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if(temp == rev)
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}

15. Write a C Program for merging two strings without pre-defined functions

#include <stdio.h>
int main() {
char str1[100], str2[100];
int i=0, j=0;
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

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


while(str2[j] != '\0') {
str1[i++] = str2[j++];
}
str1[i] = '\0';
printf("Merged string: %s", str1);
return 0;
}
16. Write a C program for adding two NxM matrices

#include <stdio.h>
int main() {
int a[10][10], b[10][10], sum[10][10];
int i, j, n, m;

printf("Enter rows and columns: ");


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

printf("Enter elements of Matrix A:\n");


for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d", &a[i][j]);

printf("Enter elements of Matrix B:\n");


for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d", &b[i][j]);

for(i=0;i<n;i++)
for(j=0;j<m;j++)
sum[i][j] = a[i][j] + b[i][j];

printf("Sum of matrices:\n");
for(i=0;i<n;i++) {
for(j=0;j<m;j++)
printf("%d ", sum[i][j]);
printf("\n");
}
return 0;
}

17. Define pointer? Explain pointer to array with example

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

Pointer to array example:

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


int *ptr = arr; // points to arr[0]

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


printf("%d ", *(ptr + i)); // Access array elements using pointer
}

18. Explain call-by-value and call-by-reference with example


Call-by-value: Copies the actual value

Call-by-reference: Passes the address

Example:

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


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x=10, y=20;
swap(&x, &y); // Call by reference
printf("%d %d", x, y); // Output: 20 10
}

19. Write C program to read employee details using structure

#include <stdio.h>
struct Employee {
int id;
char name[30];
char designation[30];
char department[20];
float salary;
};

int main() {
struct Employee e;
printf("Enter Employee Details:\n");
printf("ID: "); scanf("%d", &e.id);
printf("Name: "); scanf(" %[^\n]", e.name);
printf("Designation: "); scanf(" %[^\n]", e.designation);
printf("Department: "); scanf(" %[^\n]", e.department);
printf("Salary: "); scanf("%f", &e.salary);

printf("\nEmployee Information:\n");
printf("ID: %d\nName: %s\nDesignation: %s\nDepartment: %s\nSalary: %.2f\n",
e.id, e.name, e.designation, e.department, e.salary);
return 0;
}

12. List out C Tokens and explain with suitable examples

C Tokens are the smallest elements in a program:


1. Keywords – int, return, if, while

2. Identifiers – sum, total

3. Constants – 10, 'A'

4. Operators – +, -, *, ==

5. Special Symbols – {}, ;, #, ()

6. Strings – "Hello"

13. Discuss in detail about decision making statements in C

C provides decision-making statements like:

1. if

if(a > b) printf("A is greater");

2. if-else

if(a > b) printf("A");


else printf("B");

3. else-if Ladder

if(a > b) {...}


else if(a == b) {...}
else {...}

4. switch

switch(choice) {
case 1: printf("One"); break;
default: printf("Invalid");
}

14. Write a C Program for given number is palindrome or not


#include <stdio.h>
int main() {
int n, rev = 0, temp, rem;
printf("Enter a number: ");
scanf("%d", &n);
temp = n;
while(n != 0) {
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if(temp == rev)
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}

15. Write a C Program for merging two strings without pre-defined functions

#include <stdio.h>
int main() {
char str1[100], str2[100];
int i=0, j=0;
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);

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


while(str2[j] != '\0') {
str1[i++] = str2[j++];
}
str1[i] = '\0';
printf("Merged string: %s", str1);
return 0;
}

16. Write a C program for adding two NxM matrices

#include <stdio.h>
int main() {
int a[10][10], b[10][10], sum[10][10];
int i, j, n, m;

printf("Enter rows and columns: ");


scanf("%d%d", &n, &m);
printf("Enter elements of Matrix A:\n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d", &a[i][j]);

printf("Enter elements of Matrix B:\n");


for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d", &b[i][j]);

for(i=0;i<n;i++)
for(j=0;j<m;j++)
sum[i][j] = a[i][j] + b[i][j];

printf("Sum of matrices:\n");
for(i=0;i<n;i++) {
for(j=0;j<m;j++)
printf("%d ", sum[i][j]);
printf("\n");
}
return 0;
}

17. Define pointer? Explain pointer to array with example

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

Pointer to array example:

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


int *ptr = arr; // points to arr[0]

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


printf("%d ", *(ptr + i)); // Access array elements using pointer
}

18. Explain call-by-value and call-by-reference with example

Call-by-value: Copies the actual value

Call-by-reference: Passes the address

Example:

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


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x=10, y=20;
swap(&x, &y); // Call by reference
printf("%d %d", x, y); // Output: 20 10
}

19. Write C program to read employee details using structure

#include <stdio.h>
struct Employee {
int id;
char name[30];
char designation[30];
char department[20];
float salary;
};

int main() {
struct Employee e;
printf("Enter Employee Details:\n");
printf("ID: "); scanf("%d", &e.id);
printf("Name: "); scanf(" %[^\n]", e.name);
printf("Designation: "); scanf(" %[^\n]", e.designation);
printf("Department: "); scanf(" %[^\n]", e.department);
printf("Salary: "); scanf("%f", &e.salary);

printf("\nEmployee Information:\n");
printf("ID: %d\nName: %s\nDesignation: %s\nDepartment: %s\nSalary: %.2f\n",
e.id, e.name, e.designation, e.department, e.salary);
return 0;
}

20. Write a C program to read characters from one file and write to another file

#include <stdio.h>
int main() {
FILE *f1, *f2;
char ch;
f1 = fopen("input.txt", "r");
f2 = fopen("output.txt", "w");

if(f1 == NULL || f2 == NULL) {


printf("File error!");
return 1;
}

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


fputc(ch, f2);
}

fclose(f1);
fclose(f2);
printf("File copied successfully.");

Q1) What is an array? Explain 2D array with memory representation.

Array is a collection of elements of same data type stored in contiguous memory.

2D Array:

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

Memory Representation:

arr[0][0] = 1, arr[0][1] = 2, arr[0][2] = 3


arr[1][0] = 4, arr[1][1] = 5, arr[1][2] = 6

Q2) Define pointer. Explain functions of DMA (Dynamic Memory Allocation).

Pointer: A variable that stores address of another variable.

int a = 10;
int *p = &a;

DMA Functions:

malloc()

calloc()

realloc()

free()

Used for dynamic memory management at runtime.

Q3) What are structure and union? Difference?


Structure
Memory for all members Memory shared among all

Union
Members accessed simultaneously One at a time

struct Student { int id; float marks; };


union Data { int i; float f; };

Q4) Define macro. How to use it?

Macro: Preprocessor directive used for defining constants or code.

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

Use: Substitutes text before compilation.

Q5) What is an operator and its types? Explain left and right shift.

Operators: Symbols that perform operations.

Types: Arithmetic, Logical, Relational, Bitwise, Assignment, etc.

Shift Operators:

x << 1 // left shift


x >> 1 // right shift

Q6) Swap two numbers without using temporary variable

int a=5, b=10;


a = a + b;
b = a - b;
a = a - b;

Q7) Why is C called mid-level language?

C combines features of:

Low-level (direct memory access)

High-level (structured programming)

Hence, it's mid-level.


Q8) Basic data types in C

int → integers

char → characters

float → decimal

double → large decimal

void → no value

Q9) What are preprocessor directives? Example of macro.

Instructions processed before compilation.

Example:

#define MAX 100


#include <stdio.h>

Q10) What is recursion? Explain with example.

Recursion: A function calling itself.

Example:

int fact(int n) {
if(n==0) return 1;
return n * fact(n-1);
}

Q11) Difference between local and global variables

Local Global

Declared inside functions Outside all functions


Scope is limited Scope is whole program

Q12) Difference between type casting and type conversion


Type Casting: Manual conversion.

float f = (float)10;

Type Conversion: Automatic by compiler.

Q13) Functions and their types in C

Types:

Library functions (e.g., printf())

User-defined functions

Application: Code reuse and modularity.

Q14) Difference between macro and function. Storage classes?

Macro Function

Text substitution Executable code


No type checking Type checked

Storage Classes:

auto, register, static, extern

Q15) Call by value vs Call by reference

Call by Value Call by Reference

Copy passed Address passed


Original not changed Original modified

Example:

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


Q16) Program to check prime number

int isPrime(int n) {
if (n <= 1) return 0;
for(int i=2; i<n; i++)
if(n%i==0) return 0;
return 1;
}

Q17) Static vs Dynamic Memory Allocation

Static Dynamic

Compile-time Runtime
Fixed size Variable size

Functions: malloc(), calloc(), realloc(), free()

Q18) Program to check if string is palindrome

int isPalindrome(char str[]) {


int i=0, j=strlen(str)-1;
while(i<j) {
if(str[i++] != str[j--]) return 0;
}
return 1;
}

Q19) Use of printf() and scanf(), format specifiers

printf(): Prints output


scanf(): Takes input

Format specifiers:

%d → int

%f → float

%c → char

%s → string
Q20) Key features of C

Simple and efficient

Fast execution

Rich library

Pointers and direct memory access

Structured programming

Portable and flexible

Important questions.

1. Explain the use of switch statement.

Syntax:

switch(expression) {
case value1:
// code;
break;
case value2:
// code;
break;
default:
// code;
}

Example:

int ch = 2;
switch(ch) {
case 1: printf("One"); break;
case 2: printf("Two"); break;
default: printf("Invalid");
}

2. How to reverse a string without using library functions?

Syntax:

for(i = 0, j = len - 1; i < j; i++, j--) {


swap(str[i], str[j]);
}

Example:

char str[] = "hello";


// Swap characters from start and end

3. Difference between ++i and i++.

Example:

int i = 5;
printf("%d", ++i); // Outputs 6 (pre-increment)
printf("%d", i++); // Outputs 6, then i becomes 7 (post-increment)

4. What is file handling in C? List file modes.

Common file modes:

"r" – Read

"w" – Write

"a" – Append

"r+" – Read and Write

Syntax:

FILE *fp = fopen("data.txt", "r");

5. How to find largest and smallest in array?

Logic:

max = arr[0];
for(i = 1; i < n; i++) {
if(arr[i] > max) max = arr[i];
}

Use same logic for min with < operator.

6. Difference between gets() and scanf().

Syntax:
char str[100];
gets(str); // reads full line
scanf("%s", str); // reads till space

Note: gets() is unsafe and deprecated.

7. What is Bubble Sort?

Syntax:

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


for(j = 0; j < n-i-1; j++)
if(arr[j] > arr[j+1])
swap(arr[j], arr[j+1]);

8. Difference between struct and typedef struct.

Using struct:

struct Student {
int id;
};
struct Student s1;

Using typedef struct:

typedef struct {
int id;
} Student;
Student s1;

9. What is scope and lifetime of variables?

Example with static:

void func() {
static int x = 0;
x++;
printf("%d", x);
}

static retains value between function calls.

10. Fibonacci series using loop and recursion


Loop syntax:

a = 0, b = 1;
for(i = 0; i < n; i++) {
c = a + b;
a = b;
b = c;
}

Recursion:

int fib(int n) {
if(n <= 1) return n;
return fib(n-1) + fib(n-2);
}

EXPECTED QUESTIONS FOR THIS SEMISTER EXAM


2025.

1. Explain the structure of a C program.

Answer: A typical C program consists of the following sections:

Preprocessor Directives: Instructions processed before compilation, e.g., #include


<stdio.h>.

Global Declarations: Variables and functions declared outside main().

main() Function: The entry point of the program.

Function Definitions: Definitions of user-defined functions.

2. Differentiate between break and continue statements with examples.

Answer:

break: Terminates the nearest enclosing loop or switch statement.

continue: Skips the current iteration and proceeds with the next iteration of the loop.

Example:

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


if(i == 2) continue; // Skips when i is 2
if(i == 4) break; // Exits loop when i is 4
printf("%d ", i);
}

3. What is recursion? Provide an example.

Answer: Recursion is a programming technique where a function calls itself to solve


a problem.

Example:

int factorial(int n) {
if(n == 0) return 1;
else return n * factorial(n - 1);
}

4. Explain the difference between gets() and scanf() functions.

Answer:

gets(): Reads an entire line, including spaces, until a newline character is


encountered.

scanf(): Reads input until a whitespace character is encountered; cannot read multi-
word strings.

Note: gets() is unsafe and deprecated due to potential buffer overflows.

5. Describe the use of arrays in inter-function communication.

Answer: Arrays can be passed to functions to allow multiple values to be processed


or modified within the function, facilitating communication between functions.

Example:

void modifyArray(int arr[], int size) {


for(int i = 0; i < size; i++) {
arr[i] += 1;
}
}

6. What are pointers? List their advantages.

Answer: Pointers are variables that store the memory address of another variable.
Advantages:

Efficient array and string handling.

Dynamic memory allocation.

Facilitates call by reference.

Enables the creation of complex data structures like linked lists.

7. Define a stream in C programming.

Answer: A stream is an abstraction that represents a source or destination of data,


such as files or input/output devices. C uses streams to perform input and output
operations.

8. How are files handled in C? Mention common file operations.

Answer: Files in C are handled using the FILE pointer and functions like fopen(),
fclose(), fread(), fwrite(), fprintf(), and fscanf().

Common operations:

Opening a file: fopen()

Reading from a file: fread() or fscanf()

Writing to a file: fwrite() or fprintf()

Closing a file: fclose()

9. Explain the concept of storage classes in C.

Answer: Storage classes in C define the scope, visibility, and lifetime of variables.
The main storage classes are:

auto: Default for local variables.

register: Suggests storing the variable in a CPU register.

static: Retains the value of a variable between function calls.

extern: Declares a global variable that is defined in another file.

10. What is the difference between call by value and call by reference?
Answer:

Call by value: Passes a copy of the variable's value to the function; original value
remains unchanged.

Call by reference: Passes the variable's address to the function; allows the function
to modify the original variable.

Example:

void modify(int *ptr) {


*ptr = 10;
}

return 0;
}
Unit 1,2,3,4,5 imp questions

Unit-1:

1. Explain different types of Computers?

Computers can be categorized based on size, purpose, and performance:

Supercomputers: Extremely fast and powerful, used for scientific simulations,


weather forecasting, and nuclear research.

Mainframe Computers: Large systems used by big organizations for bulk data
processing like census, ERP, and financial transactions.

Minicomputers: Mid-sized computers used in manufacturing and small businesses.

Microcomputers: Common personal computers (PCs), laptops, and desktops.

Embedded Computers: Built into other devices (like washing machines, microwave
ovens, and cars) to perform dedicated functions.

2. What is software? Explain different types of software?

Software is a collection of instructions that tell a computer how to work. It is broadly


classified into:

System Software: Includes operating systems (Windows, Linux), device drivers, and
utility programs that help run the hardware.

Application Software: Programs designed for end-users, like MS Word, Excel, or


browsers.

Programming Software: Tools to write and test programs (compilers, debuggers).

Middleware: Software that acts as a bridge between applications and the operating
system.

3. Explain flow chart and algorithms?

Algorithm: A step-by-step procedure to solve a problem or perform a task (e.g.,


finding the largest number).
Flowchart: A diagrammatic representation of an algorithm using symbols like
arrows, rectangles (process), diamonds (decision), and ovals (start/end).

4. Explain the Basic Structure of C Language?

A basic C program includes:

Preprocessor Directives: #include<stdio.h>

Main Function: int main()

Variable Declaration: int a, b;

Statements and Expressions: a = b + 5;

Return Statement: return 0;

Example:

#include <stdio.h>
int main() {
int a = 10;
printf("Value: %d", a);
return 0;
}

5. Explain Data Types in C?

C language supports several data types:

Basic Types: int, float, char, double

Derived Types: Arrays, pointers, functions

Enumeration Types: enum

Void: Represents the absence of value

Examples:

int age = 25;


float pi = 3.14;
char grade = 'A';

6. What is Operator? Explain Different types of Operators in C?

Operators are symbols used to perform operations. Types:


Arithmetic: +, -, *, /, %

Relational: ==, !=, >, <

Logical: &&, ||, !

Assignment: =, +=, -=

Increment/Decrement: ++, --

Bitwise: &, |, ^, ~

7. Explain I/O statements in C?

Input: scanf() – takes input from the user

Output: printf() – displays output to the screen

Example:

int a;
scanf("%d", &a);
printf("Value: %d", a);

Unit-2:

1. Explain Control Statements (if, switch) in C?

Control statements are used to control the flow of execution in a C program.

1.1 if Statement: Used to execute a block of code if a condition is true.

Syntax:

if (condition) {
// code to be executed
}

Example:

int num = 10;


if (num > 0) {
printf("Number is positive");
}

1.2 if-else Statement: Executes one block if the condition is true, another if false.
Example:

if (num % 2 == 0) {
printf("Even number");
} else {
printf("Odd number");
}

1.3 Nested if: One if inside another.

Example:

if (num > 0) {
if (num < 100) {
printf("Number is between 1 and 99");
}
}

1.4 switch Statement: Used to select one of many blocks of code to be executed.

Syntax:

switch (expression) {
case constant1:
// code
break;
case constant2:
// code
break;
default:
// code
}

Example:

int day = 2;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
default:
printf("Other day");
}
---

2. Explain Looping Statements in C?

Loops are used to execute a block of code repeatedly.

2.1 for Loop:

Syntax:

for(initialization; condition; increment/decrement) {


// code
}

Example:

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


printf("%d ", i);
}

2.2 while Loop: Executes block as long as the condition is true.

Syntax:

while (condition) {
// code
}

Example:

int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}

2.3 do-while Loop: Executes at least once, then repeats as long as condition is true.

Syntax:

do {
// code
} while (condition);
Example:

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);

3. Explain break and continue and goto statements?

3.1 break Statement: Used to exit a loop or switch statement immediately.

Example:

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


if (i == 5) break;
printf("%d ", i);
}

Output: 1 2 3 4

3.2 continue Statement: Skips the current iteration and moves to the next.

Example:

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


if (i == 3) continue;
printf("%d ", i);
}

Output: 1 2 4 5

3.3 goto Statement: Transfers control to a labeled statement.

Syntax:

goto label;
// code
label:
// code

Example:

int i = 1;
if (i == 1) goto jump;
printf("This will not print.");
jump:
printf("Goto used!");

Unit-3

1. What is an Array? (4M)

An array is a collection of elements of the same data type stored at contiguous


memory locations. Arrays are used to store multiple values in a single variable.

Syntax:

datatype arrayName[size];

Example:

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

Accessing elements:

printf("%d", numbers[2]); // Output: 30

Key Points:

Array index starts from 0.

Elements are stored sequentially in memory.

Useful for loops and batch operations.

2. Explain different types of Arrays with Example?

2.1 One-Dimensional Array: Used to store a list of values.

Example:

int arr[3] = {1, 2, 3};

2.2 Two-Dimensional Array: Used to represent matrices or tables.

Syntax:
datatype arrayName[rows][columns];

Example:

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

2.3 Multi-Dimensional Array: More than two dimensions (rarely used).

Example:

int cube[2][2][2] = {
{{1,2},{3,4}},
{{5,6},{7,8}}
};

3. Explain String Handling Functions in C?

C provides several string handling functions through the <string.h> header file.

Some common ones:

strlen(str) – Returns the length of the string.

strcpy(dest, src) – Copies src into dest.

strcat(dest, src) – Concatenates src to dest.

strcmp(str1, str2) – Compares two strings.

strrev(str) – Reverses the string (non-standard, works in some compilers).

Example:

#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";

strcat(str1, str2);
printf("Concatenated: %s", str1);
return 0;
}
4. Explain String Declaration? (4M)

A string in C is an array of characters terminated by a null character \0.

Declaration Methods:

Character array:

char str[10] = "Hello";

Without size:

char str[] = "Hello";

Using individual characters:

char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Important Points:

Strings are stored as arrays.

Always terminate with \0.

Use %s in printf and scanf.

Unit-4

1. What is a Function? (4M)

A function in C is a block of code that performs a specific task. It promotes


modularity, reusability, and better organization.

Advantages:

Code reuse

Easier debugging and maintenance

Logical program structure

Syntax:

return_type function_name(parameters) {
// function body
}
Example:

int add(int a, int b) {


return a + b;
}

2. Function Call (4M)

Function call refers to invoking a function to execute its code.

Types of Function Calls:

Call by value: Copy of variable is passed (changes don’t reflect).

Call by reference (using pointers): Address is passed (changes reflect in actual


values).

Example:

int main() {
int result = add(5, 10);
printf("%d", result);
return 0;
}

3. Return Statement (4M)

The return statement is used to return a value from a function to the calling function.

Syntax:

return expression;

Example:

int square(int x) {
return x * x;
}

Note: void functions do not return a value.

4. Explain Parameter Passing (Passing Values in Functions)

Parameter passing means supplying inputs (arguments) to a function.


Call by Value (default in C):

Copy of argument is passed.

Original value is not modified.

void change(int x) {
x = 20;
}

Call by Reference (using pointers):

Address of variable is passed.

Original value can be changed.

void change(int *x) {


*x = 20;
}

5. Explain Storage Classes in C?

Storage classes define the scope, visibility, and lifetime of variables.

Types:

1. auto – Default for local variables.

2. register – Requests storage in CPU registers for faster access.

3. static – Retains value between function calls.

4. extern – Used to declare a global variable defined in another file.

Example:

static int count = 0;

6. What is a Pointer?

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


Syntax:

datatype *pointer_name;

Example:

int a = 10;
int *p = &a;

&a gives address of a.

*p gives value at the address.

7. Explain Pointer and Functions?

Pointers can be used:

To pass values by reference.

To return multiple values from a function.

Example:

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


int temp = *a;
*a = *b;
*b = temp;
}

Call:

swap(&x, &y);

8. Explain Pointer and Arrays?

Pointers and arrays are closely related. Array name is a constant pointer to the first
element.

Example:

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


int *p = arr;

printf("%d", *(p + 1)); // Output: 20

Accessing array using pointers is equivalent to using indices:


p[0] == arr[0], p[1] == arr[1]

Unit-5

1. Explain Dynamic Memory Allocation Functions in C?

Dynamic Memory Allocation allows programmers to allocate memory during runtime


using functions in the <stdlib.h> header.

Key functions:

malloc(size) – Allocates specified bytes of memory.

int *ptr = (int *)malloc(5 * sizeof(int));

calloc(n, size) – Allocates memory for an array of n elements and initializes to zero.

int *ptr = (int *)calloc(5, sizeof(int));

realloc(ptr, new_size) – Changes the size of memory block.

ptr = (int *)realloc(ptr, 10 * sizeof(int));

free(ptr) – Frees allocated memory.

free(ptr);

Advantages:

More efficient memory usage.

Useful when size of data is unknown during compile-time.

2. What is a Structure?

A structure is a user-defined data type in C that allows grouping of different data


types under a single name.

Syntax:

struct structure_name {
datatype member1;
datatype member2;
...
};
Example:

struct Student {
int roll;
char name[20];
float marks;
};

Declaration and Access:

struct Student s1;


s1.roll = 101;

3. Explain Arrays of Structure in C?

An array of structures stores multiple records of the same structure type.

Example:

struct Student {
int roll;
char name[20];
float marks;
};

struct Student s[3]; // array of 3 students

Accessing:

s[0].roll = 101;
strcpy(s[0].name, "Aman");
s[0].marks = 95.5;

Used for handling records like employee list, student database, etc.

4. Explain Structure and Pointer in C?

You can use pointers to structures to access or modify structure data dynamically.

Example:

struct Student {
int roll;
float marks;
};

struct Student s1 = {101, 88.5};


struct Student *ptr = &s1;

printf("%d", ptr->roll); // Access using arrow (->)

ptr->member is shorthand for (*ptr).member.

5. Explain Difference Between Structure and Union in C?

Feature Stracture Union


Memory Separate memory Share memory
For each member All member

Access All members can be Only one member


Access at once A time

Size Sum of size all size of largest


Members Members

Use case When storing When storing only


Multiple values one value at a time

Structure Example:

struct Data {
int i;
float f;
};

Union Example:

union Data {
int i;
float f;
};

You might also like