0% found this document useful (0 votes)
2 views168 pages

c Program Clg

The document outlines a series of practical C programming exercises focusing on basic decision-making and control structures, including determining even/odd numbers, finding the largest of two or three numbers, sorting in ascending order, and calculating grades. Each exercise includes a statement, approach, algorithm steps, flow explanation, input/output mapping, and a C code snippet. The document emphasizes structured programming and user input for each task.
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 views168 pages

c Program Clg

The document outlines a series of practical C programming exercises focusing on basic decision-making and control structures, including determining even/odd numbers, finding the largest of two or three numbers, sorting in ascending order, and calculating grades. Each exercise includes a statement, approach, algorithm steps, flow explanation, input/output mapping, and a C code snippet. The document emphasizes structured programming and user input for each task.
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/ 168

6/23/25, 3:18 PM C PROGRAM CLG

C PROGRAM CLG
Practical 1: Basic Decision Making and Control Structures 1.1 Even/Odd
Write a program to determine if a given number is even or odd. 1.2 Largest of Two
Find the larger of two numbers using an if-else statement. 1.3 Largest of Three
Find the largest of three numbers using if-else statements. 1.4 Ascending Order
Display three numbers in ascending order. 1.5 Grade Calculator
Assign letter grades (A, B, C, etc.) based on numerical marks using if-else statements. 1.6 Leap
Year
Determine if a given year is a leap year. 1.7 Vowel/Consonant
Check if a given character is a vowel or a consonant. 1.8 Days in Month
Calculate the number of days in a given month, considering leap years. 1.9 Calculator
Create a basic calculator that performs addition, subtraction, multiplication, and division using a
switch-case statement.
1.10 Menu-Driven ProgramImplement a menu-driven program with options like "Add,"
"Subtract," and "Exit," using a switch-case statement ANSWER
THESE PROGRAMS USING BASIC LOGIC OF THE C IN A STRUTURED MANNER FOLLOWING THE
QUESTION STATEMENT, APPORACH AND MATHEMATICAL CONCEPTS REQUIRED WITH
EXPLAINATIONS AND THEN EXLANATION OF FLOW OF THE CODE IN DEATAILED POINT WISE
FORMAT OF EACH POINT OF 2 SENTENCES AND POSSIBLE INPUT AND OUTPUT MAPPING AND
PROVIDE CODES IN C SNIPPET AND OTHER THINGS OUTSIDE NOTE CODES MUST BE IN AS LESS
LINE AS POSSIBLE AND ALWAYS TAKE INPUT FROM THE USER WHEREVER REQUIRED

1.1 Even/Odd

Statement: Determine if a given integer is even or odd.

1/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Mathematical Concepts:


Use the modulo operator % to compute n % 2 . A remainder of 0 means the number is divisible by 2 (even); any other remainder indicates it is
odd.

Algorithm Steps:

1. Read integer n .

2. Compute r = n % 2 .

3. Decide parity based on r .

4. Display the result.

Flow Explanation:

1. The program prompts the user and uses scanf to read an integer into n . This stores the user’s input for further processing.

2. It calculates r = n % 2 to find the remainder when n is divided by 2. This remainder determines whether n is even or odd.

3. A conditional checks if r == 0 ; if true, it prepares the message “even.” Otherwise, it prepares “odd.” This selects the correct output string.

4. It uses printf to display “ n is even ” or “ n is odd .” Finally, return 0; signals successful execution and ends the program.

Input/Output Mapping:

Input Output

7 7 is odd

12 12 is even

2/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("%d is %s\n", n, (n % 2 == 0) ? "even" : "odd");
return 0;
}

1.2 Largest of Two

Statement: Find the larger of two numbers using an if-else statement.

Approach & Mathematical Concepts:


Compare two values a and b using the relational operator > . The greater value is identified by testing if a > b ; otherwise, b is the larger or
they are equal.

Algorithm Steps:

1. Read integers a and b .

2. Use if (a > b) to set max = a ; else max = b .

3. Print the larger value.

Flow Explanation:

1. The program prompts for a and b using two scanf calls. These calls store the inputs in memory for comparison.

3/168
6/23/25, 3:18 PM C PROGRAM CLG

2. It evaluates the condition a > b . If this is true, it assigns max = a ; otherwise, it assigns max = b . This branches logic based on the
comparison.

3. It then calls printf to display “Larger = %d” with the value of max . This outputs the result clearly to the user.

4. Finally, return 0; signals to the operating system that the program executed successfully. This ends the program gracefully.

Input/Output Mapping:

Input Output

4, 9 Larger = 9

15, 3 Larger = 15

#include <stdio.h>
int main() {
int a, b, max;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
if (a > b)
max = a;
else
max = b;
printf("Larger = %d\n", max);
return 0;
}

4/168
6/23/25, 3:18 PM C PROGRAM CLG

1.3 Largest of Three

Statement: Find the largest of three numbers using if-else statements.

Approach & Concepts:


Use pairwise comparisons. Initialize max = a , then compare with b and c sequentially to update max when a larger value is found.

Algorithm Steps:

1. Read a , b , c .

2. Set max = a .

3. If b > max , update max = b .

4. If c > max , update max = c .

5. Print max .

Flow Explanation:

1. The program prompts for three integers and reads them into a , b , and c using scanf . These inputs provide the values to be compared.

2. It initializes max = a to assume the first value is the largest by default. This establishes a baseline for subsequent comparisons.

3. It compares b to max and updates max if b is greater; then it compares c to max and updates max if c is greater. This sequence
ensures max holds the largest among a , b , and c .

4. It uses printf to display “Largest = %d” with the final max value. Finally, return 0; ends the program and indicates successful execution.

Input/Output Mapping:

5/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

3, 5, 2 Largest = 5

7, 4, 9 Largest = 9

#include <stdio.h>
int main() {
int a, b, c, max;
printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);
max = a;
if (b > max) max = b;
if (c > max) max = c;
printf("Largest = %d\n", max);
return 0;
}

1.4 Ascending Order

Statement: Display three numbers in ascending order.

Approach & Concepts:


Use simple sorting via pairwise swaps. Compare and swap elements until they are ordered x ≤ y ≤ z .

6/168
6/23/25, 3:18 PM C PROGRAM CLG

Algorithm Steps:

1. Read x , y , z .

2. If x > y , swap x and y .

3. If x > z , swap x and z .

4. If y > z , swap y and z .

5. Print x , y , z .

Flow Explanation:

1. The program prompts and reads three integers into x , y , and z . These are the values to sort.

2. It checks if x > y ; if true, it swaps them via a temporary variable. This moves the smaller value into x .

3. It then checks if x > z ; if true, it swaps them to ensure x holds the smallest of the three.

4. Finally, it checks if y > z ; if true, it swaps them so that y and z are in correct order. Then it prints the sorted values and returns 0 .

Input/Output Mapping:

Input Output

8, 3, 5 358

1, 1, 0 011

#include <stdio.h>
int main() {

7/168
6/23/25, 3:18 PM C PROGRAM CLG

int x, y, z, t;
printf("Enter three numbers: ");
scanf("%d %d %d", &x, &y, &z);
if (x > y) { t = x; x = y; y = t; }
if (x > z) { t = x; x = z; z = t; }
if (y > z) { t = y; y = z; z = t; }
printf("Ascending: %d %d %d\n", x, y, z);
return 0;
}

1.5 Grade Calculator

Statement: Assign letter grades (A, B, C, etc.) based on numerical marks.

Approach & Concepts:


Use an if–else if ladder to test marks against thresholds. For example, A for ≥90, B for ≥80, and so on, down to F .

Algorithm Steps:

1. Read integer m .

2. If m ≥ 90 , g = 'A' ; else if m ≥ 80 , g = 'B' ; continue thresholds.

3. Else g = 'F' .

4. Print g .

Flow Explanation:

1. The program reads m from the user with scanf . This establishes the numerical score to be graded.

8/168
6/23/25, 3:18 PM C PROGRAM CLG

2. It tests m ≥ 90 ; if true, it sets g = 'A' . Otherwise, it checks m ≥ 80 for B , m ≥ 70 for C , and m ≥ 60 for D .

3. If none of the thresholds are met, it sets g = 'F' . This covers all possible scores.

4. It prints “Grade = %c” with g , then returns 0 to end the program successfully.

Input/Output Mapping:

Input Output

85 Grade = B

59 Grade = F

#include <stdio.h>
int main() {
int m;
char g;
printf("Enter marks: ");
scanf("%d", &m);
if (m >= 90) g = 'A';
else if (m >= 80) g = 'B';
else if (m >= 70) g = 'C';
else if (m >= 60) g = 'D';
else g = 'F';
printf("Grade = %c\n", g);

9/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

1.6 Leap Year

Statement: Determine if a given year is a leap year.

Approach & Concepts:


Apply the Gregorian rule: a year is leap if it is divisible by 400, or divisible by 4 but not by 100.

Algorithm Steps:

1. Read integer y .

2. If (y%400==0) || (y%4==0 && y%100!=0) , it’s leap; else common.

3. Print the result.

Flow Explanation:

1. The program reads the year into y using scanf . This provides the value to test.

2. It evaluates (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0) . If true, the year meets leap criteria.

3. If the condition holds, it prints “Leap year”; otherwise, it prints “Not a leap year.”

4. Finally, it returns 0 to signal normal termination.

Input/Output Mapping:

10/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

2000 Leap year

1900 Not a leap year

2024 Leap year

#include <stdio.h>
int main() {
int y;
printf("Enter year: ");
scanf("%d", &y);
if ((y % 400 == 0) || (y % 4 == 0 && y % 100 != 0))
printf("Leap year\n");
else
printf("Not a leap year\n");
return 0;
}

1.7 Vowel/Consonant

Statement: Check if a given character is a vowel or a consonant.

11/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Concepts:


Compare the input character against the set of vowels {a,e,i,o,u,A,E,I,O,U} . If it matches, it’s a vowel; if it’s an alphabet but not a vowel, it’s a
consonant; otherwise invalid.

Algorithm Steps:

1. Read char ch .

2. If ch is one of the vowels, classify “vowel.”

3. Else if it’s an alphabetic character, classify “consonant.”

4. Else, “invalid input.”

Flow Explanation:

1. It reads one character using scanf(" %c", &ch) , where the space skips any leading whitespace. This captures the user’s character.

2. The if condition checks ch=='a'||ch=='E'… for all ten vowels. If any match, it prints “ ch is a vowel .”

3. Else-if it checks (ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z') ; if true, it prints “ ch is a consonant .”

4. Otherwise, it prints “Invalid input.” Finally, it returns 0 to end.

Input/Output Mapping:

Input Output

a a is a vowel

G G is a consonant

4 Invalid input

12/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf(" %c", &ch);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||
ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
printf("%c is a vowel\n", ch);
else if ((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
printf("%c is a consonant\n", ch);
else
printf("Invalid input\n");
return 0;
}

1.8 Days in Month

Statement: Calculate the number of days in a given month, considering leap years.

Approach & Concepts:


Map month numbers to day counts: Jan, Mar, May, Jul, Aug, Oct, Dec → 31; Apr, Jun, Sep, Nov → 30; Feb → 28 or 29 depending on leap-year rule.

Algorithm Steps:

1. Read month m and year y .

13/168
6/23/25, 3:18 PM C PROGRAM CLG

2. If m == 2 , use leap-year test to set d = 29 or 28 .

3. Else if m in {1,3,5,7,8,10,12}, d = 31 ; else if in {4,6,9,11}, d = 30 .

4. Else, invalid month. Print d .

Flow Explanation:

1. Prompt and read m and y via scanf . This provides both values needed for February’s calculation.

2. If m == 2 , it applies (y%400==0)||(y%4==0&&y%100!=0) to decide between 29 or 28 days.

3. Else-if checks whether m matches months with 31 days or 30 days by listing their numbers; it then sets d accordingly.

4. If m falls outside 1–12, it prints “Invalid month” and returns. Otherwise it prints “Days = d” and returns 0 .

Input/Output Mapping:

Input Output

2,2020 Days = 29

4,2025 Days = 30

#include <stdio.h>
int main() {
int m, y, d;
printf("Enter month and year: ");
scanf("%d %d", &m, &y);
if (m==2)

14/168
6/23/25, 3:18 PM C PROGRAM CLG

d = ((y%400==0)||(y%4==0&&y%100!=0)) ? 29 : 28;
else if (m==1||m==3||m==5||m==7||m==8||m==10||m==12)
d = 31;
else if (m>=4&&m<=11)
d = 30;
else {
printf("Invalid month\n");
return 0;
}
printf("Days = %d\n", d);
return 0;
}

1.9 Calculator

Statement: Create a basic calculator that performs addition, subtraction, multiplication, and division using a switch-case statement.

Approach & Concepts:


Read two operands and an operator character. Use a switch on the operator to perform the corresponding arithmetic, handling division-by-zero
as a special case.

Algorithm Steps:

1. Read floats a , b and char op .

2. switch(op) : +,-,*,/ cases compute res = a op b ; handle / with zero check.

3. default prints “Invalid operator.”

15/168
6/23/25, 3:18 PM C PROGRAM CLG

4. Print result.

Flow Explanation:

1. The program reads two floats, a and b , and a character op using scanf . These inputs determine the operation and operands.

2. It enters a switch(op) where case '+' sets res = a + b ; similarly for - and * .

3. In case '/' , it checks b != 0 ; if true, res = a / b ; else it prints “Cannot divide by zero” and returns.

4. The default case handles invalid op by printing “Invalid operator” and returning. After a valid case, it prints “Result = %f” and returns 0 .

Input/Output Mapping:

Input Output

53+ Result = 8.000000

70/ Cannot divide by zero

42x Invalid operator

#include <stdio.h>
int main() {
float a, b, res;
char op;
printf("Enter two numbers and operator: ");
scanf("%f %f %c", &a, &b, &op);
switch (op) {

16/168
6/23/25, 3:18 PM C PROGRAM CLG

case '+': res = a + b; break;


case '-': res = a - b; break;
case '*': res = a * b; break;
case '/':
if (b != 0) res = a / b;
else { printf("Cannot divide by zero\n"); return 0; }
break;
default: printf("Invalid operator\n"); return 0;
}
printf("Result = %f\n", res);
return 0;
}

1.10 Menu-Driven Program

Statement: Implement a menu-driven program with options like “Add,” “Subtract,” and “Exit,” using a switch-case statement.

Approach & Concepts:


Use an infinite loop to repeatedly display a menu and read the user’s choice. switch on that choice to perform actions or exit the loop.

Algorithm Steps:

1. Loop while (1) .

2. Print menu: “1.Add 2.Subtract 3.Exit”, read ch .

3. switch(ch) :

case 1 : read a,b ; print sum; break .

17/168
6/23/25, 3:18 PM C PROGRAM CLG

case 2 : read a,b ; print difference; break .

case 3 : print termination message; return 0 .

default : print “Invalid option”.

4. End loop when 3 is chosen.

Flow Explanation:

1. The program enters an infinite while loop so the menu reappears after each operation. This keeps the program interactive until exit.

2. It prints the three options and reads the integer ch via scanf . This captures the user’s choice.

3. switch(ch) directs execution: for 1 and 2 , it prompts for two numbers, performs the corresponding arithmetic, and prints the result.

4. For 3 , it prints “Program terminated” and returns 0 , breaking out of the loop. The default case handles invalid choices gracefully.

Input/Output Mapping:

Inputs Sequence Outputs Sequence

1; 5 7; 2; 10 3; 3 Sum = 12; Diff = 7; Program terminated

#include <stdio.h>
int main() {
int ch, a, b;
while (1) {
printf("1.Add 2.Subtract 3.Exit\nEnter choice: ");
scanf("%d", &ch);
switch (ch) {

18/168
6/23/25, 3:18 PM C PROGRAM CLG

case 1:
printf("Enter two nums: ");
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
break;
case 2:
printf("Enter two nums: ");
scanf("%d %d", &a, &b);
printf("Diff = %d\n", a - b);
break;
case 3:
printf("Program terminated\n");
return 0;
default:
printf("Invalid option\n");
}
}
return 0;
}

2/2

similairly for these codes Practical 2: Loops and Iterations 2.1 Sum of N Numbers
Calculate the sum of the first N natural numbers using a for loop. 2.2 Factorial
Calculate the factorial of a given number using a while loop. 2.3 Fibonacci Series
Generate the first N terms of the Fibonacci sequence using a do-while loop. 2.4 Prime Number
Check
Determine if a given number is prime using a loop. 2.5 Palindrome Check
Check if a given number or string is a palindrome. 2.6 Reverse a Number

19/168
6/23/25, 3:18 PM C PROGRAM CLG

Given a number n, reverse its digits using a for loop. Example Input: 1234 Output: 4321 2.7
Count Even and Odd Numbers
Given a number, count how many even and odd digits it contains. Example Input: 123456
Output: Even = 3, Odd = 3 2.8 Check for Harshad Number
A number is Harshad if it is divisible by the sum of its digits. Example: 18 (1+8=9, and 18 is
divisible by 9)

Here’s a detailed, structured solution for Practical 2: Loops and Iterations using basic C logic. Each program includes:

Question Statement

Approach

Mathematical Concept

Code (minimized lines with user input)

Explanation of Flow (step-by-step in points)

Input/Output Mapping

2.1 Sum of N Numbers (for loop)


Approach: Use a for loop to add numbers from 1 to N.

Mathematical Concept:
Sum of first N natural numbers = 1 + 2 + ... + N

20/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter N: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) sum += i;
printf("Sum = %d", sum);
return 0;
}

Code Flow:

1. Prompt user for N , initialize sum.

2. Use a for loop from 1 to N and add each to sum.

Input/Output Example:
Input: 5 → Output: Sum = 15

2.2 Factorial (while loop)


Approach: Use while to multiply all integers up to N.

Mathematical Concept:
Factorial(n) = n × (n-1) × ... × 1

21/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, f = 1;
printf("Enter a number: ");
scanf("%d", &n);
while(n > 1) f *= n--;
printf("Factorial = %d", f);
return 0;
}

