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

Programming in C important questions

The document outlines important questions and concepts related to programming in C, covering topics such as algorithms, data types, control statements, arrays, recursion, dynamic memory allocation, structures, unions, file handling, pointers, and macros. It includes examples and explanations for each concept, providing a comprehensive overview for learners. Additionally, it addresses specific programming tasks like checking for palindromes, merging strings, and reading employee details using structures.

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)
2 views

Programming in C important questions

The document outlines important questions and concepts related to programming in C, covering topics such as algorithms, data types, control statements, arrays, recursion, dynamic memory allocation, structures, unions, file handling, pointers, and macros. It includes examples and explanations for each concept, providing a comprehensive overview for learners. Additionally, it addresses specific programming tasks like checking for palindromes, merging strings, and reading employee details using structures.

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/ 25

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

You might also like