C Programming Practice Questions
C Programming Practice Questions
return 0; return 0;
} }
Q. C program to check whether input alphabet is a vowel or not
Sol:
#include <stdio.h>
main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
return 0;
}
#include <stdio.h>
main()
{
char ch;
printf("Enter a character\n");
scanf("%c", &ch);
switch(ch)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
printf("%c is a vowel.\n", ch);
break;
default:
printf("%c is not a vowel.\n", ch);
}
return 0;
}
Q. Factorial program in c using recursion
Sol:
#include <stdio.h>
long factorial(int n)
{
long factorial(int);
if (n == 0)
return 1;
int main()
else
{
return (n * factorial(n - 1));
int num;
}
long f;
printf("Enter a number to find factorial\n");
scanf("%d", &num);
if (num < 0)
printf("Negative numbers are not allowed.\n");
else
{
f = factorial(num);
printf("%d! = %ld\n", num, f);
}
return 0;
}
Q. C program to reverse a number
Sol:
#include <stdio.h>
main()
{
int n, reverse = 0;
while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10;
}
return 0;
}
Q. Write a C program to accept three numbers using command line arguments and print the largest number.
Sol:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b, c, largest;
if (argc != 4)
{
printf("Usage: %s <num1> <num2> <num3>\n", argv[0]);
return 1;
}
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
largest = a;
if (b > largest)
largest = b;
if (c > largest)
largest = c;
printf("Largest Number = %d\n", largest);
return 0;
Q. C program to print patterns of numbers and stars Sol: #include <stdio.h>
* int main()
*** {
***** int rows, i, j;
******* printf("Enter the number of rows: ");
********* scanf("%d", &rows);
int main()
{
int arr[100], n, i, max;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");
1. What are the fundamental data types in C programming? Explain the difference between implicit and explicit
typecasting with suitable code snippets.
2. Differentiate between while loop and do-while loop based on execution flow, syntax, and entry/exit conditions.
3. Define a for loop and explain its syntax. Write a C program to reverse a given integer using a for loop.
4. Define an Array. Explain One-Dimensional (1D) and Multi-Dimensional (2D) arrays with syntax and memory layout
representation.
5. What is recursion? State the necessity of a base condition in recursive functions and write a recursive program to
calculate the sum of the first N natural numbers.
1. What are the fundamental data types in C programming? Explain the difference between
implicit and explicit typecasting with suitable code snippets.
Data types specify the type and size of data a variable can store, determining how much memory is allocated in RAM.
Loops are used to execute a block of code repeatedly as long as a specified condition remains true. Both while and do-while
loops are used for iteration, but they differ fundamentally in when they test their condition and how many times they are
guaranteed to execute.
Key Differences
1. Entry-Controlled vs. Exit-Controlled
● while loop (Entry-Controlled): The condition is evaluated before the control enters the loop body. If the condition is
false at the very beginning, the loop body will not execute even once.
● do-while loop (Exit-Controlled): The condition is evaluated after executing the loop body. This guarantees that the loop
body will execute at least once, regardless of whether the condition is true or false initially.
2. Minimum Iteration Count
● while loop: Minimum execution count = 0.
● do-while loop: Minimum execution count = 1.
3. Syntax Differences
● while loop: Does not end with a semicolon after the loop condition.
● do-while loop: Requires a mandatory semicolon (;) right after the closing parenthesis of the while(condition) statement.
1. while Loop Example (Condition initially false) 2. do-while Loop Example (Condition initially false)
int main() { int main() {
// Condition is false (10 < 5 is false) // Body runs first, condition checked later
do {
while (i < 5) {
printf("This WILL be printed at least once!\n");
printf("This will NOT be printed.\n");
i++;
i++;
} while (i < 5); // Condition (11 < 5) is false, loop terminates
}
return 0;
return 0;
}
}
Output : This WILL be printed at least once!
Output: (No output printed because condition fails at
entry)
3. Define a for loop and explain its syntax. Write a C program to reverse a given integer using a for
loop.
A for loop is an entry-controlled iteration structure in C programming used to execute a block of code repeatedly for a
known or fixed number of times. It combines loop initialization, condition evaluation, and variable modification into a single
concise line.
Explanation of Components:
1. Initialization: Executed only once at the beginning to set up the loop counter variable (e.g., int i = 0).
2. Condition: Checked before every iteration. If true, the loop body executes; if false, the loop terminates.
3. Increment/Decrement: Updates the loop counter variable after each loop execution (e.g., i++ or i--).
An array is a data structure in C that stores a fixed-size, sequential collection of elements of the same data type in
contiguous (adjacent) memory locations.
A 1D array stores elements in a single linear sequence. Elements are accessed using a single index starting from 0.
Memory Layout
Value: | 10 | | 20 | | 30 |
A 2D array stores elements in a grid or matrix format consisting of rows and columns. It is accessed using two indices:
[row_index][column_index].
Memory Layout
Although visually represented as a table, C stores 2D arrays linearly in RAM using Row-Major Order (row by row):
Recursion is a programming process where a function calls itself directly or indirectly to break down a complex problem into
smaller, manageable sub-problems of the same type.
A base condition is a predefined termination criteria in a recursive function that stops further recursive calls.
● Why it is required: Without a base condition, the function will call itself infinitely, consuming memory stack space
continuously until it triggers a stack overflow error and crashes the program.
Program: Sum of First N Natural Numbers
}
return n + sum(n - 1); // Recursive call
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Sum of first %d natural numbers = %d\n", n,
sum(n));
return 0;
}
Long Answer Questions
1. Write a C program to print all prime numbers between 1 and N, where N is provided by the user. Optimize your inner
loop to check divisibility up to sqrt{N} or N/2.
2. Write a C program to print a right-angled half-pyramid pattern of stars (*) for N rows using nested loops.
3. What is a function? Explain its syntax. Compare Call by Value and Call by Reference with a complete C program
demonstrating a swap function.
4. Write a C program to perform matrix multiplication of two dynamic matrices. State and check the necessary condition
for matrix multiplication before proceeding with the operation.
5. Differentiate among struct, union, and enum in C programming regarding memory allocation, access mechanics, and
use cases. Provide a code example illustrating all three.
6. Define a Linked List. What is the fundamental role of pointers in building and traversing a linked list? Write a
complete C program to dynamically allocate, link, and display a 3-node singly linked list.
1. Write a C program to print all prime numbers between 1 and N, where N is provided by the user.
Optimize your inner loop to check divisibility up to sqrt{N} or N/2
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself (e.g., 2, 3, 5, 7,
11).
int main()
{ Code Explanation
int n, i, j, isPrime; 1. Outer Loop (i from 2 to N): Tests every number
printf("Enter the value of N: "); in the range. Numbers 0 and 1 are skipped as
scanf("%d", &n); they are not prime.
printf("Prime numbers between 1 and %d are:\n", n); 2. Inner Loop Optimization (j up to i / 2): Checks
for (i = 2; i <= n; i++) if any integer divides i evenly (i % j == 0).
{ 3. Early Termination (break): As soon as a single
isPrime = 1; factor is discovered, isPrime is marked as 0 and
for (j = 2; j <= i / 2; j++) the inner loop terminates immediately to save
{ execution time.
if (i % j == 0) 4. Display: If isPrime remains 1 after checking all
{ possible factors up to i/2, the number is printed.
isPrime = 0;
break;
}
}
if (isPrime == 1) printf("%d ", i);
}
return 0;
}
2. Write a C program to print a right-angled half-pyramid pattern of stars (*) for N rows using nested
loops.
A half-pyramid pattern is a triangular arrangement of characters, numbers, or symbols printed line by line using nested
loops. Nested loops are used whenever code needs to execute across two dimensions (rows and columns).
#include <stdio.h>
int main()
{
int rows, i, j;
printf("\n");
}
return 0;
}
3. What is a function? Explain its syntax. Compare Call by Value and Call by Reference with a
complete C program demonstrating a swap function.
A function is a self-contained block of statements function_name: The identifier used to call the function.
designed to perform a specific task. Functions promote
code reusability, modularity, and readability by allowing a
parameters: Input variables passed to the function
program to be divided into smaller, manageable sub-
programs. (optional).
2. Syntax of a Function return_value: The value sent back to the main caller.
// Local Variables
// Statement(s) to execute
}
3. Call by Value vs. Call by Reference
Data Transfer Passes a copy of the actual Passes the memory address
parameter's value. (pointer) of the variable.
Modification Changes made inside the function do Changes made inside the function
not affect original variables. directly affect original variables.
Memory Allocation Creates separate memory locations Shares the same memory location via
for formal arguments. pointers.
Use Case Useful when original data protection Useful when a function needs to
is needed. modify input data or return multiple
values.
4. Complete C Program: Swap Demonstration
Overview & Key Differences : struct, union, and enum are user-defined data types used to group related data, but they differ
significantly in memory allocation and usage.
Memory Allocation Allocates memory for all Allocates memory equal to Stores integer values
members combined (sum the largest member size (usually 4 bytes for an int).
of sizes + padding). only.
Member Access All members can be Only one member can Members represent fixed
accessed and store unique store and retain a valid named constants, not
values simultaneously. value at a time. variables.
return 0;
}
6. Define a Linked List. What is the fundamental role of pointers in building and traversing a linked
list? Write a complete C program to dynamically allocate, link, and display a 3-node singly linked
list.
1. Linkedlist : A Linked List is a linear data structure composed of a sequence of elements called nodes. Unlike arrays,
linked list elements are not stored in contiguous memory locations.
Pointers are the core component that makes a linked list functional:
● In Building: Since nodes are created dynamically in scattered memory locations using functions like malloc(),
pointers are essential to link these independent blocks together. The next pointer of one node stores the address of
the subsequent node.
● In Traversing: A temporary pointer (e.g., struct Node *temp = head) is used to start at the first node (head) and
sequentially step through the list by continually updating its value to temp->next until it reaches NULL (the end of the
list).
3. Complete C Program: 3-Node Singly Linked List
#include <stdio.h> int main()
#include <stdlib.h> {
// Declare node pointers
// Definition of a Linked List Node struct Node *head = NULL;
struct Node { struct Node *second = NULL;
int data; struct Node *third = NULL;
struct Node *next;
// Allocate memory for three nodes
};
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
// Function to display the linked list
third = (struct Node *)malloc(sizeof(struct Node));
void displayList(struct Node *head) {
struct Node *temp = head; // Check memory allocation
printf("Linked List Elements: "); if (head == NULL || second == NULL || third == NULL)
while (temp != NULL) { {
printf("[%d] -> ", temp->data); printf("Memory allocation failed!\n");
temp = temp->next; return 1;
} }
printf("NULL\n");
} return 0;
}
// 3. Assign data and link the nodes Sample Output :
// First Node (Head) Linked List Elements: [10] -> [20] -> [30] -> NULL
head->data = 10;
head->next = second; // Link head to second node
// Second Node
second->data = 20;
second->next = third; // Link second to third node
// Third Node
third->data = 30;
third->next = NULL; // Last node points to NULL
return 0; }