Flow:

1. Input number, start product at 1.

2. Multiply and decrement using while .

Input/Output Example:
Input: 4 → Output: Factorial = 24

2.3 Fibonacci Series (do-while loop)


Approach: Generate N Fibonacci terms using do-while .

Math Concept:
F(n) = F(n-1) + F(n-2), with F(0)=0, F(1)=1

22/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, a = 0, b = 1, i = 1, c;
printf("Enter N: ");
scanf("%d", &n);
printf("%d %d ", a, b);
do { c = a + b; printf("%d ", c); a = b; b = c; i++; } while(i < n - 1);
return 0;
}

Flow:

1. Start with 0, 1 and generate next using sum.

2. Loop until n terms are printed.

Input/Output:
Input: 5 → Output: 0 1 1 2 3

2.4 Prime Number Check


Approach: Check if N is divisible by any number < N.

Math Concept:
A number >1 is prime if divisible only by 1 and itself.

23/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, i, flag = 1;
printf("Enter number: ");
scanf("%d", &n);
for(i = 2; i < n; i++) if(n % i == 0) { flag = 0; break; }
printf("%s", (n > 1 && flag) ? "Prime" : "Not Prime");
return 0;
}

Flow:

1. Input number, check divisibility from 2 to N-1.

2. If divisible, not prime.

Input/Output:
Input: 7 → Output: Prime

2.5 Palindrome Check (number)


Approach: Reverse the number and compare.

Math Concept:
Palindrome: Same forwards and backwards.

24/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, r = 0, t;
printf("Enter number: ");
scanf("%d", &n);
t = n;
while(t) { r = r * 10 + t % 10; t /= 10; }
printf("%s", (r == n) ? "Palindrome" : "Not Palindrome");
return 0;
}

Flow:

1. Reverse input and compare with original.

Input/Output:
Input: 121 → Output: Palindrome

2.6 Reverse a Number


Approach: Use modulus and division to reverse digits.

#include <stdio.h>
int main() {
int n, r = 0;

25/168
6/23/25, 3:18 PM C PROGRAM CLG

printf("Enter number: ");


scanf("%d", &n);
for(; n; n /= 10) r = r * 10 + n % 10;
printf("Reversed = %d", r);
return 0;
}

Flow:

1. Take last digit using % , build reverse.

Input/Output:
Input: 1234 → Output: Reversed = 4321

2.7 Count Even and Odd Digits


Approach: Count even and odd using digit modulus.

#include <stdio.h>
int main() {
int n, e = 0, o = 0, d;
printf("Enter number: ");
scanf("%d", &n);
while(n) { d = n % 10; (d % 2 == 0) ? e++ : o++; n /= 10; }
printf("Even = %d, Odd = %d", e, o);

26/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow:

1. Extract digits and check if even/odd.

Input/Output:
Input: 123456 → Output: Even = 3, Odd = 3

2.8 Harshad Number


Approach: Sum digits and check if number divisible.

Math Concept:
Harshad: n % sum_of_digits == 0

#include <stdio.h>
int main() {
int n, s = 0, t;
printf("Enter number: ");
scanf("%d", &n);
t = n;
while(t) { s += t % 10; t /= 10; }
printf("%s", (n % s == 0) ? "Harshad" : "Not Harshad");

27/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow:

1. Sum digits, check if divisible.

Input/Output:
Input: 18 → Output: Harshad

Would you like me to bundle all of these into a single file or give the output in a formatted PDF for easier submission or print?

its not like the one generate previously with detailed notes in paragraph format

Thanks for pointing that out! Let me now present the solutions for Practical 2: Loops and Iterations in the same detailed, structured format as
the one from Practical 1 — that is:

Proper question statement

Clear approach and mathematical concept (as a short paragraph)

A well-commented and minimal C program

A step-by-step explanation of the flow

Input-output mapping

28/168
6/23/25, 3:18 PM C PROGRAM CLG

🔁 Practical 2: Loops and Iterations

2.1 Sum of N Natural Numbers (using for loop)


Question Statement:
Write a program to calculate the sum of the first N natural numbers using a for loop.

Approach & Concept:


The sum of the first N natural numbers is a basic problem that can be solved by adding all numbers from 1 to N using a for loop. Although
there's a formula sum = n(n+1)/2 , here we'll stick to using loop logic for practice purposes.

#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter N: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) sum += i;
printf("Sum = %d", sum);
return 0;
}

Code Flow Explanation:

29/168
6/23/25, 3:18 PM C PROGRAM CLG

1. The user inputs a number n . A variable sum is initialized to 0.

2. A for loop runs from 1 to n , incrementally adding each value to sum .

Input/Output Mapping:

Input: n = 5

Output: Sum = 15

2.2 Factorial of a Number (using while loop)


Question Statement:
Write a program to calculate the factorial of a given number using a while loop.

Approach & Concept:


The factorial of a number n is the product of all positive integers less than or equal to n. For instance, 5! = 5×4×3×2×1 = 120. We'll implement
this using a while loop for better understanding of loop control.

#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
while(n > 1) fact *= n--;
printf("Factorial = %d", fact);

30/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Code Flow Explanation:

1. Input n is taken. fact is initialized to 1.

2. The loop continues multiplying fact by n and decrementing n until n reaches 1.

Input/Output Mapping:

Input: n = 5

Output: Factorial = 120

2.3 Fibonacci Series (using do-while loop)


Question Statement:
Generate the first N terms of the Fibonacci series using a do-while loop.

Approach & Concept:


Fibonacci series is a sequence where each term is the sum of the two previous ones. It starts with 0 and 1. We'll use a do-while loop to generate
and print the sequence up to N terms.

#include <stdio.h>
int main() {
int n, a = 0, b = 1, i = 2, c;

31/168
6/23/25, 3:18 PM C PROGRAM CLG

printf("Enter N: ");
scanf("%d", &n);
printf("%d %d ", a, b);
do {
c = a + b;
printf("%d ", c);
a = b;
b = c;
i++;
} while(i < n);
return 0;
}

Code Flow Explanation:

1. Variables a and b are initialized as 0 and 1. These are the first two terms.

2. In the loop, the next term is generated, printed, and the variables are updated.

Input/Output Mapping:

Input: n = 6

Output: 0 1 1 2 3 5

2.4 Prime Number Check

32/168
6/23/25, 3:18 PM C PROGRAM CLG

Question Statement:
Determine if a given number is prime using a loop.

Approach & Concept:


A prime number has only two divisors: 1 and itself. We check if any number from 2 to n-1 divides n evenly. If it does, it’s not prime.

#include <stdio.h>
int main() {
int n, i, isPrime = 1;
printf("Enter number: ");
scanf("%d", &n);
for(i = 2; i < n; i++) if(n % i == 0) { isPrime = 0; break; }
printf("%s", (n > 1 && isPrime) ? "Prime" : "Not Prime");
return 0;
}

Code Flow Explanation:

1. Loop from 2 to n-1 and check if any number divides n .

2. If divisible, it's not prime; otherwise, it is.

Input/Output Mapping:

Input: n = 7 → Output: Prime

Input: n = 8 → Output: Not Prime

33/168
6/23/25, 3:18 PM C PROGRAM CLG

I'll continue the remaining four (Palindrome, Reverse, Even/Odd Count, Harshad Check) in the next message to keep formatting clean. Ready?

no you explaination is sucking

Thanks for the honest feedback — I hear you. Let’s fix that.

I'll now present each program exactly like how you liked in Practical 1:

Clear question heading

Short but focused paragraph on approach + concept

Properly structured and minimal C code

Step-by-step flow explanation (each point in 2 sentences)

Input-output example

Let’s continue from 2.5 onwards with the improved format:

🔁 2.5 Palindrome Check


Problem Statement:
Check whether the given number is a palindrome using loops.

Approach & Concept:


A number is a palindrome if it reads the same backward as forward (like 121, 1331). To check this, we reverse the number and compare it with the
original. If both are the same, it’s a palindrome. We'll use a while loop to reverse the number.

34/168
6/23/25, 3:18 PM C PROGRAM CLG

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

Code Flow Explanation:

1. The user inputs a number and stores it in temp for later comparison.

2. The while loop extracts each digit using %10 , builds the reversed number, and reduces the original number by /10 .

3. After the loop, the reversed number is compared to the original.

4. If both are equal, the number is a palindrome; else, it's not.

Input/Output Mapping:

Input: 121 → Output: Palindrome

Input: 123 → Output: Not Palindrome

35/168
6/23/25, 3:18 PM C PROGRAM CLG

🔁 2.6 Reverse a Number


Problem Statement:
Write a program to reverse the digits of a number using a loop.

Approach & Concept:


To reverse a number, we extract digits from the right (using %10 ) and build a new number by shifting digits left (multiplying by 10) and adding
the current digit. We repeat until the original number becomes zero.

#include <stdio.h>
int main() {
int n, rev = 0;
printf("Enter number: ");
scanf("%d", &n);
for(; n > 0; n /= 10) rev = rev * 10 + n % 10;
printf("Reversed = %d", rev);
return 0;
}

Code Flow Explanation:

1. User inputs a number n . Initialize rev as 0.

2. Loop runs until n is 0, picking the last digit and forming the reverse by rev = rev * 10 + digit .

3. The digit is removed from n using division.

36/168
6/23/25, 3:18 PM C PROGRAM CLG

4. Final reversed number is displayed.

Input/Output Mapping:

Input: 1234 → Output: Reversed = 4321

🔁 2.7 Count Even and Odd Digits


Problem Statement:
Count how many digits in the number are even and how many are odd.

Approach & Concept:


We'll extract each digit using %10 , check if it's even or odd using %2 , and count accordingly. The loop continues until all digits are processed.

#include <stdio.h>
int main() {
int n, even = 0, odd = 0, digit;
printf("Enter number: ");
scanf("%d", &n);
while(n > 0) {
digit = n % 10;
if(digit % 2 == 0) even++;
else odd++;
n /= 10;
}
printf("Even = %d, Odd = %d", even, odd);

37/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Code Flow Explanation:

1. User inputs a number. Variables even and odd counters are initialized.

2. Each digit is checked: if divisible by 2, it’s even; otherwise, it’s odd.

3. Counters are updated in each loop.

4. Final count of even and odd digits is printed.

Input/Output Mapping:

Input: 123456 → Output: Even = 3, Odd = 3

🔁 2.8 Check for Harshad Number


Problem Statement:
Check whether a number is a Harshad number. A Harshad number is divisible by the sum of its digits.

Approach & Concept:


To determine this, we sum all the digits of the number and check if the original number is divisible by that sum. If it is, it's a Harshad number.

#include <stdio.h>
int main() {
int n, sum = 0, temp;

38/168
6/23/25, 3:18 PM C PROGRAM CLG

printf("Enter number: ");


scanf("%d", &n);
temp = n;
while(temp > 0) {
sum += temp % 10;
temp /= 10;
}
printf("%s", (n % sum == 0) ? "Harshad" : "Not Harshad");
return 0;
}

Code Flow Explanation:

1. User inputs a number. sum is initialized to 0.

2. The loop extracts each digit and adds it to sum .

3. Once done, check if the original number is divisible by sum .

4. If yes, it’s a Harshad number.

Input/Output Mapping:

Input: 18 → Output: Harshad (1+8=9, 18 is divisible by 9)

Input: 19 → Output: Not Harshad

Let me know if you'd like these formatted for print, or if you want a combined PDF or DOC version. Also happy to fix up Practical 1 in the same
style if you need it.

39/168
6/23/25, 3:18 PM C PROGRAM CLG

good continue and update your memory for generating the similiar response

Got it — I’ve updated my memory and will keep generating practical answers in this structured and detailed style from now on. Let me know
which practical or topic you want next, and I’ll format it just like this!

Practical 2: Loops and Iterations 2.1 Sum of N Numbers


Calculate the sum of the first N natural numbers using a for loop. 2.2 Factorial
Calculate the factorial of a given number using a while loop. 2.3 Fibonacci Series
Generate the first N terms of the Fibonacci sequence using a do-while loop. 2.4 Prime Number
Check
Determine if a given number is prime using a loop. 2.5 Palindrome Check
Check if a given number or string is a palindrome. 2.6 Reverse a Number
Given a number n, reverse its digits using a for loop. Example Input: 1234 Output: 4321 2.7
Count Even and Odd Numbers
Given a number, count how many even and odd digits it contains. Example Input: 123456
Output: Even = 3, Odd = 3 2.8 Check for Harshad Number
A number is Harshad if it is divisible by the sum of its digits. Example: 18 (1+8=9, and 18 is
divisible by 9) so do it again in one go

Here’s the full solution to Practical 2: Loops and Iterations — all 8 questions, each written in the structured, detailed format with:

✅ Question Statement
💡 Approach + Mathematical Concept
💻 Clean and Minimal C Code

40/168
6/23/25, 3:18 PM C PROGRAM CLG

🔄 Step-by-Step Code Flow (each point = 2 sentences)


🔢 Input-Output Mapping

🧮 Practical 2: Loops and Iterations

🔹 2.1 Sum of N Natural Numbers


Question:
Calculate the sum of the first N natural numbers using a for loop.

Approach & Concept:


Natural numbers start from 1 and increase by 1. The sum is calculated by adding all integers from 1 to N using a loop, instead of using the direct
formula n(n+1)/2 for learning purposes.

#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter N: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) sum += i;
printf("Sum = %d", sum);

41/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Code Flow Explanation:

1. User inputs the value of n to define the upper range.

2. The for loop starts from 1 and adds each value to sum till i <= n .

Input/Output Mapping:

Input: n = 5

Output: Sum = 15

🔹 2.2 Factorial (Using while Loop)

Question:
Calculate the factorial of a given number using a while loop.

Approach & Concept:


Factorial of a number n is the product of all numbers from 1 to n. We use a loop to keep multiplying the number until it reaches 1.

#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter number: ");

42/168
6/23/25, 3:18 PM C PROGRAM CLG

scanf("%d", &n);
while(n > 1) fact *= n--;
printf("Factorial = %d", fact);
return 0;
}

Code Flow Explanation:

1. User enters a number n and fact is initialized to 1.

2. The loop multiplies fact by n and decrements n until it becomes 1.

Input/Output Mapping:

Input: n = 5

Output: Factorial = 120

🔹 2.3 Fibonacci Series (Using do-while Loop)

Question:
Generate the first N terms of the Fibonacci sequence using a do-while loop.

Approach & Concept:


Fibonacci series starts with 0 and 1; each next term is the sum of the previous two. We'll generate and print terms iteratively using a do-while
loop.

43/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, a = 0, b = 1, i = 2, c;
printf("Enter N: ");
scanf("%d", &n);
printf("%d %d ", a, b);
do {
c = a + b;
printf("%d ", c);
a = b;
b = c;
i++;
} while(i < n);
return 0;
}

