c Program Clg
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
1/168
6/23/25, 3:18 PM C PROGRAM CLG
Algorithm Steps:
1. Read integer n .
2. Compute r = n % 2 .
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;
}
Algorithm Steps:
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
Algorithm Steps:
1. Read a , b , c .
2. Set max = a .
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;
}
6/168
6/23/25, 3:18 PM C PROGRAM CLG
Algorithm Steps:
1. Read x , y , 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;
}
Algorithm Steps:
1. Read integer m .
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;
}
Algorithm Steps:
1. Read integer y .
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.”
Input/Output Mapping:
10/168
6/23/25, 3:18 PM C PROGRAM CLG
Input Output
#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
11/168
6/23/25, 3:18 PM C PROGRAM CLG
Algorithm Steps:
1. Read char ch .
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 .”
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;
}
Statement: Calculate the number of days in a given month, considering leap years.
Algorithm Steps:
13/168
6/23/25, 3:18 PM C PROGRAM CLG
Flow Explanation:
1. Prompt and read m and y via scanf . This provides both values needed for February’s calculation.
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.
Algorithm Steps:
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
#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
Statement: Implement a menu-driven program with options like “Add,” “Subtract,” and “Exit,” using a switch-case statement.
Algorithm Steps:
3. switch(ch) :
17/168
6/23/25, 3:18 PM C PROGRAM CLG
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:
#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
Input/Output Mapping
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:
Input/Output Example:
Input: 5 → Output: Sum = 15
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:
Input/Output Example:
Input: 4 → Output: Factorial = 24
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:
Input/Output:
Input: 5 → Output: 0 1 1 2 3
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:
Input/Output:
Input: 7 → Output: Prime
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:
Input/Output:
Input: 121 → Output: Palindrome
#include <stdio.h>
int main() {
int n, r = 0;
25/168
6/23/25, 3:18 PM C PROGRAM CLG
Flow:
Input/Output:
Input: 1234 → Output: Reversed = 4321
#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:
Input/Output:
Input: 123456 → Output: Even = 3, Odd = 3
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:
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:
Input-output mapping
28/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;
}
29/168
6/23/25, 3:18 PM C PROGRAM CLG
Input/Output Mapping:
Input: n = 5
Output: Sum = 15
#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;
}
Input/Output Mapping:
Input: n = 5
#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;
}
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
32/168
6/23/25, 3:18 PM C PROGRAM CLG
Question Statement:
Determine if a given number is prime using a loop.
#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;
}
Input/Output Mapping:
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?
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:
Input-output example
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;
}
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 .
Input/Output Mapping:
35/168
6/23/25, 3:18 PM C PROGRAM CLG
#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;
}
2. Loop runs until n is 0, picking the last digit and forming the reverse by rev = rev * 10 + digit .
36/168
6/23/25, 3:18 PM C PROGRAM CLG
Input/Output Mapping:
#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;
}
1. User inputs a number. Variables even and odd counters are initialized.
Input/Output Mapping:
#include <stdio.h>
int main() {
int n, sum = 0, temp;
38/168
6/23/25, 3:18 PM C PROGRAM CLG
Input/Output Mapping:
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!
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
#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;
}
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
Question:
Calculate the factorial of a given number using a while loop.
#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;
}
Input/Output Mapping:
Input: n = 5
Question:
Generate the first N terms of the Fibonacci sequence 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;
}
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
#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;
}
Input/Output Mapping:
45/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;
}
46/168
6/23/25, 3:18 PM C PROGRAM CLG
Input/Output Mapping:
Question:
Reverse the digits of a number using a for loop.
#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;
}
Input/Output Mapping:
#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;
}
Input/Output Mapping:
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;
}
Input/Output Mapping:
✅ 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
Statement:
Write a program to calculate the sum of the first N natural numbers using a for loop.
#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;
}
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.
#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;
}
1. Read the integer n from the user and initialize fact = 1 as the running product.
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
Statement:
Generate the first N terms of the Fibonacci sequence using a do-while loop.
#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;
}
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
55/168
6/23/25, 3:18 PM C PROGRAM CLG
Statement:
Determine if a given number is prime using a loop.
#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;
}
56/168
6/23/25, 3:18 PM C PROGRAM CLG
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
Statement:
Check if a given number (or string) is a palindrome.
#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;
}
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.
Input–Output Mapping:
Input Output
121 Palindrome
58/168
6/23/25, 3:18 PM C PROGRAM CLG
Statement:
Given a number n , reverse its digits using a for loop.
#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;
}
2. In the for loop header, check n != 0 , then extract the last digit with n % 10 and append it to rev .
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
560 Reversed = 65
Statement:
Given a number, count how many of its digits are even and how many are odd.
#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;
}
2. While n is nonzero, extract the last digit and test its parity.
4. Remove the last digit from n and repeat until all digits are processed, then print the counts.
Input–Output Mapping:
Input Output
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
#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;
}
2. In a loop, add the last digit of temp to sum and then remove that digit.
Input–Output Mapping:
62/168
6/23/25, 3:18 PM C PROGRAM CLG
Input Output
18 Harshad
19 Not Harshad
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:
* * *
******
* * *
65/168
6/23/25, 3:18 PM C PROGRAM CLG
Problem Statement
Minimal C Code
Input–Output Mapping
#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
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
Problem Statement
69/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping
70/168
6/23/25, 3:18 PM C PROGRAM CLG
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>
*****
71/168
6/23/25, 3:18 PM C PROGRAM CLG
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>
****
*****
73/168
6/23/25, 3:18 PM C PROGRAM CLG
printf("*");
printf("\n");
}
return 0;
}
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 *
**
***
****
*****
74/168
6/23/25, 3:18 PM C PROGRAM CLG
Statement:
Print an inverted left-aligned right-angled triangle of height n .
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.
75/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input ( n ) Output
5 ****<br><br>*<br><br>
76/168
6/23/25, 3:18 PM C PROGRAM CLG
printf(" ");
}
printf("\n");
}
return 0;
}
2. In each row, loop j from 1 to n and print a star if on a border (first/last row or column).
Input–Output Mapping:
Input ( n ) Output
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.
78/168
6/23/25, 3:18 PM C PROGRAM CLG
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
79/168
6/23/25, 3:18 PM C PROGRAM CLG
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
82/168
6/23/25, 3:18 PM C PROGRAM CLG
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
83/168
6/23/25, 3:18 PM C PROGRAM CLG
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 ****
******
***
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
🗂️ Practical 4: Arrays
Each program below follows our standard structure:
Problem Statement
Input–Output Mapping
86/168
6/23/25, 3:18 PM C PROGRAM CLG
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:
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;
}
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.
Input–Output Mapping:
89/168
6/23/25, 3:18 PM C PROGRAM CLG
[3, 1, 4, 2] Sorted: 1 2 3 4
[5, 5, 2, 8, 0] Sorted: 0 2 5 5 8
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;
}
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.
Input–Output Mapping:
[1, 2, 3, 4, 5] Reversed: 5 4 3 2 1
91/168
6/23/25, 3:18 PM C PROGRAM CLG
Statement:
Rotate an array left or right by K positions.
92/168
6/23/25, 3:18 PM C PROGRAM CLG
return 0;
}
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
93/168
6/23/25, 3:18 PM C PROGRAM CLG
duplicates.
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;
}
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:
[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
Input–Output Mapping
97/168
6/23/25, 3:18 PM C PROGRAM CLG
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.
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
99/168
6/23/25, 3:18 PM C PROGRAM CLG
s[j] = temp;
}
printf("Reversed = %s\n", s);
return 0;
}
1. Read the full line into s[] , then compute its length by advancing i until s[i] == '\0' .
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
100/168
6/23/25, 3:18 PM C PROGRAM CLG
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
102/168
6/23/25, 3:18 PM C PROGRAM CLG
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 .
Input–Output Mapping:
103/168
6/23/25, 3:18 PM C PROGRAM CLG
Input Output
104/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input Output
programming progamin
aabbcc abc
105/168
6/23/25, 3:18 PM C PROGRAM CLG
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] .
Input–Output Mapping:
Input Output
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;
}
2. Loop until s[i] == '\0' ; if s[i] is lowercase, convert it to uppercase, and vice versa.
Input–Output Mapping:
Input Output
108/168
6/23/25, 3:18 PM C PROGRAM CLG
109/168
6/23/25, 3:18 PM C PROGRAM CLG
return 0;
}
1. Read s[] and compute its length len by iterating until the null terminator.
3. Each recursion swaps the characters at positions i and j , then advances inward.
Input–Output Mapping:
Input Output
110/168
6/23/25, 3:18 PM C PROGRAM CLG
111/168
6/23/25, 3:18 PM C PROGRAM CLG
while (s[i]) {
if (isdigit(s[i])) d++;
i++;
}
return d;
}
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;
}
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
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;
}
114/168
6/23/25, 3:18 PM C PROGRAM CLG
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:
115/168
6/23/25, 3:18 PM C PROGRAM CLG
116/168
6/23/25, 3:18 PM C PROGRAM CLG
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';
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).
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
Input–Output Mapping
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;
}
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.”
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
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;
}
1. In reverseNumber , initialize rev = 0 . Extract the last digit d of n and append it to rev , then drop that digit from n .
3. In main , read the input, call reverseNumber , and print the result.
Input–Output Mapping:
Input Output
1000 Reversed = 1
123/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
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.
124/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input Output
10 1010
7 111
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;
}
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.
Input–Output Mapping:
126/168
6/23/25, 3:18 PM C PROGRAM CLG
Input Output
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;
}
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.
Input–Output Mapping:
Input ( n ) Output
5 Sum = 15
10 Sum = 55
128/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
4. Return 0 to finish.
129/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input Output
0 Factorial of 0 is: 1
130/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
3. In main , read array size and elements, then call both functions and print their results.
Input–Output Mapping:
131/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
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.
Input–Output Mapping:
Input Output
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
📌 Practical 7: Pointers
Each program follows our standard format:
Problem Statement
Input–Output Mapping
136/168
6/23/25, 3:18 PM C PROGRAM CLG
137/168
6/23/25, 3:18 PM C PROGRAM CLG
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.
Input–Output Mapping:
5, 6, 7 element 1 = 7
element 2 = 5
element 3 = 6
138/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
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.
139/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input Output
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
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.
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
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;
}
142/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input Output
23456 65432
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;
}
2. Enter a while loop that assigns *p to *q and increments both pointers, stopping when the null terminator is copied.
Input–Output Mapping:
Input Output
144/168
6/23/25, 3:18 PM C PROGRAM CLG
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
3. Otherwise, set count = 1 , then for each q from p+1 to end, increment count and mark visited[q−s] when duplicates found.
Input–Output Mapping:
Input Output
146/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
1. Read 3 elements into a[] and 2 into b[] via pointer arithmetic in scanf .
3. Loop 3 times, copying from *p++ into *r++ , then 2 times copying from *q++ into *r++ .
Input–Output Mapping:
147/168
6/23/25, 3:18 PM C PROGRAM CLG
10 20 30 40 50 10 20 30 40 50
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;
}
1. In main , read n and declare unsigned long result . Call factorial(n, &result) .
3. Otherwise, recurse with n-1 , then multiply *res by n on the unwinding of the recursion.
Input–Output Mapping:
Input Output
5 Factorial of 5 is 120
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.
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;
}
Input–Output Mapping:
10 20 30 40 Average = 25.00
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
Input–Output Mapping
152/168
6/23/25, 3:18 PM C PROGRAM CLG
int main() {
double amt;
printf("Enter amount: ");
scanf("%lf", &amt);
printf("$%.2f\n", amt);
return 0;
}
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.
153/168
6/23/25, 3:18 PM C PROGRAM CLG
Input–Output Mapping:
Input Output
1234.567 $1234.57
5.2 $5.20
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;
}
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.
Input–Output Mapping:
Input Output
23 00023
12345 12345
155/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
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", ...) .
Input–Output Mapping:
156/168
6/23/25, 3:18 PM C PROGRAM CLG
Input Output
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;
}
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 .
Input–Output Mapping:
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!
159/168
6/23/25, 3:18 PM C PROGRAM CLG
Problem Statement
Input–Output Mapping
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");
// free
free(arr);
161/168
6/23/25, 3:18 PM C PROGRAM CLG
return 0;
}
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.
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
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.
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;
}
1. Read n , declare Student s[n] , then loop to read each student’s roll , name , and marks .
4. The formatted output shows roll, name, and marks to two decimals.
Input–Output Mapping:
yaml
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.
int main() {
FILE *fp;
char line[100];
165/168
6/23/25, 3:18 PM C PROGRAM CLG
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.
Input–Output Mapping:
No user input; printed:
mathematica
File contents:
Hello, File I/O!
166/168
6/23/25, 3:18 PM C PROGRAM CLG
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;
}
1. Stack: Initialize top=-1 , then push values 10,20,30 by stack[++top] = … , and print the stack array up to top .
3. Queue: Initialize front=0, rear=-1 , enqueue 100,200,300 by queue[++rear]=… , and print from front to rear .
Input–Output Mapping:
No user input; printed:
yaml
168/168