Sem 2 C Assignments
Sem 2 C Assignments
a. Addition
b. Subtraction
c. Multiplication
d. Division
ALGORITHM:
Step 1: Start.
Step 2: Declare four functions for the four operations— addition, subtraction, multiplication
and division— called sum(), subtraction(), product() and quotient().
Step 3: Initialize integer variables to store two numbers from the user, and the values of the
sum, difference, product and quotient.
Step 4: After taking two numbers n1 and n2 from the user, pass them to each function:-
a. Passed to sum(), where they get added, and the returned value is stored in s1
b. Passed to subtraction() where their difference is calculated, and the returned value
is stored in d1
c. Passed to product(), where they get multiplied and the returned value is stored in p1
d. Passed to quotient(), where the quotient is calculated and the returned value is
stored in q1
Step 5: Print the sum, difference, product and quotient of the two numbers.
Step 6: Stop.
CODE:
#include<stdio.h>
int sum(int a, int b);
int subtraction(int x, int y);
int product(int e, int f);
int quotient(int g, int h);
int main()
{
int n1, n2, s1=0, d1=0, p1=0, q1=0;
printf("Enter two numbers:\n");
scanf("%d %d", &n1, &n2);
s1=sum(n1, n2);
d1=subtraction(n1, n2);
p1=product(n1, n2);
q1=quotient(n1, n2);
printf("\nThe sum of the two numbers is: %d", s1);
1
printf("\nThe difference of the two numbers is: %d", d1);
printf("\nThe product of the two numbers is: %d", p1);
printf("\nThe quotient of the two numbers is: %d", q1);
return 0;
}
int sum(int a, int b)
{
int s=0;
s=a+b;
}
int subtraction(int x, int y)
{
int d=0;
d=x-y;
}
int product(int e, int f)
{
int p=0;
p=e*f;
}
int quotient(int g, int h)
{
int q=0;
q=g/h;
}
OUTPUT:
DISCUSSION: The for-loop prints each value of i for which n is divisible, using the line
if(n%i==0).
When the user inputs the value 20, the code returns the following output: Factors of 20: 1, 2,
4, 5, 10.
2
ASSIGNMENT 2
PROBLEM STATEMENT: Write a C program to read and display the following
information of a student: Name, age, course, Department, city, marks in 12th board exam.
ALGORITHM:
Step 1: Start.
Step 2: Declare four character arrays for name, course, department and city, and declare an
integer variable for age, and a float variable for marks.
Step 3: Take user input, storing them in the declared variables and print the entered data.
Step 4: Stop.
CODE:
#include<stdio.h>
int main()
{
char name[20], course[40], department[40], city[30]; //storing strings as character arrays
int age;
float marks;
printf("Enter your name:\n");
scanf("%s", name);
printf("Enter your age:\n");
scanf("%d", &age);
printf("Enter your course:\n");
scanf("%s", course);
printf("Enter your department:\n");
scanf("%s", department);
printf("Enter your city:\n");
scanf("%s", city);
printf("Enter your marks in 12th board exam:\n");
scanf("%f", &marks);
printf("Your entered information:\n");
printf("Name: %s\n Age: %d\n Course: %s\n Department: %s\n City: %s\n Marks:
%.2f", name, age, course, department, city, marks);
return 0;
}
3
OUTPUT:
DISCUSSION: The program uses different format specifiers to accept different types of
data, such as %d for integer values like age, %s for character arrays or string variables like
city, name, etc. These specifiers are also used to display entered information in specific
formats, for example, %.2f will print the float value entered in variable “marks” up to two
decimal places.
4
ASSIGNMENT 3
PROBLEM STATEMENT: Write a C program to swap two numbers with and without a
3rd variable.
ALGORITHM:
Step 1: Start.
Step 2: Declare two functions swap3() and swap() to swap two numbers, and in the main
method, declare two integer variables n and m to store the values of these numbers.
Step 3: Take user input to store the number values, and pass them through the functions
swap3() and swap(), which return the swapped values.
Step 4: Use the function swap3() to create a temporary variable int temp, and use it to store
the value of int a, while the value of a is reassigned to int b, and int b is reassigned to the
value of int a by using the value stored in int temp.
Step 5: Use the function swap() to add the value of int y to int x and assign it to int x,
subtract the value of y from int x and assign that value to int y, and finally subtract int y from
int x and assign the final value to int x.
Step 6: Use a printf statement in each of the functions to display the swapped values.
Step 7: Stop.
CODE:
#include<stdio.h>
void swap3(int a, int b);
void swap(int x, int y);
int main()
{
int n, m;
printf("Enter two numbers:\n");
scanf("%d, %d", &n, &m);
swap3(n, m);
swap(n, m);
return 0;
}
void swap3(int a, int b) //to swap two numbers using a third variable
{
int temp=0;
temp=a;
a=b;
b=temp;
printf("\nSWAPPING USING THIRD VARIABLE\nFirst number and Second
number are now: %d, %d\n\n", a, b);
}
void swap(int x, int y) //to swap two numbers without using a third variable
5
{
x+=y;
y=x-y;
x-=y;
printf("SWAPPING WITHOUT USING THIRD VARIABLE\nFirst number and
Second number are now: %d, %d", x, y);
}
OUTPUT:
DISCUSSION: Two of the methods used to swap two numbers are shown in the above
program, where a third variable is used, or is omitted. Excluding a third temporary variable is
useful for efficient memory management in the program.
6
ASSIGNMENT 4
𝑧
PROBLEM STATEMENT: Write a C program to find 𝑥 𝑦 without using any library
functions.
ALGORITHM:
Step 1: Start.
Step 2: Declare integer variables x, y, z and p, and initialize an integer variable c to the value
1. Take values from the user for x, y and z.
Step 3: Assign the product of int y and int z to the variable p (to calculate the total exponent),
and run a while loop that makes int p decrement by 1 for each iteration.
Step 4: Inside the while loop, update the value of int c by multiplying it with int x (c=x*c) as
many times as the loop runs, that is, p times (while p>=1).
𝑧
Step 5: Once the value of p reaches 1, the loop is terminated and the value of 𝑥 𝑦 is printed.
Step 6: Stop.
CODE:
#include<stdio.h>
int main()
{ int x, y, z, c=1, p;
printf("Enter value of x: ");
scanf("%d", &x);
printf("Enter value of y: ");
scanf("%d", &y);
printf("Enter value of z: ");
scanf("%d", &z);
p = y*z;
while(p>=1)
{ c=x*c;
p=p-1;
}
printf("\nx^y^z = %d", c);
return 0;
}
7
OUTPUT:
DISCUSSION: We make use of a while-loop to recreate the process of finding the value of a
number raised to the power of another number, in this case, calculating exponents. Instead of
simply using library functions to find x raised to the power y raised to the power z, we
multiply the exponents y and z to make one exponent for x, and we use the while-loop to
multiply x with itself as many times as the value of the exponent.
In the above program, the sample values for x, y and z were 2, 3 and 4, respectively. The total
exponent was calculated by multiplying 3 and 4 to get 12, causing the while-loop to run for
12 iterations and multiplying x with itself 12 times. The value of int c is updated to reflect the
current value of x in each iteration, and the final value of c is printed when the loop is
terminated.
8
ASSIGNMENT 5
PROBLEM STATEMENT: Write a menu-driven C program to calculate the area of the
following using macro: i) circle ii) square iii) rectangle
ALGORITHM:
Step 1: Start.
Step 2: Define four macros PI, C_AREA, S_AREA and R_AREA with the corresponding
values for pi, area of a circle, area of a square and area of a rectangle.
Step 3: Print a selection for the user to choose from, with the options being to calculate the
area of any three of the shapes; circle, square or rectangle.
Step 4: Based off the user’s choice, use a switch-case statement to use the first case to take
user input for radius/length/breadth and calculate area of a circle if the user inputs 1, area of a
square if the user inputs 2, area of a rectangle if the user inputs 3, and terminate the program
if the user inputs 4.
Step 5: Use the predefined macros to calculate the areas, and return the value to the user in a
printf statement.
Step 6: Put the entire switch-case statement along with the menu selection in a while-loop,
that runs and continues to calculate areas as long as the user does not enter 4.
Step 7: Stop.
CODE:
#include <stdio.h>
#define PI 3.14159
#define C_AREA(r) (PI * (r) * (r))
#define S_AREA(s) ((s) * (s))
#define R_AREA(l, w) ((l) * (w))
int main() {
int choice;
float radius, side, length, width;
printf("Choose:\n");
printf("1. Area of a circle\n2. Area of a square\n3. Area of a rectangle\n4. Exit\n");
while(1) {
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter circle radius: ");
scanf("%f", &radius);
printf("Area of the circle: %.2f units\n", C_AREA(radius));
break;
case 2:
9
printf("Enter square side: ");
scanf("%f", &side);
printf("Area of the square: %.2f units\n", S_AREA(side));
break;
case 3:
printf("Enter rectangle length and width: ");
scanf("%f %f", &length, &width);
printf("Area of the rectangle: %.2f units\n", R_AREA(length, width));
break;
case 4:
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
DISCUSSION: We define macros for calculating the area of a circle, square, and rectangle.
We then display a menu for the user to choose which shape’s area to calculate. Based on the
user's choice, the program moves into a switch-case and asks for the necessary input (radius,
side, length, and width) and calculates the area using the corresponding macro.
10
ASSIGNMENT 6
PROBLEM STATEMENT: Write a C program to swap two integers using macro.
ALGORITHM:
Step 1: Start.
CODE:
#include <stdio.h>
#define SWAP(a, b) {int temp = a; a = b; b = temp;}
int main() {
int x, y;
printf("Enter two numbers:\n");
scanf("%d %d", &x, &y);
printf("Before swap: x = %d, y = %d\n", x, y);
SWAP(x, y)
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
OUTPUT:
DISCUSSION: In this program, the SWAP macro takes two arguments, a and b, and swaps
their values using a temporary variable. When we run this program, it will output:
This shows that the SWAP macro successfully swapped the values of x and y.
11
ASSIGNMENT 7
PROBLEM STATEMENT: Write a program in C to read n numbers and print the even/odd
numbers up to n.
ALGORITHM:
Step 1: Start.
Step 2: Take the quantity of numbers to print up to from the user and start two for-loops to
check each number.
Step 3: One for-loop will print the numbers that are divisible by 2 under “even numbers” and
the other for-loop will print the remaining numbers under “odd numbers”.
Step 4: Stop.
CODE:
#include <stdio.h>
int main() {
int n, i, num;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Even numbers up to %d: ", n);
for (i = 2; i <= n; i += 2) {
printf("%d, ", i);
}
printf("\nOdd numbers up to %d: ", n);
for (i = 1; i <= n; i += 2) {
printf("%d, ", i);
}
return 0;
}
OUTPUT:
DISCUSSION: The for-loops check each number up to n iterations, and if the number is
divisible by 2 leaving no remainder, it gets printed under “even”, while the rest are printed
under “odd”, since they are assumed to not be divisible by 2.
12
ASSIGNMENT 8
PROBLEM STATEMENT: Write a program in C to read a number and print the sum of n
natural numbers.
ALGORITHM:
Step 1: Start.
Step 2: Initialize an int n and int sum = 0, and ask the user to input a number, which will be
the number of numbers to be added up.
Step 3: Start a for-loop that runs for n iterations and adds the value of int i to sum,
incrementing int i with each iteration. Print the sum after the loop terminates.
Step 4: Stop.
CODE:
#include <stdio.h>
int main()
{
int n, sum=0;
printf("Enter number of numbers to be added:\n");
scanf("%d", &n);
for (int i=1; i<=n; i++)
{
sum+=i;
}
printf("The sum of %d natural numbers is: %d", n, sum);
return 0;
}
OUTPUT:
DISCUSSION: The for-loop runs n times and adds the value of int i to sum every single
iteration, until int i reaches the value of n, which is the number of numbers to be summed up.
13
ASSIGNMENT 9
PROBLEM STATEMENT: Write a program in C to read a number n and print factors of n.
ALGORITHM:
Step 1: Start.
Step 2: Take user input for the number whose factors are to be printed, and store it in an
integer variable n.
Step 3: Start a for-loop that runs for n iterations and checks whether n is divisible by any of
the numbers from 1 to n; if it is divisible by the number (current iteration value of int i) and
leaves no remainder, then the number is a factor, and it gets printed.
Step 4: Stop.
CODE:
#include <stdio.h>
int main()
{
int n;
printf("Enter number:\n");
scanf("%d", &n);
printf("Factors of %d: ", n);
for(int i=1; i<n; i++)
{
if (n%i==0)
printf("%d, ", i);
}
return 0;
}
OUTPUT:
DISCUSSION: The program utilizes a for-loop that checks all the numbers up to n, and
whether a remainder is produced when n is divided by each of the numbers. If there is no
remainder, the number is a factor.
14
ASSIGNMENT 10
PROBLEM STATEMENT: Write a program in C to read a number n and print first 10
multiples of n.
ALGORITHM:
Step 1: Start.
Step 2: Take user input for the number whose multiples are to be printed, and store it in int n.
Step 3: Start a for-loop that runs for ten iterations and prints n*i in each iteration, where the
values of int i are from 1 to 10. Terminate the loop after it has run ten times and printed ten
multiples of n.
Step 4: Stop.
CODE:
#include <stdio.h>
int main()
{
int n;
printf("Enter a number:\n");
scanf("%d", &n);
printf("First ten multiples of %d: ", n);
for(int i=1; i<11; i++)
{
printf("%d ", i*n);
}
return 0;
}
OUTPUT:
DISCUSSION: The for-loop runs for ten iterations and multiplies the user’s number with 1,
2, 3, …, 10 and prints the output (multiple) for each iteration. The integer variable int i works
as a control variable that increments after each loop iteration and terminates the loop after it
reaches a value of 10 (since the loop condition is i<11).
15
ASSIGNMENT 11
PROBLEM STATEMENT: Write a program in C to read a number n and print if n is
“PRIME” or “COMPOSITE”.
ALGORITHM:
Step 1: Start.
Step 2: Declare variables int n, int i and int flag=0, and take user input for the number to be
checked, storing it in n.
Step 3: Use an if-statement to check if the number is less than one, or equal to one. If it is
found to fall under any of these conditions, the number is declared neither PRIME nor
COMPOSITE.
Step 4: Use a for-loop to check if a number has any factors besides itself and 1, and return
the value of int flag as 1 if it does. If not, the value of flag remains 0.
Step 5: The for-loop runs for n/2 iterations (i.e. up to half of the user’s inputted number)
before terminating, and returns a value for int flag.
Step 6: An if-statement is used to check the returned value of int flag after the for-loop
terminates; if the value is 1, then a printf statement is used to declare that the number is
composite, otherwise if int flag is equal to 0, a printf statement is used to declare that the
number is prime.
Step 7: Stop.
CODE:
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1)
{ printf("%d is neither PRIME nor COMPOSITE\n", n); }
else
{
for (i = 2; i <= n / 2; i++)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 1)
16
{ printf("COMPOSITE", n); }
else
{ printf("PRIME", n); }
}
return 0;
}
OUTPUT:
DISCUSSION: The program checks if a number has any factors besides itself and 1, and if
found with other factors, it prints “COMPOSITE”, otherwise it prints “PRIME”. An if-
statement is used to check first that the value of the user’s input is not 1 or less, since that
would mean that the number is neither prime nor composite.
17
ASSIGNMENT 12
PROBLEM STATEMENT: Write a program in C to convert a given temperature in Celsius
to Fahrenheit or vice-versa.
ALGORITHM:
Step 1: Start.
Step 2: Print a menu for the user to choose what type of conversion they want to do; a
conversion from Celsius to Fahrenheit, or a conversion from Fahrenheit to Celsius.
Step 3: Take the user’s choice, storing the input in int choice and ask for a temperature to
convert.
Step 4: Start a switch statement using the variable choice, where if the user inputs 1, it runs
the first case, and if the user inputs 2, it runs the second case, otherwise the default case
executes.
Step 5: In the first case, the temperature is taken as a reading in Celsius, and is converted into
Fahrenheit, storing the converted reading in float result.
Step 6: In the second case, the temperature is taken as a reading in Fahrenheit, and is
converted into Celsius, storing the converted reading in float result.
Step 7: The final conversion is printed after the switch-statement is terminated.
Step 8: Stop.
CODE:
#include <stdio.h>
int main()
{
float temp, result;
int choice;
printf("Conversions:\n1. Celsius to Fahrenheit\n2. Fahrenheit to Celsius\n");;
printf("Enter your choice: ");
scanf("%d", &choice);
printf("Enter temperature: ");
scanf("%f", &temp);
switch (choice)
{
case 1:
result = (temp * 9 / 5) + 32;
printf("%.2f°C = %.2f°F", temp, result);
break;
case 2:
result = (temp - 32) * 5 / 9;
printf("%.2f°F = %.2f°C", temp, result);
break;
default:
18
printf("Invalid choice. Please try again.\n");
}
return 0;
}
OUTPUT:
DISCUSSION: This program prompts the user to choose whether they want to convert
Celsius to Fahrenheit or vice-versa. It then asks for the temperature value and performs the
conversion using the following formulas:
19
ASSIGNMENT 13
PROBLEM STATEMENT: Write a program in C to determine and print the sum of the
1 1 1
following harmonic series for a given value of n: 1 + 2 + 3 + ⋯ + 𝑛 .
ALGORITHM:
Step 1: Start.
Step 2: Ask the user for the number of terms in the harmonic series to be calculated, and
store the value in int n.
Step 3: Use a for-loop that runs for n iterations to calculate each term and add it to double
sum, using 1.0/i as the formula.
Step 4: Print the sum of the terms as a float value.
Step 5: Stop.
CODE:
#include <stdio.h>
int main() {
int n;
double sum=0.0;
printf("Enter number of terms for the series: ");
scanf("%d", &n);
for (int i=1.0; i<=n; i++)
{ sum+=1.0/i; }
printf("\nThe sum of the series is: %.2f", sum);
return 0;
}
OUTPUT:
DISCUSSION: The program calculates the value of a harmonic series up until n terms,
1 1 1
which is given by the formula: 1 + 2 + 3 + ⋯ + 𝑛 . In this program, we use a sample value 8,
1 1 1 1 1 1 1
which gives us the series: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 2.71786. The printf statement
rounds the float value up to 2 decimal places, so our output is 2.72.
20
ASSIGNMENT 14
PROBLEM STATEMENT: Swap two numbers using call by value and call by reference.
ALGORITHM:
Step 1: Start.
Step 2: Declare the member functions swap() and ref(), and inside main(), declare two
variables int n and int m, to store the two numbers to be swapped.
Step 3: Take the user input for n and m, and pass the values through functions swap() and
ref().
Step 4: Create the function void swap() with integer variables int a and int b, and swap their
values using a temporary variable int temp. Print the swapped values.
Step 5: Create the function void ref() with pointer variables int *x and int *y, and use a
temporary third variable int temp to swap their values. Print the swapped values.
Step 6: The called functions return control to the calling function main() and the program
terminates.
Step 7: Stop.
CODE:
#include<stdio.h>
void swap(int a, int b);
void ref(int *x, int *y);
int main()
{
int n, m;
printf("Enter two numbers:\n");
scanf("%d, %d", &n, &m);
swap(n, m);
ref(&n, &m);
return 0;
}
void swap(int a, int b)
{
int temp=0;
temp=a;
a=b;
b=temp;
printf("SWAPPING USING CALL-BY VALUE\nFirst number and Second number
are now: %d, %d\n\n", a, b);
}
void ref(int *x, int *y)
{
int temp=0;
21
temp=*x;
*x=*y;
*y=temp;
printf("SWAPPING USING CALL-BY REFERENCE\nFirst number and Second
number are now: %d, %d", *x, *y);
}
OUTPUT:
DISCUSSION: In the function swap(), we pass a copy of int n and m and use typical
swapping logic, and return the swapped values. However, in function ref(), we pass the
addresses of the values to pointers, which directly operate on n and m, rather than a copy of n
and m. When we print the swapped values, we use *x and *y instead of just x and y, to
indicate that we are printing the values at those pointer addresses, and not the addresses.
22
ASSIGNMENT 15
PROBLEM STATEMENT: Find the length of a string using pointers.
ALGORITHM:
Step 1: Start.
Step 2: Declare a character array ‘str’ to store the input string and a pointer ‘ptr’ that points
to the beginning of ‘str’ and ask the user to enter a string using scanf.
Step 3: The string is stored in the character array str, and a while-loop is run to increment the
pointer, which starts at the 0 index of the character array and terminates when it comes across
a null character in the string. The variable ‘length’ is incremented each iteration of the loop.
Step 4: The value of int length is returned and printed as the length of the user’s inputted
string.
Step 5: Stop.
CODE:
#include <stdio.h>
int main() {
char str[100];
char *ptr = str;
int length = 0;
printf("Enter a string: ");
scanf("%s", str);
while (*ptr != '\0') {
length++;
ptr++;
} printf("Length of the string: %d\n", length);
return 0;
}
OUTPUT:
DISCUSSION: A while-loop is used to iterate through the string. The loop continues until it
encounters the null character ('\0'), which marks the end of the string. Inside the loop, the
length variable is incremented and the pointer is moved to the next character using ptr++. We
assume that the input string is less than 100 characters long to prevent buffer overflow.
23
ASSIGNMENT 16
PROBLEM STATEMENT: Program to find and print all Fibonacci numbers up to n terms.
ALGORITHM:
Step 1: Start.
Step 2: Take the number of Fibonacci terms to be printed from the user and store it in int n.
Step 3: Print the first two Fibonacci numbers, 0 and 1, which are the initialized values of int a
and int b.
Step 4: Run a for-loop for n iterations starting from the value 2, and print each Fibonacci
number, which is the sum of the previous two numbers.
Step 5: Stop.
CODE:
#include <stdio.h>
int main()
{ int n, a=0, b=1;
printf("Enter number of Fibonacci numbers to be printed: ");
scanf("%d", &n);
printf("\n%d, %d, ", a, b);
int nextTerm;
for (int i=2; i<n; i++)
{ nextTerm = a+b;
a = b;
b = nextTerm;
printf("%d, ", nextTerm); }
return 0; }
OUTPUT:
DISCUSSION: Fibonacci numbers are a series of numbers where each number is the sum of
the preceding two numbers. In this program, the for-loop adds the two integer variables int a
and int b, and uses a variable int nextTerm to store the sum and update the value of int b.
24
ASSIGNMENT 17
PROBLEM STATEMENT: Write a C program to print Pascal's triangle for n rows.
ALGORITHM:
Step 1: Start.
Step 2: Take the number of rows from the user and store it in int rows.
Step 3: Use the first nested for-loop to create the triangle pattern and use the second nested
for-loop to add the two numbers in a row and obtain the number below them in the next row.
Print each element and terminate all the for-loops when the nth row has been printed.
Step 4: Stop.
CODE:
#include <stdio.h>
int main()
{ int rows, coef=1, space, i;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (int i=0; i<rows; i++)
{ for (space=1; space<=rows-i-1; space++)
printf(" ");
coef=1;
for (int j=0; j<=i; j++)
{ printf("%3d ", coef);
coef = coef*(i-j)/(j+1); }
printf("\n"); }
return 0; }
OUTPUT:
25
ASSIGNMENT 18
PROBLEM STATEMENT: Write a C program to find sum of the digits of a number.
ALGORITHM:
Step 1: Start.
Step 2: Take a number from the user and store it in int n. Declare an int remainder and
initialize an int sum=0.
Step 3: Run a while-loop that extracts the last digit of the number n, adds it to sum, and
removes it. This process is repeated until the loop has iterated as many times as there are
digits in the number, i.e. until the value of int n becomes 0.
Step 4: The sum of digits of the number is then printed, after the while-loop terminates.
Step 5: Stop.
CODE:
#include <stdio.h>
int main()
{ int n, sum=0, remainder;
printf("Enter a number: ");
scanf("%d", &n);
while (n!=0)
{ remainder = n%10;
sum+= remainder;
n/=10; }
printf("Sum of digits = %d", sum);
return 0; }
OUTPUT:
DISCUSSION: We use a while-loop to extract the last digit of a number, add it to the sum,
and then remove it from the original number for the next iteration to work on the next digit.
In this program, the loop extracts 5 from 345, adds it to sum and removes it from 345, so that
the next iteration of the loop operates on 34. The process repeats so that we get 3+4+5 = 12.
26
ASSIGNMENT 19
PROBLEM STATEMENT: Write a C program to check if a number is a palindrome or not.
ALGORITHM:
Step 1: Start.
Step 2: Take a number from the user and store it in int n and int original to be compared to
the reversed number later.
Step 3: Run a while-loop that extracts the last digit of the number and makes it the first digit,
storing in int reversed and repeating this process until the number is reversed and the value of
n is 0. Terminate while-loop.
Step 4: Compare the reversed number with the original number, and if they are the same, the
number is a palindrome, otherwise it is not.
Step 5: Stop.
CODE:
#include <stdio.h>
int main()
{ int n, reversed=0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n!=0)
{ remainder = n%10;
reversed = reversed * 10 + remainder;
n/=10; }
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0; }
OUTPUT:
DISCUSSION: The while-loop extracts the last digit, putting it in the first digit’s place, and
then moves on to the next digit, changing it from second-last digit place to second digit. This
process reverses the order of digits in the number. If the number is a palindrome, this order is
the exact same as the original number’s order of digits.
27
ASSIGNMENT 20
PROBLEM STATEMENT: To calculate factorial of a number using recursion.
ALGORITHM:
Step 1: Start.
Step 2: Create a function factorial(int n) to operate on a user input and calculate its factorial
using n*factorial(n-1) as the return value, while calling itself until n reaches the value 1 or 0
and eventually returns a final value.
Step 3: Write the main() function to accept a number from the user and pass it to the function
factorial(), and return and print the value of the number’s factorial.
Step 4: Stop.
CODE:
#include <stdio.h>
long factorial(int n) {
if (n == 0 || n == 1)
{ return 1; }
else
{ return n * factorial(n - 1); }
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0)
{ printf("Invalid (negative number).\n"); }
else
{ printf("Factorial of %d = %ld", num, factorial(num)); }
return 0;
}
OUTPUT:
28
ASSIGNMENT 21
PROBLEM STATEMENT: Write a C program to count the number of vowels and
consonants in a string using a pointer.
ALGORITHM:
Step 1: Start.
Step 2: Declare a character array to hold the user’s entered string and declare a character
pointer ptr to point to the array.
Step 3: Take a string from the user and run a while-loop to check each character of the string,
incrementing the pointer ptr with each iteration.
Step 4: The loop contains an if-statement that increments the consonant counter if the
character matches the ASCII value of a consonant, or else it increments the vowel counter if
the character matches the ASCII value of a vowel. The number of vowels and consonants are
then printed after the pointer encounters a null character ‘\0’.
Step 5: Stop.
CODE:
#include <stdio.h>
int main() {
char str[100];
char *ptr = str;
int vowels = 0, consonants = 0;
printf("Enter a string: ");
scanf("%s", str);
while (*ptr != '\0') {
if (*ptr == 'a' || *ptr == 'e' || *ptr == 'i' || *ptr == 'o' || *ptr == 'u' || *ptr == 'A' || *ptr == 'E' ||
*ptr == 'I' || *ptr == 'O' || *ptr == 'U')
{ vowels++; }
else if (*ptr >= 'a' && *ptr <= 'z' || *ptr >= 'A' && *ptr <= 'Z')
{ consonants++; }
ptr++;}
printf("Vowels: %d\n", vowels);
printf("Consonants: %d", consonants);
return 0;
}
OUTPUT: DISCUSSION:
We declare a character array str of size 100 to store the
string and then have a pointer ptr to point to the
beginning of str. The loop iterates through the string until
a null character is encountered, which marks the end of
the string. It increments either the vowels counter or the
consonants counter depending on whichever condition
the character fulfils. 29
ASSIGNMENT 22
PROBLEM STATEMENT: To read and display multiple strings using pointers.
ALGORITHM:
Step 1: Start.
Step 2: Create an array of pointers to store several strings, and take the number of strings
from the user.
Step 3: After allocating memory for each string, accept each string from the user with the
help of a for-loop. Print them using another for-loop that prints a string character by character
until it encounters a null character ‘\0’ before moving to the next line to print the next string.
Step 4: Stop.
CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str[10]; // array of pointers to store strings
int i, n;
printf("Enter the number of strings: ");
scanf("%d", &n);
for (i = 0; i < n; i++) // allocate memory for each string
{ str[i] = (char *)malloc(100 * sizeof(char));
printf("Enter string %d: ", i + 1);
scanf("%s", str[i]);
}
printf("\nDisplaying Strings:\n");
for (i = 0; i < n; i++)
{ printf("String %d: %s\n", i + 1, str[i]); }
for (i = 0; i < n; i++) // free allocated memory
{ free(str[i]); }
return 0;
}
OUTPUT: DISCUSSION:
We declare an array of pointers to store multiple strings
and store each string in the allocated memory, after using
malloc to make space for each string. After the strings are
printed, we free the allocated memory to avoid memory
leaks. We also assume each string is less than 100
characters.
30
ASSIGNMENT 23
PROBLEM STATEMENT: Write a C program to swap two characters using pointers.
ALGORITHM:
Step 1: Start.
Step 2: Declare a function swap() that takes two char pointers as arguments and performs
swapping logic.
Step 3: In the main() function, take two character variables c1 and c2 from the user, display
them before swapping, and pass them to the swap() function, where they get swapped and
returned. Display the swapped character values.
Step 4: Stop.
CODE:
#include <stdio.h>
void swap(char *a, char *b) {
char temp = *a;
*a = *b;
*b = temp;
}
int main() {
char c1, c2;
printf("Enter first character: ");
scanf(" %c", &c1);
printf("Enter second character: ");
scanf(" %c", &c2);
printf("Before swap: %c %c\n", c1, c2);
swap(&c1, &c2);
printf("After swap: %c %c", c1, c2);
return 0;
}
OUTPUT:
DISCUSSION: We take two char pointers as arguments in the swap function and use a
temporary variable to exchange the values pointed to by a and b. The space before %c in the
scanf statements is used to ignore whitespace characters.
31
ASSIGNMENT 24
PROBLEM STATEMENT: Display all the student names whose CGPA is more than 9,
using a structure.
ALGORITHM:
Step 1: Start.
Step 2: Define a structure called Student with variables char name[100] and float cgpa.
Step 3: Take the number of students from the user in the main function and store it in
variable int n, using this value of n to determine the number of elements or structures in the
array of Student structures.
Step 4: Prompt the user to input data for each student’s name and CGPA using a for-loop to
iterate as many times as number of students entered, and store the data in the structure
variables students[i].name and students[i].cgpa to be processed later.
Step 5: Use another for-loop to check the structure variable students[i].cgpa for each student
and check if their CGPA is greater than 9. If yes, then their name is printed along with their
CGPA.
Step 6: Stop.
CODE:
#include <stdio.h>
struct Student // Defining a structure to represent a student
{ char name[100];
float cgpa;
};
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[n]; // Creating an array of Student structures
for (int i = 0; i < n; i++) // To input student details
{ printf("Enter name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter CGPA of student %d: ", i + 1);
scanf("%f", &students[i].cgpa);
}
printf("\nStudents with CGPA more than 9:\n");
for (int i = 0; i < n; i++) // Displaying students with CGPA more than 9
{ if (students[i].cgpa > 9)
{ printf("%s (%.2f)\n", students[i].name, students[i].cgpa); }
}
return 0;
}
32
OUTPUT:
DISCUSSION: We define a structure called Student, with fields called name and cgpa. After
we take the number of students from the user, we create an array of n Student structures, and
then ask the user to input the name of each student along with their CGPA.
We then run a for-loop that goes through each structure variable with the cgpa field and
checks if the user input for the CGPA is greater than 9 or not. After all the structures have
been iterated through, we print the names and CGPAs of the students who have a CGPA of 9
or more.
33
ASSIGNMENT 25
PROBLEM STATEMENT: Write a program in C to accept numbers till a negative number
is entered and calculate the sum of a list of numbers read, using static variable.
ALGORITHM:
Step 1: Start.
Step 2: Take numbers from a user continuously until a negative number is entered, with the
help of recursion. If the number is greater than 0, call calculateSum() inside itself and add the
positive number to the static variable int sum, which will retain its value between function
calls. When a negative number is eventually entered, the sum of the numbers is printed.
Step 3: Stop.
CODE:
#include <stdio.h>
void calculateSum() {
static int sum = 0; // Static variable
int num;
printf("Enter a number (negative number for termination): ");
scanf("%d", &num);
if (num < 0)
{ printf("Sum: %d\n", sum); }
else {
sum += num;
calculateSum(); }
}
int main() {
calculateSum();
return 0; }
OUTPUT:
DISCUSSION: Here, the static variable int sum will retain its value between function calls
in the recursive function calculateSum(), and is initialized only once at program startup.
34