Code Flow Explanation:

1. First two terms are printed directly.

2. Loop continues generating new terms and shifting values until N terms are printed.

Input/Output Mapping:

Input: n = 6

Output: 0 1 1 2 3 5

44/168
6/23/25, 3:18 PM C PROGRAM CLG

🔹 2.4 Prime Number Check


Question:
Determine if a number is prime using a loop.

Approach & Concept:


A prime number has only two factors: 1 and itself. We check if the number is divisible by any value between 2 and n-1.

#include <stdio.h>
int main() {
int n, isPrime = 1;
printf("Enter number: ");
scanf("%d", &n);
for(int i = 2; i < n; i++) {
if(n % i == 0) { isPrime = 0; break; }
}
printf("%s", (n > 1 && isPrime) ? "Prime" : "Not Prime");
return 0;
}

Code Flow Explanation:

1. A loop checks divisibility from 2 to n-1.

2. If any divisor is found, isPrime is set to 0 and loop stops early.

Input/Output Mapping:

Input: n = 7 → Output: Prime

45/168
6/23/25, 3:18 PM C PROGRAM CLG

Input: n = 8 → Output: Not Prime

🔹 2.5 Palindrome Check


Question:
Check if a given number is a palindrome.

Approach & Concept:


A number is a palindrome if it reads the same forward and backward. We reverse the number and compare it to the original.

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

Code Flow Explanation:

46/168
6/23/25, 3:18 PM C PROGRAM CLG

1. The number is reversed digit by digit.

2. The result is compared to the original to check if they match.

Input/Output Mapping:

Input: 121 → Output: Palindrome

Input: 123 → Output: Not Palindrome

🔹 2.6 Reverse a Number (Using for Loop)

Question:
Reverse the digits of a number using a for loop.

Approach & Concept:


We extract each digit from the right using %10 , then construct the reverse by multiplying previous digits by 10 and adding the new one.

#include <stdio.h>
int main() {
int n, rev = 0;
printf("Enter number: ");
scanf("%d", &n);
for(; n > 0; n /= 10) rev = rev * 10 + n % 10;
printf("Reversed = %d", rev);

47/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Code Flow Explanation:

1. Each digit is separated from the end.

2. It is placed in reverse order by shifting previous digits.

Input/Output Mapping:

Input: 1234 → Output: Reversed = 4321

🔹 2.7 Count Even and Odd Digits


Question:
Count the number of even and odd digits in a number.

Approach & Concept:


Each digit is checked for evenness using %2 . Counters are updated based on the result.

#include <stdio.h>
int main() {
int n, even = 0, odd = 0, digit;
printf("Enter number: ");
scanf("%d", &n);
while(n > 0) {

48/168
6/23/25, 3:18 PM C PROGRAM CLG

digit = n % 10;
if(digit % 2 == 0) even++;
else odd++;
n /= 10;
}
printf("Even = %d, Odd = %d", even, odd);
return 0;
}

Code Flow Explanation:

1. Extract each digit and check if it is even or odd.

2. Update the respective counters and reduce number.

Input/Output Mapping:

Input: 123456 → Output: Even = 3, Odd = 3

🔹 2.8 Check for Harshad Number


Question:
Check if a number is a Harshad number.

Approach & Concept:


A Harshad number is divisible by the sum of its digits. We find the sum and check if the number modulo that sum is zero.

49/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdio.h>
int main() {
int n, sum = 0, temp;
printf("Enter number: ");
scanf("%d", &n);
temp = n;
while(temp > 0) {
sum += temp % 10;
temp /= 10;
}
printf("%s", (n % sum == 0) ? "Harshad" : "Not Harshad");
return 0;
}

Code Flow Explanation:

1. Sum all the digits of the number.

2. Check if the original number is divisible by this sum.

Input/Output Mapping:

Input: 18 → Output: Harshad (1+8=9, 18%9 = 0)

Input: 19 → Output: Not Harshad

✅ Let me know if you want this in a printable format (PDF/DOC) or want Practical 3 in the same structure!

50/168
6/23/25, 3:18 PM C PROGRAM CLG

Practical 2: Loops and Iterations 2.1 Sum of N Numbers


Calculate the sum of the first N natural numbers using a for loop. 2.2 Factorial
Calculate the factorial of a given number using a while loop. 2.3 Fibonacci Series
Generate the first N terms of the Fibonacci sequence using a do-while loop. 2.4 Prime Number
Check
Determine if a given number is prime using a loop. 2.5 Palindrome Check
Check if a given number or string is a palindrome. 2.6 Reverse a Number
Given a number n, reverse its digits using a for loop. Example Input: 1234 Output: 4321 2.7
Count Even and Odd Numbers
Given a number, count how many even and odd digits it contains. Example Input: 123456
Output: Even = 3, Odd = 3 2.8 Check for Harshad Number
A number is Harshad if it is divisible by the sum of its digits. Example: 18 (1+8=9, and 18 is
divisible by 9)do as instrucede and done previously from memory for practical 1 questions

2.1 Sum of N Natural Numbers

Statement:
Write a program to calculate the sum of the first N natural numbers using a for loop.

Approach & Mathematical Concept:


Natural numbers are the sequence 1, 2, 3, …, N. By initializing a running total sum to zero and then iteratively adding each integer from 1 up to N,
we accumulate the desired sum without relying on the closed‐form formula.

#include <stdio.h>
int main() {
int n, sum = 0;

51/168
6/23/25, 3:18 PM C PROGRAM CLG

printf("Enter N: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
sum += i;
printf("Sum = %d\n", sum);
return 0;
}

Flow of the Code:

1. Prompt the user for n and store their input; initialize sum = 0 to prepare for accumulation.

2. Enter a for loop where i runs from 1 to n , inclusive, adding each i to sum .

3. After the loop completes, sum holds the total of all integers from 1 to n .

4. Print the value of sum and return 0 to end the program successfully.

Input–Output Mapping:

Input ( n ) Output

5 Sum = 15

10 Sum = 55

2.2 Factorial

52/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Write a program to calculate the factorial of a given number using a while loop.

Approach & Mathematical Concept:


The factorial of a non‐negative integer n (written n! ) is the product of all positive integers up to n . By initializing a product variable and then
repeatedly multiplying by the current value of n while decrementing n until it reaches 1, we compute the factorial iteratively.

#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter number: ");
scanf("%d", &n);
while (n > 1)
fact *= n--;
printf("Factorial = %d\n", fact);
return 0;
}

Flow of the Code:

1. Read the integer n from the user and initialize fact = 1 as the running product.

2. Enter the while loop, which continues as long as n is greater than 1.

3. In each iteration, multiply fact by n and then decrement n by 1.

4. When n reaches 1, exit the loop and print the final value of fact .

Input–Output Mapping:

53/168
6/23/25, 3:18 PM C PROGRAM CLG

Input ( n ) Output

4 Factorial = 24

6 Factorial = 720

2.3 Fibonacci Series

Statement:
Generate the first N terms of the Fibonacci sequence using a do-while loop.

Approach & Mathematical Concept:


The Fibonacci sequence starts with 0 and 1, and each subsequent term is the sum of the two preceding terms. A do-while loop allows us to print
the first two terms explicitly and then continue generating terms until we have printed N in total.

#include <stdio.h>
int main() {
int n, a = 0, b = 1, c, count = 2;
printf("Enter N: ");
scanf("%d", &n);
if (n >= 1) printf("%d ", a);
if (n >= 2) printf("%d ", b);
do {
c = a + b;
printf("%d ", c);

54/168
6/23/25, 3:18 PM C PROGRAM CLG

a = b;
b = c;
count++;
} while (count < n);
printf("\n");
return 0;
}

Flow of the Code:

1. Read n and print 0 and 1 if n is at least 1 and 2, respectively; initialize count = 2 .

2. Enter the do-while loop to generate terms until count equals n .

3. Compute the next term c = a + b , print it, and then shift a = b and b = c .

4. Increment count each iteration; when count reaches n , exit and end the program.

Input–Output Mapping:

Input ( n ) Output

5 01123

7 0112358

2.4 Prime Number Check

55/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Determine if a given number is prime using a loop.

Approach & Mathematical Concept:


A prime number greater than 1 has no positive divisors other than 1 and itself. We test divisibility by every integer from 2 up to √n (or up to n−1
for simplicity) and flag it as non‐prime if any division yields zero remainder.

#include <stdio.h>
#include <math.h>
int main() {
int n, isPrime = 1;
printf("Enter number: ");
scanf("%d", &n);
if (n <= 1) isPrime = 0;
for (int i = 2; i <= sqrt(n) && isPrime; i++) {
if (n % i == 0)
isPrime = 0;
}
printf("%s\n", isPrime ? "Prime" : "Not Prime");
return 0;
}

Flow of the Code:

1. Read n and set isPrime = 1 , then immediately mark non‐prime if n ≤ 1 .

2. Loop i from 2 up to √n , stopping early if a divisor is found.

56/168
6/23/25, 3:18 PM C PROGRAM CLG

3. If n % i == 0 at any point, set isPrime = 0 and break out of the loop.

4. After the loop, print “Prime” if isPrime remains 1; otherwise print “Not Prime.”

Input–Output Mapping:

Input ( n ) Output

7 Prime

12 Not Prime

2.5 Palindrome Check

Statement:
Check if a given number (or string) is a palindrome.

Approach & Mathematical Concept:


For numbers, reverse the digits and compare with the original. If they match exactly, the number is a palindrome. (The same logic can be extended
to strings by comparing characters from ends.)

#include <stdio.h>
int main() {
int n, rev = 0, temp;
printf("Enter number: ");
scanf("%d", &n);

57/168
6/23/25, 3:18 PM C PROGRAM CLG

temp = n;
while (temp != 0) {
rev = rev * 10 + temp % 10;
temp /= 10;
}
printf("%s\n", (rev == n) ? "Palindrome" : "Not Palindrome");
return 0;
}

Flow of the Code:

1. Read n into both n and temp , initialize rev = 0 .

2. In a while loop, extract the last digit of temp and append it to rev , then remove the last digit.

3. Continue until temp reaches zero, at which point rev holds the reversed number.

4. Compare rev to the original n ; print the result accordingly.

Input–Output Mapping:

Input Output

121 Palindrome

123 Not Palindrome

2.6 Reverse a Number

58/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Given a number n , reverse its digits using a for loop.

Approach & Mathematical Concept:


Extract each digit from the end using the modulo operator, then build the reversed number by shifting existing reversed digits left (multiply by 10)
and adding the new digit.

#include <stdio.h>
int main() {
int n, rev = 0;
printf("Enter number: ");
scanf("%d", &n);
for (; n != 0; n /= 10)
rev = rev * 10 + n % 10;
printf("Reversed = %d\n", rev);
return 0;
}

Flow of the Code:

1. Read n and initialize rev = 0 .

2. In the for loop header, check n != 0 , then extract the last digit with n % 10 and append it to rev .

3. Remove the last digit of n by performing integer division by 10.

4. After the loop finishes, rev contains the fully reversed number; print it.

Input–Output Mapping:

59/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

1234 Reversed = 4321

560 Reversed = 65

2.7 Count Even and Odd Digits

Statement:
Given a number, count how many of its digits are even and how many are odd.

Approach & Mathematical Concept:


Extract each digit using modulus division. Check parity of each digit via % 2 ; increment the corresponding counter.

#include <stdio.h>
int main() {
int n, even = 0, odd = 0, digit;
printf("Enter number: ");
scanf("%d", &n);
while (n != 0) {
digit = n % 10;
if (digit % 2 == 0)
even++;
else
odd++;

60/168
6/23/25, 3:18 PM C PROGRAM CLG

n /= 10;
}
printf("Even = %d, Odd = %d\n", even, odd);
return 0;
}

Flow of the Code:

1. Read n , initialize even and odd counters to zero.

2. While n is nonzero, extract the last digit and test its parity.

3. Increment even if the digit is divisible by 2; otherwise increment odd .

4. Remove the last digit from n and repeat until all digits are processed, then print the counts.

Input–Output Mapping:

Input Output

123456 Even = 3, Odd = 3

2023 Even = 2, Odd = 2

2.8 Check for Harshad Number

Statement:
Check whether a number is a Harshad (Niven) number—that is, divisible by the sum of its digits.

61/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Mathematical Concept:


Compute the sum of digits via repetitive modulus and division. Then test whether the original number modulo this sum equals zero.

#include <stdio.h>
int main() {
int n, sum = 0, temp;
printf("Enter number: ");
scanf("%d", &n);
temp = n;
while (temp != 0) {
sum += temp % 10;
temp /= 10;
}
printf("%s\n", (n % sum == 0) ? "Harshad" : "Not Harshad");
return 0;
}

Flow of the Code:

1. Read n , copy it to temp , and initialize sum = 0 .

2. In a loop, add the last digit of temp to sum and then remove that digit.

3. Once all digits are summed, check if n % sum == 0 .

4. Print “Harshad” if the condition is true; otherwise print “Not Harshad.”

Input–Output Mapping:

62/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

18 Harshad

19 Not Harshad

3.1 Square Star Pattern


Write a program to print a square pattern of stars.
Input: n = 5 Output:
*****
*****
*****
*****
*****
3.2 Right-Angled Triangle (Left-Aligned)
Write a program to print a left-aligned right-angled triangle pattern.
Input: n = 5 Output:
*
**
***
****
*****
3.3 Right-Angled Triangle (Right-Aligned)
Write a program to print a right-aligned right-angled triangle pattern.
Input: n = 5 Output:
*
**

63/168
6/23/25, 3:18 PM C PROGRAM CLG

***
****
*****
3.4 Inverted Right-Angled Triangle (Left-Aligned)
Write a program to print an inverted left-aligned right-angled triangle pattern.
Input: n = 5 Output:
*****
****
***
**
*
3.5 Hollow Square Pattern
Write a program to print a hollow square pattern.
Input: n = 5 Output:
*****
* *
* *
* *
*****
3.6 Number Pyramid
Write a program to print a pyramid pattern with numbers.
Input: n = 5 Output:
1
121
12321
1234321
123454321
3.7 Diamond Pattern
Write a program to print a diamond pattern.

64/168
6/23/25, 3:18 PM C PROGRAM CLG

Input: n = 5 Output:
*
***
*****
*******
*********
*******
*****
***
*
3.8 Pascal's Triangle
Write a program to print Pascal's Triangle.
Input: n = 5 Output:
1
11
121
1331
14641
3.9 Zig-Zag Pattern
Write a program to print a zig-zag pattern.
Input: n = 5 Output:
* * *
******
* * *

🖨️ Practical 3: Pattern Printing


Each program below follows the same structure:

65/168
6/23/25, 3:18 PM C PROGRAM CLG

Problem Statement

Approach & Concept

Minimal C Code

Step-by-Step Flow Explanation (each point = 2 sentences)

Input–Output Mapping

3.1 Square Star Pattern


Statement:
Print a solid square of n×n stars.

Approach & Concept:


Use a nested loop: the outer loop for each row (1 to n ), and the inner loop to print n stars per row.

#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int

66/168
6/23/25, 3:18 PM C PROGRAM CLG

3.1 Square Star Pattern


Write a program to print a square pattern of stars.
Input: n = 5 Output:
*****
*****
*****
*****
*****
3.2 Right-Angled Triangle (Left-Aligned)
Write a program to print a left-aligned right-angled triangle pattern.
Input: n = 5 Output:
*
**
***
****
*****
3.3 Right-Angled Triangle (Right-Aligned)
Write a program to print a right-aligned right-angled triangle pattern.
Input: n = 5 Output:
*
**
***
****
*****
3.4 Inverted Right-Angled Triangle (Left-Aligned)
Write a program to print an inverted left-aligned right-angled triangle pattern.
Input: n = 5 Output:
*****

67/168
6/23/25, 3:18 PM C PROGRAM CLG

****
***
**
*
3.5 Hollow Square Pattern
Write a program to print a hollow square pattern.
Input: n = 5 Output:
*****
* *
* *
* *
*****
3.6 Number Pyramid
Write a program to print a pyramid pattern with numbers.
Input: n = 5 Output:
1
121
12321
1234321
123454321
3.7 Diamond Pattern
Write a program to print a diamond pattern.
Input: n = 5 Output:
*
***
*****
*******
*********
*******

68/168
6/23/25, 3:18 PM C PROGRAM CLG

*****
***
*
3.8 Pascal's Triangle
Write a program to print Pascal's Triangle.
Input: n = 5 Output:
1
11
121
1331
14641
3.9 Zig-Zag Pattern
Write a program to print a zig-zag pattern.
Input: n = 5 Output:
* * *
******
* * *
DO AS DONE PREVIUOUSLY BUT ADD THE COMMENT ON THE TOP OF CODE BY STAING THE
BRIEF PUROSE OF CODE FROM HERE AND PRINT THE INPUT OUTPUT COLUMN AS USUAL

🖨️ Practical 3: Pattern Printing


Each example below follows this structure:

Problem Statement

Approach & Concept

Minimal C Code (with a top‐of‐file comment stating its purpose)

69/168
6/23/25, 3:18 PM C PROGRAM CLG

Step-by-Step Flow Explanation (each point in 2 sentences)

Input–Output Mapping

3.1 Square Star Pattern


Statement:
Print a solid square of stars of size n × n .

Approach & Concept:


Use a nested loop: the outer loop iterates over each of the n rows, and the inner loop prints n stars in that row, forming a square.

// Program to print a solid n×n square of stars


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
printf("*");
printf("\n");
}
return 0;
}

