0% found this document useful (0 votes)
4 views36 pages

C Programming Practice Questions

The document contains multiple C programming solutions, including checking even/odd numbers, identifying vowels, calculating factorials using recursion, reversing numbers, and finding the maximum element in an array. It also explains fundamental data types, typecasting, loop structures, arrays, and recursion with examples. Additionally, it covers the syntax and memory layout of one-dimensional and multi-dimensional arrays.

Uploaded by

aviyukt21
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)
4 views36 pages

C Programming Practice Questions

The document contains multiple C programming solutions, including checking even/odd numbers, identifying vowels, calculating factorials using recursion, reversing numbers, and finding the maximum element in an array. It also explains fundamental data types, typecasting, loop structures, arrays, and recursion with examples. Additionally, it covers the syntax and memory layout of one-dimensional and multi-dimensional arrays.

Uploaded by

aviyukt21
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

Q.

C Program to check even and odd


1. using bitwise operator and
2. without using bitwise or modulus operator

Sol: Due to operator precedence, it is better to write the condition as:

1. #include <stdio.h> 2. #include <stdio.h>

int main() int main()


{ {
int n; int n;

printf("Enter an integer\n"); printf("Enter an integer\n");


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

if ((n & 1) == 1) if ((n / 2) * 2 == n)


printf("Odd\n"); printf("Even\n");
else else
printf("Even\n"); printf("Odd\n");

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

if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' ||


ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' ||
ch == 'u' || ch == 'U')
printf("%c is a vowel.\n", ch);
else
printf("%c is not a vowel.\n", 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;

printf("Enter a number to reverse\n");


scanf("%d", &n);

while (n != 0)
{
reverse = reverse * 10;
reverse = reverse + n % 10;
n = n / 10;
}

printf("Reverse of entered number is = %d\n", reverse);

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

for (i = 1; i <= rows; i++)


{
// Print spaces
for (j = 1; j <= rows - i; j++)
{
printf(" ");
}
// Print stars
for (j = 1; j <= (2 * i - 1); j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Q. WAP to find maximum element in the array

Sol: #include <stdio.h>

int main()
{
int arr[100], n, i, max;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter array elements:\n");

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


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

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


{
if (arr[i] > max)
max = arr[i];
}
printf("Maximum element = %d\n", max);
return 0;
}
Q. WAP to insert an element after the no. inside array

Sol: #include <stdio.h> int main()


{
void insertAfter(int arr[], int *n, int num, int element) int arr[100], n, i;
{ int num, element;
int i, pos = -1;
for (i = 0; i < *n; i++) printf("Enter number of elements: ");
if (arr[i] == num) scanf("%d", &n);
{
pos = i; printf("Enter array elements:\n");
break; for (i = 0; i < n; i++)
} scanf("%d", &arr[i]);
if (pos == -1) printf("Enter the number after which element is to be
{ scanf("%d", &num);
printf("Number not found.\n"); printf("Enter the new element: ");
return; scanf("%d", &element);
} insertAfter(arr, &n, num, element);
// Shift elements to the right printf("Array after insertion:\n");
for (i = *n; i > pos + 1; i--) for (i = 0; i < n; i++)
arr[i] = arr[i - 1]; printf("%d ", arr[i]);
arr[pos + 1] = element; return 0;
(*n)++; }
}
Short Answer Questions

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.

Fundamental Data Types in C

1. int (Integer): Used to store whole numbers without decimals.


○ Size: Typically 2 or 4 bytes.
○ Example: int age = 25;
2. float (Floating-point): Used to store single-precision fractional/decimal numbers (up to 6 digits of precision).
○ Size: 4 bytes.
○ Example: float pi = 3.14f;
3. double (Double-precision Float): Used to store high-precision decimal numbers (up to 15 digits of precision).
○ Size: 8 bytes.
○ Example: double preciseValue = 3.1415926535;
4. char (Character): Used to store a single character enclosed in single quotes.
○ Size: 1 byte.
○ Example: char grade = 'A';
Typecasting : Typecasting refers to converting a variable from one data type to another. C supports two
types of typecasting:

2. Explicit Typecasting (Manual Conversion)


1. Implicit Typecasting (Automatic Conversion)
This conversion is performed manually by the
This conversion is performed automatically by the programmer using the cast operator (type).
compiler when a value of a smaller data type is It is used when converting a larger data type to a smaller
assigned to a larger data type. It does not cause any one or during operations where precise division is
loss of data. needed to prevent unintended data truncation.

int main() { int main() {


int totalMarks = 17;
int count = 10;
int subjects = 5;
double total = count; // Implicitly converts 'int' 10 to
// Explicitly converting totalMarks to double before
'double' 10.000000
division
printf("Total: %f\n", total); double average = (double) totalMarks / subjects; //
Result: 3.400000
return 0;
printf("Average: %.2f\n", average);
} return 0;
}
2. Differentiate between while loop and do-while loop based on execution flow, syntax, and
entry/exit conditions.

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() {

int i = 10; int i = 10;

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

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

// Code block to be executed repeatedly }

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--).

Execution Flow of a for Loop


1. Initialize counter variable => 2. Check Condition => 3. Execute Loop Body => 4. Increment/Decrement Counter => 5.
Repeat from Step 2 until condition becomes false.
#include <stdio.h>
Program: Reverse an Integer Using a for Loop
To reverse a number (e.g., 1234 => 4321): int main()
{
● Extract the last digit using modulus:
remainder = num % 10 int num, originalNum, reverse = 0, rem;
● Build the reversed number: reversed =
printf("Enter a number: ");
(reversed * 10) + remainder
● Remove the last digit from original number: scanf("%d", &num);
num = num / 10
originalNum = num;
Output : while (num != 0)

Enter an integer: 5821 {


rem = num % 10;
Original Number: 5821
reverse = reverse * 10 + rem;
Reversed Number: 1285
num = num / 10;
}
printf("Original Number = %d\n", originalNum);
printf("Reversed Number = %d\n", reverse);
return 0;
}
4. Define an Array. Explain One-Dimensional (1D) and Multi-Dimensional (2D) arrays with syntax
and memory layout representation.

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.

1. One-Dimensional (1D) Array

A 1D array stores elements in a single linear sequence. Elements are accessed using a single index starting from 0.

● Syntax: datatype array_name[size];


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

Memory Layout

Elements occupy adjacent memory addresses linearly:

Index: [0] [1] [2]

Value: | 10 | | 20 | | 30 |

Address: 2000 2004 2008 (4 bytes apart for int)


2. Two-Dimensional (2D) Array

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].

● Syntax: datatype array_name[rows][columns];


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

Memory Layout

Although visually represented as a table, C stores 2D arrays linearly in RAM using Row-Major Order (row by row):

Visual Matrix: Memory Address Layout:

[ 1 2 ] --> Row 0 Address 3000: matrix[0][0] = 1

[ 3 4 ] --> Row 1 Address 3004: matrix[0][1] = 2

Address 3008: matrix[1][0] = 3

Address 3012: matrix[1][1] = 4


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.

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.

Necessity of Base Condition

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

Execution Flow (for N = 3)


// Recursive function to calculate sum
1. sum(3) returns 3 + sum(2)
int sum(int n) {
2. sum(2) returns 2 + sum(1)
if (n <= 1) { // Base Condition 3. sum(1) hits the base condition and returns 1
return n; 4. Unwinding: 2 + 1 = 3 => 3 + 3 = 6

}
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).

Program Logic & Loop Optimization


To check if a number ii is prime, we divide it by numbers starting from 2 up to i/2 (or sqrt{i}).

● Why optimize to i/2 or sqrt{i}?


If a number i has a factor greater than sqrt{i}, it must also have a corresponding smaller factor less than sqrt{i}.
Thus, checking factors beyond i/2 or sqrt{i} is redundant and wastes processor cycles.

C Program to Print All Prime Numbers Between 1 and N : Continued


#include <stdio.h>

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).

Understanding the Logic


To print a half-pyramid pattern, we use two loops:

● Outer Loop: Controls the current row index (i).


● Inner Loop: Controls the columns printed per row (j).

In a standard N-row half-pyramid, row i prints exactly i elements.

Row 1 (i=1): * -> 1 star

Row 2 (i=2): * * -> 2 stars

Row 3 (i=3): * * * -> 3 stars

Row 4 (i=4): * * * * -> 4 stars


Program: Printing Half-Pyramid of Stars (*)

#include <stdio.h>

int main()
{
int rows, i, j;

printf("Enter number of rows: ");


scanf("%d", &rows);

for (i = 1; i <= rows; i++)


{
for (j = 1; j <= i; j++)
{
printf("* ");
}

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.

return_type: Data type of the value the function returns


1. What is a Function? to the caller (e.g., int, void, float).

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.

A C function consists of two parts: the declaration/header


and the body.

return_type function_name(parameter1_type param1,


parameter2_type param2) {

// Local Variables

// Statement(s) to execute

return return_value; // Required if return_type is not void

}
3. Call by Value vs. Call by Reference

Feature Call by Value 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

#include <stdio.h> int main()


// Call by Value {
void swapByValue(int a, int b) { int x = 10, y = 20;
int temp; printf("Original Values\n");
temp = a; printf("x = %d, y = %d\n", x, y);
a = b; swapByValue(x, y);
b = temp; printf("\nAfter Call by Value\n");
} printf("x = %d, y = %d\n", x, y);
// Call by Reference swapByReference(&x, &y);
void swapByReference(int *a, int *b) { printf("\nAfter Call by Reference\n");
int temp; printf("x = %d, y = %d\n", x, y);
temp = *a; return 0;
*a = *b; }
*b = temp;
}
4. Write a C program to perform matrix multiplication of two dynamic matrices.

// Dynamic memory allocation


#include <stdio.h>
int **A = (int **)malloc(r1 * sizeof(int *));
#include <stdlib.h>
int **B = (int **)malloc(r2 * sizeof(int *));
int **C = (int **)malloc(r1 * sizeof(int *));
int main()
{ for (i = 0; i < r1; i++)
int r1, c1, r2, c2; A[i] = (int *)malloc(c1 * sizeof(int));
int i, j, k;
for (i = 0; i < r2; i++)
printf("Enter rows and columns of Matrix A: "); B[i] = (int *)malloc(c2 * sizeof(int));
scanf("%d %d", &r1, &c1);
for (i = 0; i < r1; i++)
printf("Enter rows and columns of Matrix B: "); C[i] = (int *)malloc(c2 * sizeof(int));
scanf("%d %d", &r2, &c2);
// Input Matrix A
if (c1 != r2) printf("\nEnter elements of Matrix A:\n");
{ for (i = 0; i < r1; i++)
printf("Matrix multiplication is not possible.\n"); {
return 0; for (j = 0; j < c1; j++)
} {
printf("A[%d][%d]: ", i, j);
scanf("%d", &A[i][j]);
}
}
// Display Result
// Input Matrix B printf("\nResultant Matrix:\n");
printf("\nEnter elements of Matrix B:\n");
for (i = 0; i < r2; i++) for (i = 0; i < r1; i++)
{ {
for (j = 0; j < c2; j++) for (j = 0; j < c2; j++)
{ {
printf("B[%d][%d]: ", i, j); printf("%d ", C[i][j]);
scanf("%d", &B[i][j]); }
} printf("\n");
} }

// Matrix Multiplication // Free allocated memory


for (i = 0; i < r1; i++) for (i = 0; i < r1; i++)
{ {
for (j = 0; j < c2; j++) free(A[i]);
{ free(C[i]);
C[i][j] = 0; }
for (i = 0; i < r2; i++)
for (k = 0; k < c1; k++) {
{ free(B[i]);
C[i][j] += A[i][k] * B[k][j]; }
} free(A);
} free(B);
} free(C);
return 0;
}
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.

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.

Feature struct (Structure) union enum (Enumeration)

Purpose Groups variables of Groups variables of Assigns names to integral


different data types into a different data types into a constants to make code
single unit. shared memory location. readable.

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.

Keyword struct union enum


2. Code Example Demonstrating struct, union, and enum

// 1. Enum Definition int main() {


enum Level {
LOW = 1, // --- ENUM DEMO ---
MEDIUM, // Automatically gets value 2 enum Level currentLevel = MEDIUM;
HIGH // Automatically gets value 3 printf("--- ENUM ---\n");
}; printf("Selected Level: %d\n\n", currentLevel);

// 2. Struct Definition // --- STRUCT DEMO ---


struct Student { struct Student s1 = {101, 89.5};
int id; // 4 bytes printf("--- STRUCT ---\n");
float marks; // 4 bytes printf("Student ID: %d, Marks: %.1f\n", [Link], [Link]);
}; printf("Size of Struct: %lu bytes\n\n", sizeof(s1)); // Both
id and marks exist safely together
// 3. Union Definition
union Data {
int id; // 4 bytes
float marks; // 4 bytes
};
// --- UNION DEMO --- Output :
union Data d1;
printf("--- UNION ---\n"); --- ENUM ---
Selected Level: 2
[Link] = 500;
printf("Assigned ID: %d\n", [Link]); --- STRUCT ---
Student ID: 101, Marks: 89.5
// Assigning marks overwrites the shared memory space Size of Struct: 8 bytes
of id
[Link] = 98.6; --- UNION ---
printf("Assigned Marks: %.1f\n", [Link]); Assigned ID: 500
Assigned Marks: 98.6
printf("ID after Marks assignment ID after Marks assignment (Overwritten/Corrupted):
(Overwritten/Corrupted): %d\n", [Link]); 1120272384
Size of Union: 4 bytes
printf("Size of Union: %lu bytes\n", sizeof(d1));

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.

Each node in a singly linked list contains two main parts:

1. Data: Holds the actual value/information.


2. Next Pointer: Stores the memory address of the next node in the sequence.

2. Fundamental Role of Pointers

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

// 4. Display the Linked List


displayList(head);

// 5. Free dynamically allocated memory


free(head);
free(second);
free(third);

return 0; }

You might also like