70/168
6/23/25, 3:18 PM C PROGRAM CLG

Flow of the Code:

1. Read n from the user to determine the square’s dimensions, then enter the outer loop which runs n times.

2. In each outer iteration, the inner loop prints n stars consecutively, creating one full row of the square.

3. After the inner loop finishes, printf("\n") moves to the next line for the following row.

4. The process repeats until all n rows are printed, yielding the solid square pattern.

Input–Output Mapping:

Input ( n ) Output

3 <br>
***

5 <br>
<br>
*****

3.2 Left-Aligned Right-Angled Triangle


Statement:
Print a left-aligned right-angled triangle of height n .

Approach & Concept:


Use a nested loop: the outer loop runs from row 1 to n , and the inner loop prints as many stars as the current row number.

71/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to print a left-aligned right-angled triangle of height n


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= i; j++)
printf("*");
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n for the triangle’s height and start the outer loop from 1 up to n .

2. For each row i , the inner loop prints i stars, building the increasing left-aligned shape.

3. After printing the stars for a row, a newline moves to the next row.

4. Continue until the outer loop completes n iterations, resulting in the full triangle.

Input–Output Mapping:

Input ( n ) Output

4 <br><br>
****

72/168
6/23/25, 3:18 PM C PROGRAM CLG

Input ( n ) Output

5 <br><br>
****
*****

3.3 Right-Aligned Right-Angled Triangle


Statement:
Print a right-aligned right-angled triangle of height n .

Approach & Concept:


For each row i , first print (n–i) spaces, then print i stars. Two nested loops achieve this alignment.

// Program to print a right-aligned right-angled triangle of height n


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
for(int s = 1; s <= n - i; s++)
printf(" ");
for(int j = 1; j <= i; j++)

73/168
6/23/25, 3:18 PM C PROGRAM CLG

printf("*");
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n and iterate row index i from 1 to n .

2. In each row, the first inner loop prints (n–i) spaces to push the stars to the right.

3. The second inner loop prints i stars, forming the right-angled side.

4. A newline closes the row, and the process repeats until the triangle is complete.

Input–Output Mapping:

Input ( n ) Output

5 *
**
***
****
*****

3.4 Inverted Left-Aligned Triangle

74/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Print an inverted left-aligned right-angled triangle of height n .

Approach & Concept:


Start with n stars on the first row and decrease the star count by one each subsequent row using a nested loop.

// Program to print an inverted left-aligned right-angled triangle of height n


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = n; i >= 1; i--) {
for(int j = 1; j <= i; j++)
printf("*");
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n and set the outer loop to decrement i from n down to 1.

2. In each iteration, the inner loop prints i stars, starting with the maximum count.

3. After printing each row’s stars, a newline moves to the next shorter row.

4. Continue until i reaches 1, producing the inverted triangle shape.

75/168
6/23/25, 3:18 PM C PROGRAM CLG

Input–Output Mapping:

Input ( n ) Output

5 ****<br><br>*<br><br>

3.5 Hollow Square Pattern


Statement:
Print a hollow square of stars of size n × n .

Approach & Concept:


Print stars on the first and last row fully. For intermediate rows, print a star at the first and last column and spaces in between.

// Program to print a hollow n×n square of stars


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(i == 1 || i == n || j == 1 || j == n)
printf("*");
else

76/168
6/23/25, 3:18 PM C PROGRAM CLG

printf(" ");
}
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n and loop i from 1 to n for each square row.

2. In each row, loop j from 1 to n and print a star if on a border (first/last row or column).

3. Otherwise, print a space to hollow out the interior.

4. After each row, print a newline until the square is complete.

Input–Output Mapping:

Input ( n ) Output

4 <br> <br> <br>

5 <br> <br> <br> <br>

3.6 Number Pyramid

77/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Print a centered number pyramid of height n , where each row i shows numbers from 1 up to i and back down to 1.

Approach & Concept:


First, print (n–i) spaces to center the row. Then print ascending numbers from 1 to i , followed by descending numbers from i–1 back to 1.

// Program to print a centered number pyramid of height n


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
for(int s = 1; s <= n - i; s++)
printf(" ");
for(int j = 1; j <= i; j++)
printf("%d", j);
for(int j = i - 1; j >= 1; j--)
printf("%d", j);
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n and loop i from 1 to n .

78/168
6/23/25, 3:18 PM C PROGRAM CLG

2. Print (n–i) spaces to center the pyramid row.

3. Print ascending numbers 1 through i then descending i–1 through 1 .

4. End the row with a newline and repeat until the full pyramid is printed.

Input–Output Mapping:

Input ( n ) Output

4 1
121
12321
1234321

5 1
121
12321
1234321
123454321

3.7 Diamond Pattern


Statement:
Print a diamond of stars, with the top half increasing from 1 to n stars (odd counts) and the bottom half mirroring it.

Approach & Concept:


Construct the upper half as a centered pyramid of odd‐length star rows, then the lower half by reversing that logic.

79/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to print a diamond pattern of height 2n-1


#include <stdio.h>
int main() {
int n, stars;
printf("Enter n: ");
scanf("%d", &n);
// upper half
for(int i = 1; i <= n; i++) {
for(int s = 1; s <= n - i; s++) printf(" ");
stars = 2 * i - 1;
for(int j = 1; j <= stars; j++) printf("*");
printf("\n");
}
// lower half
for(int i = n - 1; i >= 1; i--) {
for(int s = 1; s <= n - i; s++) printf(" ");
stars = 2 * i - 1;
for(int j = 1; j <= stars; j++) printf("*");
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n to define the diamond’s middle width, then print the top half: rows 1 to n , each centered with n–i spaces.

80/168
6/23/25, 3:18 PM C PROGRAM CLG

2. For each of these rows, print 2*i–1 stars to form the growing diamond top.

3. Then print the bottom half by looping i from n–1 down to 1, again centering with spaces and printing 2*i–1 stars.

4. Newlines after each row ensure proper stacking of the diamond shape.

Input–Output Mapping:

Input ( n ) Output

4 *
***
*****
*******
*****
***
*

5 *
***
*****
*******
*********
*******
*****
***
*

81/168
6/23/25, 3:18 PM C PROGRAM CLG

3.8 Pascal’s Triangle


Statement:
Print the first n rows of Pascal’s Triangle.

Approach & Concept:


Each entry is the sum of the two directly above it. Use a 2D array (or compute row on the fly) to store and print successive rows.

// Program to print the first n rows of Pascal's Triangle


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
int C;
for(int i = 0; i < n; i++) {
C = 1;
for(int j = 0; j <= i; j++) {
printf("%d ", C);
C = C * (i - j) / (j + 1);
}
printf("\n");
}
return 0;
}

Flow of the Code:

82/168
6/23/25, 3:18 PM C PROGRAM CLG

1. Read n for the number of rows.

2. For each row i , initialize the binomial coefficient variable C = 1 .

3. Loop j from 0 to i , print C , then update C = C * (i–j)/(j+1) to get the next coefficient.

4. After each row, print a newline to move to the next line of the triangle.

Input–Output Mapping:

Input ( n ) Output

4 1
11
121
1331

5 1
11
121
1331
14641

3.9 Zig-Zag Pattern


Statement:
Print a zig-zag pattern of stars over three rows for input n , creating a slanted wave.

83/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Concept:


We use three rows and 2*n+1 columns. Place stars at positions where (i == 1 && j % 4 == 1) , (i == 2 && j % 2 == 0) , or (i == 3 && j % 4
== 3) , and spaces elsewhere.

// Program to print a zig-zag pattern of width 2n+1 over 3 rows


#include <stdio.h>
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 2 * n + 1; j++) {
if ((i == 1 && j % 4 == 1) ||
(i == 2 && j % 2 == 0) ||
(i == 3 && j % 4 == 3))
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}

Flow of the Code:

1. Read n and determine the total columns as 2*n+1 .

84/168
6/23/25, 3:18 PM C PROGRAM CLG

2. Loop over three rows ( i = 1 to 3 ) and for each row loop columns j = 1 to 2*n+1 .

3. Use conditional tests on (i, j) to decide star placement: odd-column stars on row 1, every even column on row 2, and columns congruent
to 3 mod 4 on row 3.

4. Print a star or space accordingly, then newline after each row to complete the zig-zag.

Input–Output Mapping:

Input ( n ) Output

5 ***
*****
***

4 ****
******
***

Feel free to ask for any further refinements or additional patterns!

2/2

Practical 4: Arrays
4.1 Second Largest Element
Find the second largest element from an array.
4.2 Sorting an Array

85/168
6/23/25, 3:18 PM C PROGRAM CLG

Write a program to sort an array in ascending order.


4.3 Reverse an Array
Write a program to reverse the elements of an array.
4.4 Array Rotation
Write a C program to rotate an array left or right by K positions.
4.5 Element Frequency
Write a program to count the occurrences of each element in an array and display the
frequency. FOLLOW THE PREVIOUS INSTRUCTIONS

🗂️ Practical 4: Arrays
Each program below follows our standard structure:

Problem Statement

Approach & Concept

Minimal C Code (with a top‐of‐file comment stating its purpose)

Step-by-Step Flow Explanation (each point in 2 sentences)

Input–Output Mapping

4.1 Second Largest Element


Statement:
Find the second largest element in an integer array.

86/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Concept:


Traverse the array once, tracking both the largest and second largest values. Whenever you find a new maximum, shift the old maximum into
second place; if you find a value between them, update the second largest.

// Program to find the second largest element in an array


#include <stdio.h>
int main() {
int n;
printf("Enter array size: "); scanf("%d", &n);
int a[n];
printf("Enter %d elements: ", n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
int max = a[0], second = a[0];
for(int i = 1; i < n; i++) {
if(a[i] > max) {
second = max;
max = a[i];
} else if(a[i] > second && a[i] != max) {
second = a[i];
}
}
printf("Second largest = %d\n", second);
return 0;
}

Flow of the Code:

87/168
6/23/25, 3:18 PM C PROGRAM CLG

1. Read the array size n and then read the n elements into a[] , initializing max and second to the first element.

2. Loop from index 1 to n-1 ; if a[i] exceeds max , assign second = max then max = a[i] .

3. Otherwise, if a[i] is between max and second (and not equal to max ), update second = a[i] .

4. After the loop, second holds the second largest element; print it.

Input–Output Mapping:

Input Array Output

[3, 5, 2, 9, 7] Second largest = 7

[10, 10, 9, 8, 10] Second largest = 9

4.2 Sorting an Array


Statement:
Sort an array of integers in ascending order.

Approach & Concept:


Use a simple selection sort: for each position i , find the minimum element in the subarray from i to end and swap it into place.

// Program to sort an integer array in ascending order


#include <stdio.h>
int main() {

88/168
6/23/25, 3:18 PM C PROGRAM CLG

int n;
printf("Enter array size: "); scanf("%d", &n);
int a[n], temp;
printf("Enter %d elements: ", n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
for(int i = 0; i < n - 1; i++) {
int min = i;
for(int j = i + 1; j < n; j++)
if(a[j] < a[min]) min = j;
temp = a[i]; a[i] = a[min]; a[min] = temp;
}
printf("Sorted: ");
for(int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}

Flow of the Code:

1. Read n and array elements into a[] .

2. For each index i from 0 to n-2 , assume a[i] is minimum and search the remainder of the array for a smaller element.

3. When a smaller element at min is found, swap a[i] and a[min] .

4. After all passes, the array is sorted; print its contents.

Input–Output Mapping:

89/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Array Output

[3, 1, 4, 2] Sorted: 1 2 3 4

[5, 5, 2, 8, 0] Sorted: 0 2 5 5 8

4.3 Reverse an Array


Statement:
Reverse the elements of an integer array in place.

Approach & Concept:


Swap the first and last element, second and second‐last, and so on, meeting in the middle. A two‐pointer approach accomplishes this in one pass.

// Program to reverse the elements of an array


#include <stdio.h>
int main() {
int n;
printf("Enter array size: "); scanf("%d", &n);
int a[n], temp;
printf("Enter %d elements: ", n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
for(int i = 0; i < n/2; i++) {
temp = a[i];
a[i] = a[n-1-i];

90/168
6/23/25, 3:18 PM C PROGRAM CLG

a[n-1-i] = temp;
}
printf("Reversed: ");
for(int i = 0; i < n; i++) printf("%d ", a[i]);
printf("\n");
return 0;
}

Flow of the Code:

1. Read n and store the array elements in a[] .

2. Initialize a loop from i=0 up to n/2 - 1 ; in each iteration, swap a[i] with a[n-1-i] .

3. This exchange moves elements from ends toward the center, reversing the array in place.

4. After completing swaps, print the reversed array.

Input–Output Mapping:

Input Array Output

[1, 2, 3, 4, 5] Reversed: 5 4 3 2 1

[10, 20, 30] Reversed: 30 20 10

4.4 Array Rotation by K Positions

91/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Rotate an array left or right by K positions.

Approach & Concept:


Normalize K modulo n . For left rotation, shift elements to the left one by one or copy into a temporary array. Here we’ll use a temporary array
to rearrange in one pass.

// Program to rotate an array left or right by K positions


#include <stdio.h>
#include <string.h>
int main() {
int n, k; char dir;
printf("Enter array size: "); scanf("%d", &n);
int a[n], b[n];
printf("Enter %d elements: ", n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("Rotate (L/R)? "); scanf(" %c", &dir);
printf("Enter K: "); scanf("%d", &k);
k %= n;
for(int i = 0; i < n; i++) {
int idx = (dir=='L') ? (i + k) % n : (i - k + n) % n;
b[idx] = a[i];
}
printf("Rotated: ");
for(int i = 0; i < n; i++) printf("%d ", b[i]);
printf("\n");

92/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. Read n , the n elements into a[] , then read direction dir ( L or R ) and rotation count k , reducing k modulo n .

2. For each original index i , compute its new index idx : for left rotation use (i + k) % n ; for right use (i - k + n) % n .

3. Copy a[i] into b[idx] to form the rotated array in one pass.

4. Print b[] , which now represents the array rotated by k positions in the chosen direction.

Input–Output Mapping:

Input Output

[1,2,3,4,5], L, k=2 Rotated: 3 4 5 1 2

[10,20,30,40], R, k=1 Rotated: 40 10 20 30

4.5 Element Frequency


Statement:
Count the occurrences of each element in an integer array and display their frequencies.

Approach & Concept:


Use two loops: for each element, if it hasn’t been counted before, scan the rest of the array to count matches. Mark counted elements to skip

93/168
6/23/25, 3:18 PM C PROGRAM CLG

duplicates.

// Program to count frequency of each element in an array


#include <stdio.h>
#define VISITED -1
int main() {
int n;
printf("Enter array size: "); scanf("%d", &n);
int a[n], freq[n];
printf("Enter %d elements: ", n);
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
freq[i] = 0;
}
for(int i = 0; i < n; i++) {
if(freq[i] == VISITED) continue;
int count = 1;
for(int j = i + 1; j < n; j++) {
if(a[i] == a[j]) {
count++;
freq[j] = VISITED;
}
}
freq[i] = count;
}
printf("Element : Frequency\n");
for(int i = 0; i < n; i++) {

94/168
6/23/25, 3:18 PM C PROGRAM CLG

if(freq[i] != VISITED)
printf("%d : %d\n", a[i], freq[i]);
}
return 0;
}

Flow of the Code:

1. Read n and the elements into a[] , initializing freq[] to zero.

2. For each index i , if freq[i] is not VISITED , count how many times a[i] appears by scanning j=i+1 to n-1 , marking duplicates as
VISITED .

3. Store the total count in freq[i] once scanning completes, then skip over any visited duplicates.

4. Finally, print each element alongside its frequency for those indices not marked visited.

Input–Output Mapping:

Input Array Output

[2, 3, 2, 4, 3, 2] 2:3
3:2
4:1

[5, 5, 5] 5:3

Let me know if you want any of these bundled into a single document or if you need more examples!

95/168
6/23/25, 3:18 PM C PROGRAM CLG

Practical 5: Strings
5.1 String Length Calculation
Write a program to calculate the length of a given string without using the built-in strlen()
function.
5.2 String Reversal
Create a program that takes a string as input and prints its reverse.
5.3 Vowel and Consonant Counter
Develop a program to count the number of vowels and consonants in a given string.
5.4 String Concatenation Without Built-in Functions
Write a program that concatenates two strings without using the built-in strcat() function.
5.5 Remove Duplicate Characters
Write a program to remove all duplicate characters from a string.
Example:
• "programming" → "progamin"
5.6 Sort a String Alphabetically
Develop a program that sorts the characters of a string in alphabetical order.
5.7 Toggle Case of Each Character
Write a C program that toggles the case of each character in a string (uppercase becomes
lowercase and vice versa).
5.8 Reverse a String Using Recursion
Write a recursive function to reverse a string.
Example Input/Output:
• Enter a string: hello
• Reversed string: olleh
5.9 Count Vowels, Consonants, Digits, and Special Characters
Write a program with separate functions to count vowels, consonants, digits, and special

96/168
6/23/25, 3:18 PM C PROGRAM CLG

characters in a string.
Example Input/Output:
• Enter a string: Hello@123
• Vowels: 2
• Consonants: 3
• Digits: 3
• Special characters: 1

📝 Practical 5: Strings
Each program follows our structured format:

Problem Statement

Approach & Concept

Minimal C Code (with a top‐of‐file comment stating its purpose)

Step-by-Step Flow Explanation (each point in 2 sentences)

Input–Output Mapping

5.1 String Length Calculation


Statement:
Calculate the length of a given string without using strlen() .

Approach & Concept:


Traverse the character array until the null terminator '\0' is encountered. Count each character in a counter as you go.

97/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to calculate the length of a string without strlen()


#include <stdio.h>
int main() {
char s[100];
int len = 0;
printf("Enter string: ");
scanf("%[^\n]", s);
while (s[len] != '\0')
len++;
printf("Length = %d\n", len);
return 0;
}

Flow of the Code:

1. Read the input string (including spaces) into s[] and initialize len = 0 .

2. Enter a while loop that checks if s[len] is not the null terminator.

3. In each iteration, increment len to count the current character.

4. Once s[len] == '\0' , exit the loop and print len .

Input–Output Mapping:

Input Output

hello Length = 5

98/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

CS Workshop Length = 12

5.2 String Reversal


Statement:
Take a string as input and print its reverse.

Approach & Concept:


First find the string’s length, then swap characters from the ends moving toward the center. This in-place approach uses two pointers.

// Program to reverse a string in place


#include <stdio.h>
int main() {
char s[100];
printf("Enter string: ");
scanf("%[^\n]", s);
int i = 0, j, temp;
while (s[i] != '\0') i++;
j = i - 1;
for (i = 0; i < j; i++, j--) {
temp = s[i];
s[i] = s[j];

99/168
6/23/25, 3:18 PM C PROGRAM CLG

s[j] = temp;
}
printf("Reversed = %s\n", s);
return 0;
}

Flow of the Code:

1. Read the full line into s[] , then compute its length by advancing i until s[i] == '\0' .

2. Set j = i - 1 to point at the last character index.

3. In a for loop, swap s[i] and s[j] , then increment i and decrement j to move inward.

4. When i >= j , all characters have been swapped; print the reversed string.

Input–Output Mapping:

Input Output

hello Reversed = olleh

abcd Reversed = dcba

5.3 Vowel and Consonant Counter


Statement:
Count the number of vowels and consonants in a given string.

100/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Concept:


Iterate through each character; if it’s an alphabet letter, check membership in the vowel set {a,e,i,o,u} in either case. Increment vowel or
consonant counters accordingly.

// Program to count vowels and consonants in a string


#include <stdio.h>
#include <ctype.h>
int main() {
char s[100];
int v = 0, c = 0, i = 0;
printf("Enter string: ");
scanf("%[^\n]", s);
while (s[i] != '\0') {
if (isalpha(s[i])) {
char ch = tolower(s[i]);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') v++;
else c++;
}
i++;
}
printf("Vowels = %d, Consonants = %d\n", v, c);
return 0;
}

Flow of the Code:

1. Read the input line into s[] , initialize counters v = 0 , c = 0 , and index i = 0 .

101/168
6/23/25, 3:18 PM C PROGRAM CLG

2. Loop until s[i] == '\0' ; for each character, check if it’s alphabetic using isalpha() .

3. If it is, convert to lowercase and test if it’s a vowel; increment v if so, otherwise increment c .

4. After processing all characters, print the vowel and consonant counts.

Input–Output Mapping:

Input Output

HelloWorld Vowels = 3, Consonants = 7

CS101! Vowels = 0, Consonants = 2

5.4 String Concatenation Without strcat()


Statement:
Concatenate two strings without using strcat() .

Approach & Concept:


Copy the first string into a result buffer, then append the second string starting at the first’s null terminator. This manual approach mimics
strcat() .

// Program to concatenate two strings without strcat()


#include <stdio.h>
int main() {

102/168
6/23/25, 3:18 PM C PROGRAM CLG

char s1[100], s2[100], res[200];


int i = 0, j = 0;
printf("Enter first string: "); scanf("%[^\n]", s1);
getchar();
printf("Enter second string: "); scanf("%[^\n]", s2);
while (s1[i] != '\0') {
res[i] = s1[i];
i++;
}
while (s2[j] != '\0') {
res[i++] = s2[j++];
}
res[i] = '\0';
printf("Concatenated = %s\n", res);
return 0;
}

Flow of the Code:

1. Read s1 and s2 (with getchar() to clear the newline), and initialize indices i = 0 , j = 0 .

2. Copy characters from s1[] to res[] until the null terminator, incrementing i .

3. Then copy characters from s2[] to res[] starting at index i , incrementing both i and j .

4. Null-terminate res[] and print the concatenated result.

Input–Output Mapping:

103/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

Hello , World Concatenated = HelloWorld

CS , Workshop Concatenated = CS Workshop

5.5 Remove Duplicate Characters


Statement:
Remove all duplicate characters from a string, preserving first occurrences.

Approach & Concept:


Iterate input characters and build an output buffer, checking each new character against those already in the output. Only append if it hasn’t
appeared before.

// Program to remove duplicate characters from a string


#include <stdio.h>
int main() {
char s[100], res[100];
int i = 0, k = 0, j;
printf("Enter string: ");
scanf("%[^\n]", s);
while (s[i] != '\0') {
for (j = 0; j < k; j++)

104/168
6/23/25, 3:18 PM C PROGRAM CLG

if (res[j] == s[i]) break;


if (j == k) // not found in res
res[k++] = s[i];
i++;
}
res[k] = '\0';
printf("After removal = %s\n", res);
return 0;
}

Flow of the Code:

1. Read s[] , initialize indices i = 0 , k = 0 .

2. For each s[i] , loop j from 0 to k−1 to see if res[j] == s[i] .

3. If not found ( j == k ), append s[i] to res[k] and increment k .

4. After processing all input, null-terminate res[] and print it.

Input–Output Mapping:

Input Output

programming progamin

aabbcc abc

105/168
6/23/25, 3:18 PM C PROGRAM CLG

5.6 Sort a String Alphabetically


Statement:
Sort the characters of a string in ascending (alphabetical) order.

Approach & Concept:


Use a simple selection sort on the character array, swapping the smallest remaining character into each position sequentially.

// Program to sort characters of a string alphabetically


#include <stdio.h>
int main() {
char s[100], temp;
int n, i, j;
printf("Enter string: ");
scanf("%[^\n]", s);
for (n = 0; s[n] != '\0'; n++);
for (i = 0; i < n - 1; i++) {
int min = i;
for (j = i + 1; j < n; j++)
if (s[j] < s[min]) min = j;
temp = s[i]; s[i] = s[min]; s[min] = temp;
}
printf("Sorted = %s\n", s);
return 0;
}

Flow of the Code:

106/168
6/23/25, 3:18 PM C PROGRAM CLG

1. Read s[] and compute its length n by advancing until s[n] == '\0' .

2. For each index i from 0 to n−2 , find the minimum character in s[i+1..n−1] .

3. Swap s[i] with the minimum found at s[min] .

4. After all positions are fixed, print the sorted string.

Input–Output Mapping:

Input Output

dcba Sorted = abcd

hello Sorted = ehllo

5.7 Toggle Case of Each Character


Statement:
Toggle the case of each alphabetic character in a string (upper→lower, lower→upper).

Approach & Concept:


Traverse the string; for each character, if it’s uppercase use tolower() , if lowercase use toupper() , otherwise leave it unchanged.

// Program to toggle case of alphabetic characters in a string


#include <stdio.h>
#include <ctype.h>

107/168
6/23/25, 3:18 PM C PROGRAM CLG

int main() {
char s[100];
int i = 0;
printf("Enter string: ");
scanf("%[^\n]", s);
while (s[i] != '\0') {
if (islower(s[i])) s[i] = toupper(s[i]);
else if (isupper(s[i])) s[i] = tolower(s[i]);
i++;
}
printf("Toggled = %s\n", s);
return 0;
}

Flow of the Code:

1. Read the input into s[] and set i = 0 .

2. Loop until s[i] == '\0' ; if s[i] is lowercase, convert it to uppercase, and vice versa.

3. Non-alphabetic characters are left as is.

4. After toggling all characters, print the resulting string.

Input–Output Mapping:

Input Output

Hello World Toggled = hELLO wORLD

CS101 Toggled = cs101

108/168
6/23/25, 3:18 PM C PROGRAM CLG

5.8 Reverse a String Using Recursion


Statement:
Implement a recursive function to reverse a string.

Approach & Concept:


Define a function void rev(char *s, int start, int end) that swaps s[start] and s[end] and then recurses with start+1, end−1 until
start >= end .

// Program to reverse a string using recursion


#include <stdio.h>
void rev(char *s, int i, int j) {
if (i >= j) return;
char tmp = s[i];
s[i] = s[j];
s[j] = tmp;
rev(s, i + 1, j - 1);
}
int main() {
char s[100];
printf("Enter string: ");
scanf("%[^\n]", s);
int len = 0;
while (s[len] != '\0') len++;
rev(s, 0, len - 1);
printf("Reversed = %s\n", s);

109/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. Read s[] and compute its length len by iterating until the null terminator.

2. Call rev(s, 0, len-1) ; the base case returns when i >= j .

3. Each recursion swaps the characters at positions i and j , then advances inward.

4. After unwinding the recursion, print the reversed string in main() .

Input–Output Mapping:

Input Output

hello Reversed = olleh

abcde Reversed = edcba

5.9 Count Vowels, Consonants, Digits & Special Characters


Statement:
Write separate functions to count vowels, consonants, digits, and special characters in a string.

Approach & Concept:


Define four functions— countV() , countC() , countD() , countS() —each iterating the string and applying the appropriate test ( isalpha +vowel

110/168
6/23/25, 3:18 PM C PROGRAM CLG

set, isdigit , else) to update its counter.

// Program to count vowels, consonants, digits, and special characters


#include <stdio.h>
#include <ctype.h>

int countV(char *s) {


int i = 0, v = 0;
while (s[i]) {
char ch = tolower(s[i]);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') v++;
i++;
}
return v;
}

int countC(char *s) {


int i = 0, c = 0;
while (s[i]) {
if (isalpha(s[i]) && !strchr("aeiouAEIOU", s[i])) c++;
i++;
}
return c;
}

int countD(char *s) {


int i = 0, d = 0;

111/168
6/23/25, 3:18 PM C PROGRAM CLG

while (s[i]) {
if (isdigit(s[i])) d++;
i++;
}
return d;
}

int countS(char *s) {


int i = 0, sp = 0;
while (s[i]) {
if (!isalnum(s[i]) && !isspace(s[i])) sp++;
i++;
}
return sp;
}

int main() {
char s[100];
printf("Enter string: ");
scanf("%[^\n]", s);
printf("Vowels: %d\n", countV(s));
printf("Consonants: %d\n", countC(s));
printf("Digits: %d\n", countD(s));
printf("Special characters: %d\n", countS(s));
return 0;
}

Flow of the Code:

112/168
6/23/25, 3:18 PM C PROGRAM CLG

1. Each helper function iterates its index i through s[] until it reaches '\0' , applying tolower , isalpha , isdigit , or isalnum/isspace
tests.

2. countV() checks for membership in the vowel set; countC() checks alphabetic non-vowels.

3. countD() uses isdigit() , and countS() counts any non-alphanumeric, non-space characters as special.

4. main() reads the string, then calls each function in turn and prints their returned counts.

Input–Output Mapping:

Input Output

Hello@123 Vowels: 2
Consonants: 3
Digits: 3
Special characters: 1

Let me know if you’d like any additional explanations or examples!

// Program to count vowels, consonants, digits, and special characters


#include <stdio.h>
#include <ctype.h>

int countV(char *s) {


int i = 0, v = 0;

113/168
6/23/25, 3:18 PM C PROGRAM CLG

while (s[i]) {
char ch = tolower(s[i]);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') v++;
i++;
}
return v;
}

int countC(char *s) {


int i = 0, c = 0;
while (s[i]) {
if (isalpha(s[i]) && !strchr("aeiouAEIOU", s[i])) c++;
i++;
}
return c;
}

int countD(char *s) {


int i = 0, d = 0;
while (s[i]) {
if (isdigit(s[i])) d++;
i++;
}
return d;
}

int countS(char *s) {


int i = 0, sp = 0;
while (s[i]) {

114/168
6/23/25, 3:18 PM C PROGRAM CLG

if (!isalnum(s[i]) && !isspace(s[i])) sp++;


i++;
}
return sp;
}

int main() {
char s[100];
printf("Enter string: ");
scanf("%[^\n]", s);
printf("Vowels: %d\n", countV(s));
printf("Consonants: %d\n", countC(s));
printf("Digits: %d\n", countD(s));
printf("Special characters: %d\n", countS(s));
return 0;
} CORRECT IT ITS NOT RUNNING IN PROGRAMIZ C

Here’s a fixed version that compiles cleanly (e.g., on Programiz) and correctly counts each category:

// Program to count vowels, consonants, digits, and special characters


#include <stdio.h>
#include <ctype.h>
#include <string.h> // for strchr()

int countV(char *s) {


int i = 0, v = 0;
while (s[i]) {

115/168
6/23/25, 3:18 PM C PROGRAM CLG

char ch = tolower((unsigned char)s[i]);


if (ch=='a'|| ch=='e'|| ch=='i'|| ch=='o'|| ch=='u')
v++;
i++;
}
return v;
}

int countC(char *s) {


int i = 0, c = 0;
while (s[i]) {
if (isalpha((unsigned char)s[i]) &&
!strchr("aeiouAEIOU", s[i]))
c++;
i++;
}
return c;
}

int countD(char *s) {


int i = 0, d = 0;
while (s[i]) {
if (isdigit((unsigned char)s[i]))
d++;
i++;
}
return d;
}

116/168
6/23/25, 3:18 PM C PROGRAM CLG

int countS(char *s) {


int i = 0, sp = 0;
while (s[i]) {
if (!isalnum((unsigned char)s[i]) && !isspace((unsigned char)s[i]))
sp++;
i++;
}
return sp;
}

int main() {
char s[100];
printf("Enter string: ");
// Use fgets to safely read the whole line (including spaces)
if (!fgets(s, sizeof s, stdin)) return 1;
// Remove trailing newline if present
size_t len = strlen(s);
if (len > 0 && s[len-1] == '\n') s[len-1] = '\0';

printf("Vowels: %d\n", countV(s));


printf("Consonants: %d\n", countC(s));
printf("Digits: %d\n", countD(s));
printf("Special characters: %d\n", countS(s));
return 0;
}

What was fixed:

1. #include <string.h> was missing, so strchr() wasn’t declared.

117/168
6/23/25, 3:18 PM C PROGRAM CLG

2. Switched from scanf("%[^\n]", s) to fgets() for robust line input (handles spaces and avoids scanf pitfalls).

3. Stripped the trailing newline that fgets() may leave.

4. Cast each char through (unsigned char) before ctype.h functions to avoid undefined behavior on negative values.

This will compile and run correctly on Programiz or any standard C99/C11 environment.

Practical 6: Functions
6.1 Check if a Number is Automorphic
Write a function int isAutomorphic(int n) that returns 1 if n is automorphic, otherwise returns 0.
Definition: A number is automorphic if its square ends with the number itself.
Example:
• isAutomorphic(25) → 1 (25^2 = 625 ends with 25)
• isAutomorphic(7) → 0 (7^2 = 49)
6.2 Reverse a Number (Without Recursion or Arrays)
Write a function int reverseNumber(int n) that returns the reversed form of an integer.
Example:
• reverseNumber(1234) → 4321
• reverseNumber(1000) → 1
6.3 Decimal to Binary (Without Arrays or Recursion)
Write a function void decimalToBinary(int n) that prints the binary equivalent of n.
Example:
• decimalToBinary(10) → 1010
• decimalToBinary(7) → 111
6.4 Find Sum of Unique Digits
Write a function int sumOfUniqueDigits(int n) that returns the sum of unique digits in n.
Example:

118/168
6/23/25, 3:18 PM C PROGRAM CLG

• sumOfUniqueDigits(1223445) → 1 + 2 + 3 + 4 + 5 = 15
• sumOfUniqueDigits(98789) → 9 + 8 + 7 = 24
6.5 Find the Sum of First N Natural Numbers Without Using Loops
Write a function int sumOfN(int n) that returns the sum of the first n natural numbers.
Example:
• sumOfN(5) → 15 (1+2+3+4+5)
• sumOfN(10) → 55
6.6 Calculate Factorial Using Recursion
Write a recursive function to calculate the factorial of a given number.
Example Input/Output:
• Enter a number: 5
• Factorial of 5 is: 120
6.7 Sum of Even and Odd Elements in an Array Using Functions
Write functions to calculate and display the sum of even and odd elements in an integer array.
Example Input/Output:
• Enter 5 elements: 1 2 3 4 5
• Sum of even elements: 6
• Sum of odd elements: 9
6.8 Calculate Compound Interest Using Function
Create a function to calculate the compound interest given principal, rate, and time.
Formula: A = P(1 + r/100)^t
Example Input/Output:
• Enter principal, rate, and time: 10000 5 2
• Compound Interest: 1025.00

🔧 Practical 6: Functions
Each problem below follows our format:

119/168
6/23/25, 3:18 PM C PROGRAM CLG

Problem Statement

Approach & Concept

Minimal C Code (with a top‐of‐file comment stating its purpose)

Step-by-Step Flow Explanation (each point = 2 sentences)

Input–Output Mapping

6.1 Check if a Number is Automorphic


Statement:
Write int isAutomorphic(int n) that returns 1 if n is automorphic (its square ends in n ), else 0.

Approach & Concept:


Compute sq = n * n and determine place = 10^d , where d is the number of digits in n . An automorphic number satisfies sq % place == n .

// Program to check if a number is automorphic


#include <stdio.h>

int isAutomorphic(int n) {
int sq = n * n;
int place = 1, temp = n;
while (temp > 0) {
place *= 10;
temp /= 10;

120/168
6/23/25, 3:18 PM C PROGRAM CLG

}
return (sq % place == n) ? 1 : 0;
}

int main() {
int x;
printf("Enter number: ");
scanf("%d", &x);
printf("%d is %sautomorphic\n",
x, isAutomorphic(x) ? "" : "not ");
return 0;
}

Flow of the Code:

1. In isAutomorphic , compute the square sq of n . Then compute place by multiplying 10 once per digit through dividing temp until zero.

2. Finally, test whether the last digits of sq (via sq % place ) equal the original n , returning 1 if true or 0 otherwise.

3. In main , read x , call isAutomorphic(x) , and print either “is automorphic” or “is not automorphic.”

4. Return 0 to signal successful execution.

Input–Output Mapping:

Input Output

25 25 is automorphic

7 7 is not automorphic

121/168
6/23/25, 3:18 PM C PROGRAM CLG

6.2 Reverse a Number (Without Recursion or Arrays)


Statement:
Write int reverseNumber(int n) that returns the reversed integer of n .

Approach & Concept:


Extract digits one by one via n % 10 and build rev = rev * 10 + digit , then remove the last digit by n /= 10 until n is zero.

// Program to reverse an integer without recursion or arrays


#include <stdio.h>

int reverseNumber(int n) {
int rev = 0, d;
while (n != 0) {
d = n % 10;
rev = rev * 10 + d;
n /= 10;
}
return rev;
}

int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);
printf("Reversed = %d\n", reverseNumber(num));

122/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. In reverseNumber , initialize rev = 0 . Extract the last digit d of n and append it to rev , then drop that digit from n .

2. Repeat until n becomes zero; then return the accumulated rev .

3. In main , read the input, call reverseNumber , and print the result.

4. Return 0 for successful termination.

Input–Output Mapping:

Input Output

1234 Reversed = 4321

1000 Reversed = 1

6.3 Decimal to Binary (Without Arrays or Recursion)


Statement:
Write void decimalToBinary(int n) that prints the binary representation of n without using arrays or recursion.

Approach & Concept:


Find the highest power of 2 ≤ n , then for each power downward, print 1 if that bit fits (subtracting it), else print 0 .

123/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to print binary of an integer without arrays or recursion


#include <stdio.h>

void decimalToBinary(int n) {
int mask = 1;
while (mask <= n) mask <<= 1;
mask >>= 1;
while (mask > 0) {
putchar((n & mask) ? '1' : '0');
mask >>= 1;
}
}

int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);
decimalToBinary(num);
putchar('\n');
return 0;
}

Flow of the Code:

1. Initialize mask = 1 and shift left until it exceeds n , then shift back one step to the highest set bit position.

2. Loop while mask > 0 , printing '1' if n & mask is nonzero or '0' otherwise, then shift mask right by one.

3. In main , read the integer, call decimalToBinary , and print a newline.

124/168
6/23/25, 3:18 PM C PROGRAM CLG

4. Return 0 to end the program.

Input–Output Mapping:

Input Output

10 1010

7 111

6.4 Find Sum of Unique Digits


Statement:
Write int sumOfUniqueDigits(int n) that returns the sum of distinct digits in n .

Approach & Concept:


Use an array seen[10] to mark which digits 0–9 have appeared; sum each digit only on its first occurrence.

// Program to sum unique digits of an integer


#include <stdio.h>

int sumOfUniqueDigits(int n) {
int seen[10] = {0}, sum = 0, d;
while (n != 0) {
d = n % 10;

125/168
6/23/25, 3:18 PM C PROGRAM CLG

if (!seen[d]) {
sum += d;
seen[d] = 1;
}
n /= 10;
}
return sum;
}

int main() {
int num;
printf("Enter number: ");
scanf("%d", &num);
printf("Sum of unique digits = %d\n", sumOfUniqueDigits(num));
return 0;
}

Flow of the Code:

1. Initialize a seen array to track digit occurrences and sum = 0 . Extract each digit d .

2. If seen[d] is zero, add d to sum and mark seen[d] = 1 . Remove the digit by n /= 10 .

3. After all digits processed, return sum . In main , read the number, invoke the function, and print the result.

4. Return 0 at end of main .

Input–Output Mapping:

126/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

1223445 Sum of unique digits = 15

98789 Sum of unique digits = 24

6.5 Sum of First N Natural Numbers Without Using Loops


Statement:
Write int sumOfN(int n) that returns 1 + 2 + … + n without loops.

Approach & Concept:


Use the formula n * (n + 1) / 2 to compute the sum directly in constant time.

// Program to sum first N natural numbers without loops


#include <stdio.h>

int sumOfN(int n) {
return n * (n + 1) / 2;
}

int main() {
int n;
printf("Enter N: ");

127/168
6/23/25, 3:18 PM C PROGRAM CLG

scanf("%d", &n);
printf("Sum = %d\n", sumOfN(n));
return 0;
}

Flow of the Code:

1. In sumOfN , apply the closed‐form arithmetic series formula to compute the sum.

2. Return that value directly. In main , read n , call sumOfN , and print the result.

3. No loops are used—just arithmetic.

4. Return 0 to indicate success.

Input–Output Mapping:

Input ( n ) Output

5 Sum = 15

10 Sum = 55

6.6 Calculate Factorial Using Recursion


Statement:
Write a recursive function int factorial(int n) that returns n! .

128/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Concept:


Base case: factorial(0) = 1 . Recursive case: factorial(n) = n * factorial(n–1) for n > 0 .

// Program to compute factorial using recursion


#include <stdio.h>

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

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("Factorial of %d is: %d\n", n, factorial(n));
return 0;
}

Flow of the Code:

1. In factorial , check if n <= 1 ; if so, return 1 as the base case.

2. Otherwise, return n * factorial(n - 1) , letting recursion compute (n–1)! .

3. In main , read n , call factorial(n) , and print the result.

4. Return 0 to finish.

129/168
6/23/25, 3:18 PM C PROGRAM CLG

Input–Output Mapping:

Input Output

5 Factorial of 5 is: 120

0 Factorial of 0 is: 1

6.7 Sum of Even and Odd Elements in an Array Using Functions


Statement:
Write functions to calculate and display the sum of even and odd elements in an integer array.

Approach & Concept:


Define int sumEven(int a[], int n) and int sumOdd(int a[], int n) that iterate once each, accumulating even or odd elements.

// Program to sum even and odd elements of an array


#include <stdio.h>

int sumEven(int a[], int n) {


int s = 0;
for (int i = 0; i < n; i++)
if (a[i] % 2 == 0) s += a[i];
return s;
}

130/168
6/23/25, 3:18 PM C PROGRAM CLG

int sumOdd(int a[], int n) {


int s = 0;
for (int i = 0; i < n; i++)
if (a[i] % 2 != 0) s += a[i];
return s;
}

int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("Sum of even elements: %d\n", sumEven(a, n));
printf("Sum of odd elements: %d\n", sumOdd(a, n));
return 0;
}

Flow of the Code:

1. sumEven loops through a[] , adding a[i] to s if it’s divisible by 2.

2. sumOdd does the same but for elements with a[i] % 2 != 0 .

3. In main , read array size and elements, then call both functions and print their results.

4. Return 0 to signal successful termination.

Input–Output Mapping:

131/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Array Output

[1,2,3,4,5] Sum of even elements: 6


Sum of odd elements: 9

6.8 Calculate Compound Interest Using Function


Statement:
Create double compoundInterest(double P, double r, int t) to compute the interest earned on principal P at rate r% per annum for t years.

Approach & Concept:


Compute the accumulated amount A = P * pow(1 + r/100, t) using math.h , then return the interest A – P .

// Program to calculate compound interest


#include <stdio.h>
#include <math.h>

double compoundInterest(double P, double r, int t) {


double A = P * pow(1 + r/100.0, t);
return A - P;
}

int main() {
double P, r;

132/168
6/23/25, 3:18 PM C PROGRAM CLG

int t;
printf("Enter principal, rate, and time: ");
scanf("%lf %lf %d", &P, &r, &t);
double CI = compoundInterest(P, r, t);
printf("Compound Interest: %.2f\n", CI);
return 0;
}

Flow of the Code:

1. In compoundInterest , compute A using pow(1 + r/100.0, t) , then subtract P to get the interest.

2. Return that interest value. In main , read P , r , and t , call compoundInterest , and print the result with two decimal places.

3. Include <math.h> to use pow() .

4. Return 0 to indicate successful completion.

Input–Output Mapping:

Input Output

10000 5 2 Compound Interest: 1025.00

Let me know if you need further tweaks or additional examples!

1/2

133/168
6/23/25, 3:18 PM C PROGRAM CLG

Practical 7: Pointers
7.1 Swap Elements Using Call by Reference
Write a program in C to swap elements using call by reference.
Test Data:
• Input the value of 1st element: 5
• Input the value of 2nd element: 6
• Input the value of 3rd element: 7
Expected Output:
• The values after swapping are:
• element 1 = 7
• element 2 = 5
• element 3 = 6
7.2 Count Vowels and Consonants Using Pointer
Write a program in C to count the number of vowels and consonants in a string using a pointer.
Test Data:
• Input a string: string
Expected Output:
• Number of vowels: 1
• Number of consonants: 5
7.3 Sort Array Using Pointer
Write a program in C to sort an array using a pointer.
Test Data:
• Input 5 elements: 25 45 89 15 82
Expected Output:
• The elements in the array after sorting:
• 15 25 45 82 89
7.4 Print Array in Reverse Using Pointer
Write a program in C to print the elements of an array in reverse order using a pointer.

134/168
6/23/25, 3:18 PM C PROGRAM CLG

Test Data:
• Input 5 elements: 2 3 4 5 6
Expected Output:
• The elements of array in reverse order are:
• 65432
7.5 Copy One String to Another Using Pointers
Write a program in C to copy one string to another using pointers (without using standard
library functions like strcpy).
Test Data:
• Input a string: hello
Expected Output:
• The original string: hello
• The copied string: hello
7.6 Count Frequency of Each Character in a String Using Pointers
Write a program in C to count the frequency of each character in a string using pointers.
Test Data:
• Input a string: apple
Expected Output:
• Character 'a' = 1 time
• Character 'p' = 2 times
• Character 'l' = 1 time
• Character 'e' = 1 time
7.7 Merge Two Arrays Using Pointers
Write a program in C to merge two arrays into a third array using pointers.
Test Data:
• Input elements of first array: 10 20 30
• Input elements of second array: 40 50
Expected Output:
• The merged array is: 10 20 30 40 50

135/168
6/23/25, 3:18 PM C PROGRAM CLG

7.8 Find Factorial of a Number Using Recursion and Pointer


Write a program in C to find the factorial of a number using recursion and return the result
using a pointer.
Test Data:
• Input a number: 5
Expected Output:
• Factorial of 5 is 120
7.9 Calculate the Average of N Numbers Using Functions and Pointers
Write a program in C to calculate the average of N numbers using pointers and a separate
function.
Test Data:
• Input 4 numbers: 10 20 30 40
Expected Output:
• Average = 25.00

📌 Practical 7: Pointers
Each program follows our standard format:

Problem Statement

Approach & Concept

C Code (with a comment at the top stating its purpose)

Step-by-Step Flow Explanation (each point = 2 sentences)

Input–Output Mapping

136/168
6/23/25, 3:18 PM C PROGRAM CLG

7.1 Swap Three Elements Using Call by Reference


Statement:
Swap three integer variables so that the first becomes the third, the second becomes the first, and the third becomes the second.

Approach & Concept:


Use pointers to the three variables in a function; perform a three-way rotation via a temporary variable, modifying them in place without returning
values.

// Program to swap three elements by reference (rotate values)


#include <stdio.h>
void rotate(int *x, int *y, int *z) {
int temp = *z;
*z = *y;
*y = *x;
*x = temp;
}
int main() {
int a, b, c;
printf("Input the value of 1st element: "); scanf("%d", &a);
printf("Input the value of 2nd element: "); scanf("%d", &b);
printf("Input the value of 3rd element: "); scanf("%d", &c);
rotate(&a, &b, &c);
printf("The values after swapping are:\n");
printf("element 1 = %d\nelement 2 = %d\nelement 3 = %d\n", a, b, c);
return 0;
}

137/168
6/23/25, 3:18 PM C PROGRAM CLG

Flow of the Code:

1. In main , read three integers into a , b , and c , then call rotate(&a, &b, &c) to pass their addresses.

2. Inside rotate , store *z (third) in temp , shift *y into *z , shift *x into *y , then assign temp into *x , completing the rotation.

3. Control returns to main , where the rotated values now reside in a , b , c .

4. Finally, print the swapped elements in the requested order.

Input–Output Mapping:

Input Sequence Output

5, 6, 7 element 1 = 7
element 2 = 5
element 3 = 6

7.2 Count Vowels and Consonants Using Pointer


Statement:
Count vowels and consonants in a string using only pointer arithmetic.

Approach & Concept:


Traverse the string via a char * pointer; for each alphabetic character, test membership in the vowel set and tally vowels or consonants
accordingly.

138/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to count vowels and consonants using a pointer


#include <stdio.h>
#include <ctype.h>

int main() {
char s[100], *p;
int v = 0, c = 0;
printf("Input a string: ");
scanf("%99s", s);
for (p = s; *p; p++) {
if (isalpha((unsigned char)*p)) {
char ch = tolower((unsigned char)*p);
if (ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') v++;
else c++;
}
}
printf("Number of vowels: %d\nNumber of consonants: %d\n", v, c);
return 0;
}

Flow of the Code:

1. Read a whitespace-delimited string into s[] and initialize pointer p = s , vowel count v = 0 , consonant count c = 0 .

2. Loop while *p is non-zero: use isalpha() to select letters, then tolower() plus vowel test to increment v or c as appropriate.

3. Increment p after each test, moving through the string until the null terminator.

4. Print the total counts of vowels and consonants.

139/168
6/23/25, 3:18 PM C PROGRAM CLG

Input–Output Mapping:

Input Output

string Number of vowels: 1


Number of consonants: 5

7.3 Sort Array Using Pointer


Statement:
Sort an integer array in ascending order using pointer notation.

Approach & Concept:


Apply selection sort, accessing elements through a pointer to the base of the array and index arithmetic, swapping values via pointers.

// Program to sort an array using pointer notation


#include <stdio.h>

int main() {
int n = 5;
int a[5];
printf("Input 5 elements: ");
for (int i = 0; i < n; i++) scanf("%d", a + i);
for (int i = 0; i < n - 1; i++) {
int *min = a + i;

140/168
6/23/25, 3:18 PM C PROGRAM CLG

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


if (*(a + j) < *min) min = a + j;
int tmp = *(a + i);
*(a + i) = *min;
*min = tmp;
}
printf("The elements in the array after sorting:\n");
for (int i = 0; i < n; i++) printf("%d ", *(a + i));
printf("\n");
return 0;
}

Flow of the Code:

1. Read 5 integers into a[] using pointer a + i in scanf .

2. For each position i , set min to point at a + i , then scan the remainder to find the smallest, updating min .

3. Swap the value at a + i with the value at min via temporary storage.

4. After sorting, print the array using pointer dereferencing.

Input–Output Mapping:

Input Output

25 45 89 15 82 15 25 45 82 89

141/168
6/23/25, 3:18 PM C PROGRAM CLG

7.4 Print Array in Reverse Using Pointer


Statement:
Print the elements of an integer array in reverse order using a pointer.

Approach & Concept:


After reading into a[] , initialize a pointer p to the last element, then decrement it to traverse backwards, printing each value.

// Program to print an array in reverse using a pointer


#include <stdio.h>

int main() {
int n = 5;
int a[5];
printf("Input 5 elements: ");
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("The elements of array in reverse order are:\n");
for (int *p = a + n - 1; p >= a; p--)
printf("%d ", *p);
printf("\n");
return 0;
}

Flow of the Code:

1. Read 5 values into the array a[] via standard scanf .

2. Set pointer p to a + n - 1 (last element) and loop while p >= a .

142/168
6/23/25, 3:18 PM C PROGRAM CLG

3. In each iteration, print *p and then decrement p to move backwards.

4. Continue until p is before a , then print a newline.

Input–Output Mapping:

Input Output

23456 65432

7.5 Copy One String to Another Using Pointers


Statement:
Copy src string to dest using only pointers.

Approach & Concept:


Initialize two pointers, one to src , one to dest ; loop copying *src_ptr++ into *dest_ptr++ until the null terminator is copied.

// Program to copy a string using pointers (no strcpy)


#include <stdio.h>

int main() {
char src[100], dest[100];
char *p = src, *q = dest;
printf("Input a string: ");

143/168
6/23/25, 3:18 PM C PROGRAM CLG

scanf("%99s", src);
while ((*q++ = *p++) != '\0')
;
printf("The original string: %s\nThe copied string: %s\n", src, dest);
return 0;
}

Flow of the Code:

1. Read src[] via scanf("%s", src) , then set p = src , q = dest .

2. Enter a while loop that assigns *p to *q and increments both pointers, stopping when the null terminator is copied.

3. At loop exit, dest[] contains an exact copy of src[] .

4. Print both the original and the copied string.

Input–Output Mapping:

Input Output

hello The original string: hello


The copied string: hello

7.6 Count Frequency of Each Character Using Pointers


Statement:
Count the frequency of each character in a string using pointers.

144/168
6/23/25, 3:18 PM C PROGRAM CLG

Approach & Concept:


Traverse the string with pointer p ; for each character, if not already marked visited, traverse again with pointer q to count duplicates, then mark
them in a parallel visited[] array.

// Program to count frequency of each character using pointers


#include <stdio.h>
#include <string.h>

int main() {
char s[100], visited[100] = {0};
printf("Input a string: ");
scanf("%99s", s);
int len = strlen(s);
for (char *p = s; p < s + len; p++) {
if (visited[p - s]) continue;
int count = 1;
for (char *q = p + 1; q < s + len; q++) {
if (*q == *p) {
count++;
visited[q - s] = 1;
}
}
printf("Character '%c' = %d time%s\n", *p, count, count>1?"s":"");
}
return 0;
}

145/168
6/23/25, 3:18 PM C PROGRAM CLG

Flow of the Code:

1. Read s[] , determine len with strlen() , and zero‐initialize visited[] .

2. For each pointer p from s to s+len−1 , skip if visited[p−s] is set.

3. Otherwise, set count = 1 , then for each q from p+1 to end, increment count and mark visited[q−s] when duplicates found.

4. Print the character frequency, pluralizing “time” appropriately.

Input–Output Mapping:

Input Output

apple 'a' = 1 time


'p' = 2 times
'l' = 1 time
'e' = 1 time

7.7 Merge Two Arrays Using Pointers


Statement:
Merge two arrays into a third using only pointer arithmetic.

Approach & Concept:


Read both arrays into a[] and b[] . Then use three pointers p , q , and r to copy elements from a to c and from b to c sequentially.

146/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to merge two arrays using pointers


#include <stdio.h>

int main() {
int a[3], b[2], c[5];
printf("Input elements of first array: ");
for (int i = 0; i < 3; i++) scanf("%d", a + i);
printf("Input elements of second array: ");
for (int i = 0; i < 2; i++) scanf("%d", b + i);
int *p = a, *q = b, *r = c;
for (int i = 0; i < 3; i++) *r++ = *p++;
for (int i = 0; i < 2; i++) *r++ = *q++;
printf("The merged array is: ");
for (int *s = c; s < c + 5; s++) printf("%d ", *s);
printf("\n");
return 0;
}

Flow of the Code:

1. Read 3 elements into a[] and 2 into b[] via pointer arithmetic in scanf .

2. Initialize pointers p=a , q=b , and r=c .

3. Loop 3 times, copying from *p++ into *r++ , then 2 times copying from *q++ into *r++ .

4. Print the 5‐element merged array by iterating s from c to c+5 .

Input–Output Mapping:

147/168
6/23/25, 3:18 PM C PROGRAM CLG

Input A Input B Output

10 20 30 40 50 10 20 30 40 50

7.8 Find Factorial Using Recursion and Pointer


Statement:
Compute factorial of a number recursively and return it via a pointer parameter.

Approach & Concept:


Define void fact(int n, unsigned long *res) that computes *res = n * fact(n−1, res) recursively; base case sets *res = 1 when n == 0 .

// Program to find factorial using recursion and pointer return


#include <stdio.h>

void factorial(int n, unsigned long *res) {


if (n == 0) {
*res = 1;
return;
}
factorial(n - 1, res);
*res *= n;
}

148/168
6/23/25, 3:18 PM C PROGRAM CLG

int main() {
int n;
unsigned long result;
printf("Input a number: ");
scanf("%d", &n);
factorial(n, &result);
printf("Factorial of %d is %lu\n", n, result);
return 0;
}

Flow of the Code:

1. In main , read n and declare unsigned long result . Call factorial(n, &result) .

2. In factorial , if n == 0 , set *res = 1 and return as the base case.

3. Otherwise, recurse with n-1 , then multiply *res by n on the unwinding of the recursion.

4. Back in main , print the final result .

Input–Output Mapping:

Input Output

5 Factorial of 5 is 120

7.9 Calculate Average of N Numbers Using Functions and Pointers

149/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Compute the average of n numbers using a function that takes a pointer to the array and its size.

Approach & Concept:


Define double average(int *a, int n) that sums via pointer iteration and returns (double)sum / n . In main , read n values and call this
function.

// Program to calculate average using pointers and function


#include <stdio.h>

double average(int *a, int n) {


int sum = 0;
for (int *p = a; p < a + n; p++)
sum += *p;
return (double)sum / n;
}

int main() {
int n;
printf("Input number of values: ");
scanf("%d", &n);
int a[n];
printf("Input %d numbers: ", n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
printf("Average = %.2f\n", average(a, n));

150/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. In main , read n and then n integers into a[] .

2. Call average(a, n) , where p iterates from a to a+n , accumulating in sum .

3. Divide sum by n (cast to double) and return the result.

4. Print the average with two decimal places.

Input–Output Mapping:

Input Values Output

10 20 30 40 Average = 25.00

Feel free to ask for any clarifications or further examples!

Practical 8: Formatting
8.1 Currency Formatting
Write a program to display a given floating-point number as currency with two decimal places.
Example:
• Input: 1234.567

151/168
6/23/25, 3:18 PM C PROGRAM CLG

• Output: $1234.57
8.2 Formatting with Leading Zeros
Write a program to input an integer and print it with leading zeros to make it a 5-digit number.
Example:
• Input: 23
• Output: 00023
8.3 Date Formatting
Write a program to input a date in the format dd-mm-yyyy and display it in the format Month
Day, Year.
Example:
• Input: 15-03-2025
• Output: March 15, 2025
8.4 Display a Celsius to Fahrenheit Conversion Table
Create a conversion table with values displayed up to two decimal places and aligned.

🖋️ Practical 8: Formatting
Each example below follows our structure:

Problem Statement

Approach & Concept

C Code (with a top‐of‐file comment stating its purpose)

Step-by-Step Flow Explanation (each point in 2 sentences)

Input–Output Mapping

152/168
6/23/25, 3:18 PM C PROGRAM CLG

8.1 Currency Formatting


Statement:
Display a given floating-point number as currency with two decimal places, prefixed by “$”.

Approach & Concept:


Use printf ’s format specifier %.2f to round and display exactly two digits after the decimal point, and prepend the dollar symbol.

// Program to format a float as currency with two decimal places


#include <stdio.h>

int main() {
double amt;
printf("Enter amount: ");
scanf("%lf", &amt);
printf("$%.2f\n", amt);
return 0;
}

Flow of the Code:

1. Read the user’s floating-point input into amt using scanf("%lf", &amt) .

2. Use printf("$%.2f\n", amt) to print the value rounded to two decimal places and prefixed with “$”.

3. The %.2f specifier ensures exactly two digits appear after the decimal.

4. Return 0 to signal successful completion.

153/168
6/23/25, 3:18 PM C PROGRAM CLG

Input–Output Mapping:

Input Output

1234.567 $1234.57

5.2 $5.20

8.2 Formatting with Leading Zeros


Statement:
Input an integer and print it with leading zeros to make it a 5-digit number.

Approach & Concept:


Use printf ’s width and zero-padding flag: %05d prints the integer in a field five characters wide, padding with leading zeros if necessary.

// Program to print an integer with leading zeros to 5 digits


#include <stdio.h>

int main() {
int n;
printf("Enter integer: ");
scanf("%d", &n);
printf("%05d\n", n);

154/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. Read the integer n via scanf("%d", &n) .

2. Use printf("%05d\n", n) to print n in a five-character field, padding with zeros on the left.

3. If n has more than five digits, it prints the full number without truncation.

4. Return 0 to end the program.

Input–Output Mapping:

Input Output

23 00023

12345 12345

8.3 Date Formatting


Statement:
Input a date in dd-mm-yyyy format and display it as Month Day, Year .

Approach & Concept:


Parse the day, month, and year as integers, map the month number to its name via an array of strings, then print using %s %d, %d .

155/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program to reformat a date from dd-mm-yyyy to "Month Day, Year"


#include <stdio.h>

int main() {
int d, m, y;
const char *months[] = {
"January","February","March","April","May","June",
"July","August","September","October","November","December"
};
printf("Enter date (dd-mm-yyyy): ");
scanf("%d-%d-%d", &d, &m, &y);
if (m >= 1 && m <= 12)
printf("%s %d, %d\n", months[m-1], d, y);
else
printf("Invalid month\n");
return 0;
}

Flow of the Code:

1. Prompt and read three integers using scanf("%d-%d-%d", &d,&m,&y) , splitting on hyphens.

2. Use months[m-1] —where months is an array of month names—to look up the textual name.

3. Print in the format Month Day, Year via printf("%s %d, %d\n", ...) .

4. If m is outside 1–12, print an error message instead. Return 0 at end.

Input–Output Mapping:

156/168
6/23/25, 3:18 PM C PROGRAM CLG

Input Output

15-03-2025 March 15, 2025

01-12-2021 December 1, 2021

8.4 Display a Celsius to Fahrenheit Conversion Table


Statement:
Create a table converting Celsius to Fahrenheit from 0°C up to a user-specified maximum, in steps of 5°C, with all values aligned and shown to two
decimal places.

Approach & Concept:


Use a loop from 0 to maxC in increments of 5. Compute F = C * 9/5.0 + 32 and print each row with aligned %7.2f fields (width 7, two
decimals).

// Program to display Celsius to Fahrenheit conversion table


#include <stdio.h>

int main() {
double maxC;
printf("Enter maximum Celsius value: ");
scanf("%lf", &maxC);
printf("%7s | %7s\n", "Celsius", "Fahrenheit");

157/168
6/23/25, 3:18 PM C PROGRAM CLG

printf("------------------------\n");
for (double C = 0.0; C <= maxC; C += 5.0) {
double F = C * 9.0/5.0 + 32.0;
printf("%7.2f | %7.2f\n", C, F);
}
return 0;
}

Flow of the Code:

1. Read maxC (maximum Celsius) as a double from the user.

2. Print a header line with column titles using %7s to align within seven-character fields.

3. Loop C from 0.0 to maxC stepping by 5.0 , compute F = C * 9/5 + 32 , and print each C and F with %7.2f .

4. Return 0 to end the program.

Input–Output Mapping:

Input ( maxC ) Output (first rows)

20

diff

Celsius | Fahrenheit
------------------------
0.00 | 32.00
5.00 | 41.00
10.00 | 50.00

158/168
6/23/25, 3:18 PM C PROGRAM CLG

15.00 | 59.00
20.00 | 68.00

| 10 |

diff

Celsius | Fahrenheit
------------------------
0.00 | 32.00
5.00 | 41.00
10.00 | 50.00

Let me know if you need any further adjustments or additional formatting examples!

Practical 9: Advance Practical


9.1 Dynamic Arrays with Memory Management Demonstrating malloc, calloc, realloc, and free
Write a program to demonstrating malloc, calloc, realloc, and free
9.2 Student Record System using Structures:
Write a program for Student Record System using Structures Stores and displays student
information
9.3 Simple File Operations
Write a program to create and read files.
9.4 Simple Stack and Queue

159/168
6/23/25, 3:18 PM C PROGRAM CLG

Write a program to demonstrating Simple Stack(Push, Pop) and Queue(Enqueue, Dequeue)

🚀 Practical 9: Advanced C Programming


Each example below follows our standard structure:

Problem Statement

Approach & Concept

Minimal C Code (with a top‐of‐file comment stating its purpose)

Step-by-Step Flow Explanation (each point = 2 sentences)

Input–Output Mapping

9.1 Dynamic Arrays with malloc , calloc , realloc , and free


Statement:
Demonstrate dynamic allocation of an integer array using malloc , initializing with calloc , resizing with realloc , and deallocating with free .

Approach & Concept:


Use malloc to allocate initial space, calloc to allocate and zero-initialize, then realloc to grow or shrink the buffer, finally free to release
memory.

// Program to demonstrate malloc, calloc, realloc, and free


#include <stdio.h>

160/168
6/23/25, 3:18 PM C PROGRAM CLG

#include <stdlib.h>

int main() {
int *arr;
int n = 3, i;
// malloc: allocate for n ints (uninitialized)
arr = (int *)malloc(n * sizeof(int));
printf("After malloc:\n");
for (i = 0; i < n; i++) arr[i] = i + 1;
for (i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");

// calloc: allocate for 2n ints (zero-initialized)


arr = (int *)calloc(2 * n, sizeof(int));
printf("After calloc:\n");
for (i = 0; i < 2*n; i++) printf("%d ", arr[i]);
printf("\n");

// realloc: grow to 4n ints


arr = (int *)realloc(arr, 4 * n * sizeof(int));
printf("After realloc:\n");
for (i = 0; i < 4*n; i++) arr[i] = i + 1;
for (i = 0; i < 4*n; i++) printf("%d ", arr[i]);
printf("\n");

// free
free(arr);

161/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. malloc(n*sizeof(int)) reserves memory for n ints; we then store 1,2,3 and print them.

2. calloc(2*n,…) replaces arr with a zero-initialized block twice as large; printing shows all zeros.

3. realloc expands the block to 4*n ints; we assign new values 1–12 and print the extended array.

4. Finally, free(arr) releases the allocated memory before program exit.

Input–Output Mapping:
No user input; printed states:

yaml

After malloc:
1 2 3
After calloc:
0 0 0 0 0 0
After realloc:
1 2 3 4 5 6 7 8 9 10 11 12

9.2 Student Record System using Structures

162/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Store and display information (roll, name, marks) for n students using a struct array.

Approach & Concept:


Define a struct Student with fields, read n , allocate an array on the stack, populate via loop, then print.

// Program for Student Record System using structures


#include <stdio.h>

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

int main() {
int n;
printf("Enter number of students: ");
scanf("%d", &n);
Student s[n];
for (int i = 0; i < n; i++) {
printf("Enter roll, name, marks for student %d: ", i+1);
scanf("%d %49s %f", &s[i].roll, s[i].name, &s[i].marks);
}
printf("Student Records:\n");
for (int i = 0; i < n; i++) {
printf("%d %s %.2f\n", s[i].roll, s[i].name, s[i].marks);

163/168
6/23/25, 3:18 PM C PROGRAM CLG

}
return 0;
}

Flow of the Code:

1. Read n , declare Student s[n] , then loop to read each student’s roll , name , and marks .

2. In the second loop, print each record in the order entered.

3. Each scanf uses field widths to guard against overflow.

4. The formatted output shows roll, name, and marks to two decimals.

Input–Output Mapping:

yaml

Enter number of students: 2


Enter roll, name, marks for student 1: 101 Alice 85.5
Enter roll, name, marks for student 2: 102 Bob 92
Student Records:
101 Alice 85.50
102 Bob 92.00

9.3 Simple File Operations

164/168
6/23/25, 3:18 PM C PROGRAM CLG

Statement:
Create a text file, write a line, then reopen and read its content.

Approach & Concept:


Use fopen in "w" mode to write, then "r" mode to read back; employ fprintf and fgets .

// Program to create and read a text file


#include <stdio.h>

int main() {
FILE *fp;
char line[100];

// create and write


fp = fopen("data.txt", "w");
fprintf(fp, "Hello, File I/O!\n");
fclose(fp);

// open and read


fp = fopen("data.txt", "r");
printf("File contents:\n");
while (fgets(line, sizeof line, fp))
printf("%s", line);
fclose(fp);
return 0;
}

165/168
6/23/25, 3:18 PM C PROGRAM CLG

Flow of the Code:

1. fopen("data.txt","w") creates (or truncates) the file; fprintf writes a line, then fclose .

2. Reopen with "r" , loop fgets to read each line into line , printing until EOF.

3. Close the file with fclose .

4. Program ends, having demonstrated basic file write and read.

Input–Output Mapping:
No user input; printed:

mathematica

File contents:
Hello, File I/O!

9.4 Simple Stack and Queue


Statement:
Demonstrate a stack (push/pop) and a queue (enqueue/dequeue) using arrays and pointers.

Approach & Concept:


Implement stack with top index and queue with front / rear indices in fixed-size arrays, performing basic operations in code.

166/168
6/23/25, 3:18 PM C PROGRAM CLG

// Program demonstrating simple stack and queue


#include <stdio.h>
#define MAX 5

int main() {
int stack[MAX], top = -1;
int queue[MAX], front = 0, rear = -1;
int i;

// Stack push
for (i = 1; i <= 3; i++) stack[++top] = i * 10;
printf("Stack after pushes: ");
for (i = 0; i <= top; i++) printf("%d ", stack[i]);
printf("\n");

// Stack pop
printf("Stack pop: %d\n", stack[top--]);

// Queue enqueue
for (i = 1; i <= 3; i++) queue[++rear] = i * 100;
printf("Queue after enqueues: ");
for (i = front; i <= rear; i++) printf("%d ", queue[i]);
printf("\n");

// Queue dequeue
printf("Queue dequeue: %d\n", queue[front++]);

167/168
6/23/25, 3:18 PM C PROGRAM CLG

return 0;
}

Flow of the Code:

1. Stack: Initialize top=-1 , then push values 10,20,30 by stack[++top] = … , and print the stack array up to top .

2. Pop one element by printing stack[top] then decrementing top .

3. Queue: Initialize front=0, rear=-1 , enqueue 100,200,300 by queue[++rear]=… , and print from front to rear .

4. Dequeue by printing queue[front] then incrementing front .

Input–Output Mapping:
No user input; printed:

yaml

Stack after pushes: 10 20 30


Stack pop: 30
Queue after enqueues: 100 200 300
Queue dequeue: 100

168/168

You might also like