0% found this document useful (0 votes)
197 views71 pages

PPS Lab Record

The document describes a C program that demonstrates various data types by printing their values and discussing their memory usage and ranges. It includes programs that print the values of variables of different data types, as well as programs that output the minimum and maximum ranges of each data type and the number of bytes allocated to each one. The programs execute successfully and demonstrate the key properties of C data types.

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views71 pages

PPS Lab Record

The document describes a C program that demonstrates various data types by printing their values and discussing their memory usage and ranges. It includes programs that print the values of variables of different data types, as well as programs that output the minimum and maximum ranges of each data type and the number of bytes allocated to each one. The programs execute successfully and demonstrate the key properties of C data types.

Uploaded by

Pavan Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)

1) Write a C program to demonstrate various data types.


Aim: To demonstrate various data types in C language.
Description:
Data types in the c programming language are used to specify what kind of value can be stored in
a variable. The memory size and type of the value of a variable are determined by the variable
data type. In a c program, each variable or constant or array must have a data type and this data
type specifies how much memory is to be allocated and what type of values are to be stored in
that variable or constant or array. The formal definition of a data type is as follows

The Data type is a set of value with predefined characteristics. Data types are used to declare
variable, constants, arrays, pointers, and functions.

In the c programming language, data types are classified as follows.

Primary data types (Basic data types OR Predefined data types)


Derived data types (Secondary data types OR User-defined data types)
Enumeration data types
Void data type

Various primitive data types are:


VOID:
void
CHAR:
char
signed char
unsigned char
INT:
short int
unsigned short int
signed short int
int
unsigned int
signed int
long int
unsigned long int
signed long int
long long int
unsigned long long int
signed long long int
FLOAT:
float
double
long double

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
2

Program:
#include<stdio.h>

int main()
{
char a='A';
signed char b ='z';
unsigned char c ='!';

short int d=-4000;


signed short int e=-344;
unsigned short int f=6789;

int g=-120;
signed int h= -6778382;
unsigned int i=689;

long int j =-23444884;


signed long int k = -2388388888;
unsigned long int l =26363773;

long long int m =-2337477388373737744;


signed long long int n =-663727277777777;
unsigned long long int o =373737377373773;

float p=3.456789;
double q = 2.333484873738;
long double r =6727272789.123456789;

printf("\ncharacter %c", a);


printf("\nsigned char %c", b) ;
printf("\nunsigned char %c", c);

printf(" \n short int is %hd", d);


printf("\n signed short int is %hi ", e);
printf("\n unsigned short int is %hu", f) ;

printf("\n integer %d", g);


printf("\n signed integer %i", h);
printf("\n unsigned integer %u", i);

printf("\n long int %ld", j);


printf("\n signed long int %li", k);
printf("\n unsigned long int %lu", l);

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
3

printf("\n long long int %lld", m);


printf("\n signed long long int %lli", n);
printf("\n unsigned long long int %llu", o);

printf("\n float %f", p);


printf("\n double %lf", q);
printf("\n long double %Lf ", r);

return 0;
}

Output:
character: A
signed char: z
unsigned char: !
short int is: -4000
signed short int is: -344
unsigned short int is: 6789
integer: -120
signed integer: -6778382
unsigned integer: 689
long int: -23444884
signed long int: -238838688
unsigned long int: 26363773
long long int: -2337477388373737744
signed long long int: -663727277777777
unsigned long long int: 373737377373773
float: 3.456789
double: 23456.333485
long double: 96854751235.587448
Case 1: if value assigned to given variable of data type is in range of it's data type we get same
assigned value
suppose int a=-120;
We get int a value as -120;

Case2: if value assigned to given variables not in range of its data type then we get the value in
next in CYCLE
suppose int a= -6000000000;
We get -1705032704;
Result: The program to demonstrate various data types in C are executed successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
4

Viva Questions:
1) Define data type?
2) What is the use of data type?
3) What are examples primitive data types?
4) Where can you declare data type of a variable?
5) What are sub branching data types in float?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
5

2) Write a C program to display minimum and maximum ranges different data types.
Aim: To demonstrate maximum and minimum ranges of different data types in C.
Description:
Data ranges of a data type arises from the combinations of values which can be represented from
the amount of memory assigned for a single unit of the single data type, and how those possible
combinations are assigned to actual values that they represent.
Range means the maximum and minimum value that can be stored inside the variable of a given
type. For example in comparing unsigned byte and signed byte, their ranges are different:
unsigned byte: 0 to 255 signed byte: -128 to 127. However, they are both having 256 possible
combinations of values they can represent. They only differ by the range of values they can
represent. That's the range of a data type.
If a value of variable cross the range of particular data type it prints next value in cyclic order.
Type Typical Bit Typical Range
Width

char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255

signed char 1byte -127 to 127

int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295

signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767

unsigned short int 2bytes 0 to 65,535

signed short int 2bytes -32768 to 32767

long int 8bytes -2,147,483,648 to 2,147,483,647

signed long int 8bytes same as long int

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
6

unsigned long int 8bytes 0 to 4,294,967,295

long long int 8bytes -(2^63) to (2^63)-1

unsigned long long 8bytes 0 to 18,446,744,073,709,551,615


int

float 4bytes

double 8bytes

long double 16bytes

Program:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>

int main()
{
printf("CHAR_MAX : %d\n", CHAR_MAX);
printf("CHAR_MIN : %d\n", CHAR_MIN);
printf("SCHAR_MAX : %d\n", SCHAR_MAX);
printf("SCHAR_MIN : %d\n", SCHAR_MIN);
printf("UCHAR_MAX : %d\n", UCHAR_MAX);

printf("SHRT_MAX : %d\n", SHRT_MAX);


printf("SHRT_MIN : %d\n", SHRT_MIN);
printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX);

printf("INT_MAX : %d\n", INT_MAX);


printf("INT_MIN : %d\n", INT_MIN);
printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX);

printf("LONG_MAX : %ld\n", (long) LONG_MAX);


printf("LONG_MIN : %ld\n", (long) LONG_MIN);
printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX) ;

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
7

printf("FLT_MAX : %g\n", (float) FLT_MAX);


printf("FLT_MIN : %g\n", (float) FLT_MIN);
printf("DBL_MAX : %g\n", (double) DBL_MAX);
printf("DBL_MIN : %g\n", (double) DBL_MIN);

return 0;
}

Output:
CHAR_MAX : 127
CHAR_MIN : -128
SCHAR_MAX : 127
SCHAR_MIN : -128
UCHAR_MAX : 255
SHRT_MAX : 32767
SHRT_MIN : -32768
USHRT_MAX : 65535
INT_MAX : 2147483647
INT_MIN : -2147483648
UINT_MAX : 4294967295
LONG_MAX : 2147483647
LONG_MIN : -2147483648
ULONG_MAX : 4294967295
FLT_MAX : 3.40282e+038
FLT_MIN : 1.17549e-038
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308

Result: The program to display minimum and maximum ranges is executed successfully.

Viva Questions:
1) What is meant by range of data type?
2) What header files needed to find ranges?
3) What is the range of signed char?
4) What is the range of short?
5) What is the range of unsigned?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
8

3) Write a C program to print number of bytes allocated for every data type.
Aim: To print number of bytes allocated for each data type.
Description:
Data types in C refer to an extensive system used for declaring variables or functions of different
types. The type of a variable determines how much space it occupies in storage and how the bit
pattern stored is interpreted.
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. Let us briefly describe
them one by one:

Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single
precision.
double: It is used to store decimal numbers (numbers with floating point value) with double
precision.
sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be
used to compute the size of its operand. sizeof can be applied to any data-type, including
primitive types such as integer and floating-point types, pointer types, or compound data types
such as Structure, union etc.

Program:
#include<stdio.h>

int main()
{
printf("\n Size of char is: %ld", sizeof (char));
printf("\n Size of signed char is: %ld", sizeof (signed char));
printf("\n Size of unsigned char is: %ld", sizeof (unsigned char));

printf("\n Size of short integer is: %ld", sizeof (short int));


printf("\n Size of signed short integer is: %ld", sizeof (signed short int));
printf("\n Size of unsigned short integer is: %ld", sizeof (unsigned short int));

printf("\n Size of integer is: %ld", sizeof (int));


printf("\n Size of signed integer is: %ld", sizeof (signed int));
printf("\n Size of unsigned integer is: %ld", sizeof (unsigned int));

printf("\n Size of long integer is: %ld", sizeof (long int));


printf("\n Size of signed long integer is: %ld", sizeof (signed long int));
printf("\n Size of unsigned long integer is: %ld", sizeof (unsigned long int));

printf("\n Size of long long integer is: %ld", sizeof (long long int));

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
9

printf("\n Size of signed long long integer is: %ld", sizeof(signed long long int));
printf("\n Size of unsigned long long integer is: %ld", sizeof(unsigned long long int));

printf("\n Size of float is: %ld", sizeof(float));


printf("\n Size of double is: %ld", sizeof(double));
printf("\n Size of long double is: %ld", sizeof(long double));

return 0;
}

Output:
Size of char is: 1
Size of signed char is: 1
Size of unsigned char is: 1
Size of short integer is: 2
Size of signed short integer is: 2
Size of unsigned short integer is: 2
Size of integer is: 4
Size of signed integer is: 4
Size of unsigned integer is: 4
Size of long integer is: 4
Size of signed long integer is: 4
Size of unsigned long integer is: 4
Size of long long integer is: 8
Size of signed long long integer is: 8
Size of unsigned long long integer is: 8
Size of float is: 4
Size of double is: 8
Size of long double is: 16

Result: The program to find size of every data type is executed successfully.

Viva Questions:
1) What is the size of signed character?
2) What is the size of unsigned integer?
3) What is the size of long long int?
4) What is the size of double?
5) What is the size of long double?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
10

4) Write a C program to check whether the entered year is leap year or not.
Aim: To check whether the entered year is leap year or not using else if ladder.
Description:
A leap year is a year, which is different than a normal year having 366 days instead of 365.
A leap year comes once in four years, in which February month has 29 days. With this additional
day in February, a year becomes a Leap year.
A leap year is exactly divisible by 4 except for century years (years ending with 00). The
century year is a leap year only if it is perfectly divisible by 400.
For example,
1999 is not a leap year
2000 is a leap year
1900 is not a leap year

Program:
#include <stdio.h>

int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);

// leap year if perfectly divisible by 400


if (year % 400 == 0) {
printf("%d is a leap year.", year);
}
// not a leap year if divisible by 100 but not divisible by 400
else if (year % 100 == 0) {
printf("%d is not a leap year.", year);
}
// leap year if not divisible by 100 but divisible by 4
else if (year % 4 == 0) {
printf("%d is a leap year.", year);
}
// all other years are not leap years
else {
printf("%d is not a leap year.", year);
}
return 0;
}

Output:
Case 1
Enter a year: 1900
1900 is not a leap year.
Case 2

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
11

Enter a year: 2012


2012 is a leap year.

Result: The program to check whether or not entered year is leap year is successfully executed.

Viva Questions:
1) What are conditional branching statements in C?
2) What are unconditional branching statements in C?
3) Write the syntax of if-else.
4) What is null else?
5) Write syntax of nested if.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
12

5) Write a C program to find the roots of a quadratic equation.


Aim: To find the roots of a quadratic equation.
Description:
Quadratic equations are the polynomial equation with degree 2. It is represented as ax2 + bx +c =
0, where a, b and c are the coefficient variable of the equation. The universal rule of quadratic
equation defines that the value of 'a' cannot be zero, and the value of x is used to find the roots of
the quadratic equation (a, b). A quadratic equation's roots are defined in three ways: real and
distinct, real and equal, and real and imaginary.
For a quadratic equation ax2+ bx + c = 0 (a≠0), discriminant (b2-4ac) decides the nature of roots.
The term b2-4ac is known as the discriminant of a quadratic equation. It tells the nature of the
roots.
If the discriminant is greater than 0, the roots are real and different.
If the discriminant is equal to 0, the roots are real and equal.
If the discriminant is less than 0, the roots are complex and different.

Program:
#include<stdio.h>
#include<math.h> // it is used for math calculation

int main()
{
float a, b, c, det, root1, root2, real, img;
printf("Enter the value of coefficient a, b and c: \n ");
scanf("%f %f %f", &a, &b, &c);
// define the quadratic formula of the nature of the root
det = b * b - 4 * a * c;
// defines the conditions for real and different roots of the quadratic equation
if (det > 0)
{
root1 = (-b + sqrt(det)) / (2 * a);
root2 = (-b + sqrt(det)) / (2 * a);
printf("\n Value of root1 = %.2f and value of root2 = %.2f", root1, root2);
}
// elseif condition defines both roots (real and equal root) are equal in the quadratic equation
else if (det == 0)
{
root1 = root2 = -b / (2 * a); // both roots are equal;
printf("\n Value of root1 = %.2f and Value of root2 = %.2f", root1, root2);
}
// if det < 0, means both roots are real and imaginary in the quadratic equation.
else {
real = -b / (2 * a);
img = sqrt(-det) / (2 * a);
printf("\n value of root1 = %.2f + %.2fi and value of root2 = %.2f - %.2fi ", real, img, real,
img);

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
13

}
return 0;
}

Output:
Case 1:
Enter the value of coefficient a, b and c:
1.0
4.0
3.0
Value of root1 = -1.00 and value of root2 = -1.00
Case 2:
Enter the value of coefficient a, b and c:
1.0
1.0
4.0
Value of root1 = -0.50 + 1.94i and value of root2 = -0.50 - 1.94i
Case 3:
Enter the value of coefficient a, b and c:
8.0
-4.0
-2.0
Value of root1 = 0.81 and value of root2 = 0.81

Result: The program to find the roots of a quadratic equation is executed successfully.

Viva Questions:
1) Write the syntax of simple if statement?
2) Write an example of nested if-else statement?
3) What is else if ladder?
4) What is dangling else problem?
5) Shall we use break in if condition?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
14

6) Write a C program to make a simple calculator using switch-case.


Aim: To develop a simple calculator using switch-case.
Description:
Switch case statements are a substitute for long if statements that compare a variable to several
integral values.
The switch statement is a multi-way branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Syntax:
switch (n)
{
case 1: // code to be executed if n = 1;
break;
case 2: // code to be executed if n = 2;
break;
default: // code to be executed if n doesn't match any cases
}
Important Points about Switch Case Statements:

1. The expression provided in the switch should result in a constant value otherwise it would not
be valid.
// Constant expressions allowed
// Variable expression are not allowed
2. Duplicate case values are not allowed.
3. The default statement is optional. Even if the switch case statement do not have a default
statement, it would run without any problem.
4. The break statement is used inside the switch to terminate a statement sequence. When a break
statement is reached, the switch terminates, and the flow of control jumps to the next line
following the switch statement.
5. The break statement is optional. If omitted, execution will continue on into the next case. The
flow of control will fall through to subsequent cases until a break is reached.
6. Nesting of switch statements are allowed, which means you can have switch statements inside
another switch. However nested switch statements should be avoided as it makes program more
complex and less readable.

Program:
#include<stdio.h>

int main()
{
// Declaration of variables
int num1, num2;
char op;
printf("Enter any two values: ");
scanf("%d%d", &num1, &num2);
fflush(stdin); // To clear the input buffer

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
15

printf("Enter an operator (+, -, *, /, %): ");


scanf("%c", &op);

switch(op)
{
case '+': printf("\nThe sum is: %d", num1+num2);
break;
case '-': printf("\nThe difference is: %d", num1-num2);
break;
case '*': printf("\nThe product is: %d", num1*num2);
break;
case '/': printf("\nThe Quotient is: %f", (float) num1/num2);
break;
case '%': printf("\nThe Remainder is: %d", num1%num2);
break;
default: printf("\n**Choose Right Choice!**");
}
return 0;
}

Output:
Case 1:
Enter any two values: 9 8
Enter an operator(+, -, *, /, ): *

The product is: 72


Case 2:
Enter any two values: 9 8
Enter an operator(+, -, *, /, ): -

The difference is: 1


Case 3:
Enter any two values: 9 8
Enter an operator(+, -, *, /, ): /

The Quotient is: 1.13

Result: The simple calculator for arithmetic operators is developed successfully.

Viva-voce Questions:
1) What is a switch?
2) What are allowed as case values?
3) When will be the default case executed?
4) What is break?
5) Do switch statement contain duplicated cases?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
16

7) Write a C program to print prime numbers with in the given range.


Aim: To print prime numbers with in the given range.
Description:
Any whole number which is greater than 1 and has only two factors that is 1 and the number
itself, is called a prime number.
Other than these two number it has no positive divisor.
For example: 7 = 1 × 7
To check whether 13 is prime or not, generally we consider the divisors 2, 3 only.
Here we can conclude that only odd can be checked apart from 2 and no need to check all factors
we can stop checking when we encounter square root of the number.
Program:
#include <stdio.h>
#include <math.h>

int main()
{
int i, j, m, n, count=0;
printf("Enter two numbers to print primes within the range: ");
scanf("%d%d",&m, &n);
printf("\n Prime numbers in given range are: ");
for (i=m;i<=n;i++)
{
for ( j = 2;j <= sqrt(i);j++)
{
if(i%j == 0)
{
count++;
}
}
if(count == 0)
printf("%d\t", i);
count = 0;
}
return 0;
}
Output:
Case 1:
Enter two numbers to print primes within the range: 5 13
Prime numbers in given range are: 5 7 11 13
Case 2:

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
17

Enter two numbers to print primes within the range: 3 25


Prime numbers in given range are: 3 5 7 11 13 17 19 23

Result: The program to print prime numbers is executed successfully.

Viva Questions:
1) What are iterative statements that are available in C?
2) What is the difference between Sentinel and Counter Controlled Loop in C?
3) Write the for loop syntax.
4) Do we have for() without body?
5) Is all fields in for loop are mandatory?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
18

8) Write a C program to check whether the given number is a palindrome number or not?
Aim: To check whether or not the given number is a palindrome.
Description:
An integer is a palindrome if the reverse of that number is equal to the original number.
A palindrome number is one that remains the same on reversal.
Some examples are 8, 121, 212, 12321, -454.
To check if a number is a palindrome or not, we reverse it and compare it with the original
number.
If both are the same, it's a palindrome otherwise not.
Program:
#include<stdio.h>

int main()
{
int n, m = 0, r, t;
printf("Enter the number to check for Palindrome: ");
scanf("%d",&n);
t=n; //store the number you want to check
while(n>0) //to reverse given number
{
r=n%10;
m=m*10+r;
n=n/10;
}
if(m == t) // to check given number and reversed number
printf("**Number is a Palindrome**");
else
printf("**Number is not a Palindrome**");
return 0;
}
Output:
Case 1:
Enter the number to check for Palindrome: 1
**Number is a Palindrome**
Case 2:
Enter the number to check for Palindrome: 12
**Number is not a Palindrome**
Case 3:

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
19

Enter the number to check for Palindrome: 12321


**Number is a Palindrome**
Case 4:
Enter the number to check for Palindrome: -4568
**Number is not a Palindrome**

Result: The program to check whether the given number is palindrome or not is executed
successfully.
Viva Questions:
1) What is pretest and posttest loop in C?
2) Is while pre-condition checked loop?
3) What is a palindrome?
4) Is it correct to use do while instead of while if yes how?
5) What do think about a palindrome of negative number?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
20

9) Write a C program to print the following pattern


A
AB
ABC
ABCD
ABCDE
Aim: To write a C program to print the right angle triangle/Half pyramid pattern.
Description:
Pattern programs are nothing but patterns consisting of numbers, alphabets or symbols in a
particular form. These kinds of pattern programs can be solved easily using for loop condition.
Letter patterns are groups of letters that often appear together in many different forms they
appear with a similarity.
We can observe that, each row contain number of uppercase alphabets in an order equal to it's
corresponding row number.
That is row1/line1 has 'A' one letter and it's 1st row similarly 2nd row has 2 alphabets of
uppercase 'AB'.

Program:
#include<stdio.h>

int main()
{
int i, j, k, n;
printf("Enter positive value of n: ");
scanf("%d", &n);
for(i = 1;i <= n;i++)// to print n lines
{
k=65;
for(j=1;j<=i;j++)
{
printf("%c",k); //to print alphabets
k++;
}
printf("\n");
}
return 0;
}

Output:
Case 1:
Enter positive value of n: 1
A
Case 2:
Enter positive value of n: 5
A

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
21

AB
ABC
ABCD
ABCDE
Case 3:
Enter positive value of n: 10
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ

Result: The program to print right angle triangle using alphabets is executed successfully.

Viva Questions:
1) What is a nested loop?
2) How many number of times the body of nested loop will execute?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
22

10) Write a C program to search for an element in an array using linear search.
Aim: To find the element position in an Array using Linear search.
Description:
A linear search, also known as a sequential search, is a method of finding an element within a
list. It checks each element of the list sequentially until a match is found or the whole list has
been searched.
A simple approach is to do a linear search, i.e
 Start from the leftmost element of arr[] and one by one compare x with each element of
arr[].
 If x matches with an element, return the index.
 If x doesn’t match with any of elements, return -1.
Program:
#include<stdio.h>

int main()
{
int arr[100]; // Declaration of an array
int n, i, key;
printf("\nEnter number of Elements: ");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &arr[i]); // Reading values in to an array
printf("\nEnter an Element to be Searched: ");
scanf("%d", &key); // reading element to be searched
for(i=0;i<n;++i)
{
if(key==arr[i])
break;
}
if(i==n)
printf("\nElement is not Available.");
else
printf("\nThe element is present at index: %d", i);
return 0;
}

Output:
Case 1:
Enter number of Elements: 8
91357486
Enter an Element to be Search: 7
The element is present at index: 4

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
23

Case 2:
Enter number of Elements: 8
91357486
Enter an Element to be Search: 2
Element is not Available.

Result: The program to find the given element executed successfully.

Viva Questions:
1) What is an array?
2) Write the example of declaring an array with 1000 elements?
3) Arrays are comes under static memory allocation or dynamic memory allocation?
4) What is linear search?
5) What is the difference between linear and binary search?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
24

11) Write a C program sort given list of elements using selection sort.
Aim: To Sort the list of Array elements by using Selection sort.
Description:
The selection Sort is assaulting algorithm that works by finding the smallest number from the
array and then placing it to the first position. The next array that is to be traversed will start from
index next to the position where the smallest number is placed.
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.

1) The subarray which is already sorted.

2) Remaining subarray which is unsorted.


In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray.

Program:
#include<stdio.h>

int main()
{
int arr[100], i, j, n, x, jpos, ipos, temp;
// Reading size of data
printf("\n Enter number of Elements: ");
scanf("%d", &n);
// Reading input data
printf("\n Enter Elements: ");
for(i=0;i<n;++i)
scanf("%d", &arr[i]);
//Sorting data
for(i=0;i<n-1;++i) // 9 8 7 6 5
{
ipos = i; // 0
for(j=i+1;j<n;++j) // 1<5, 2<5, 3<5, 4<5, 5<5
{
if(arr[j]<arr[ipos]) // 8<9, 7<8, 6<7, 5<6
ipos = j; // 1, 2, 3, 4
}
temp = arr[ipos];
arr[ipos]=arr[i];
arr[i]=temp;
}
printf("\nThe elements after sorting: ");
for(i=0;i<n;++i)
printf("%d ", arr[i]);
return 0;

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
25

Output:
Case 1:
Enter number of Elements: 8
Enter Elements: 9 1 3 5 7 6 4 8
The elements after sorting: 1 3 4 5 6 7 8 9
Case 2:
Enter number of Elements: 8
Enter Elements: -9 -1 -3 -5 -7 -6 -4 -8
The elements after sorting: -9 -8 -7 -6 -5 -4 -3 -1

Result: The program to sort the given list of elements is executed successfully.

Viva Questions:
1) What is sorting?
2) What is the difference between searching and sorting?
3) Is your program works for sorting elements in descending order?
4) Is it possible to sort the given set of elements with single loop?
5) Tell me few any other sorting techniques?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
26

12) Write a C program to read a line of text and count upper case and lower case letters.
Aim: To read a line of text and count upper case and lower case letters.
Description:
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus
a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the string
is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";

Program:
#include<stdio.h>

int main()
{
int i, upper_case_count = 0, lower_case_count = 0;
char C[100];
printf("\nEnter a line of text: ");
gets(C);
i = 0;
while(C[i]!= '\0')
{
if(C[i] >='A' && C[i]<='Z')
upper_case_count++;
else if (C[i] >='a' && C[i]<='z')
lower_case_count++;
i++;
}
printf("\nUpper Case Letters are: %d", upper_case_count);
printf("\nLower Case Letters are: %d", lower_case_count);
return 0;
}

Output:
Enter a line of text: PVP Siddhartha Institute of Technology
Upper Case Letters are: 6
Lower Case Letters are: 28

Result: The program to count the number of upper case and lower case letters are executed
successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
27

Viva Questions:
1) What is the full form of ASCII?
2) How many memory locations are required to store a string with length 5?
3) What is the delimiter character of a string?
4) If I have a character array of size 15 and string stored in it of size 10. What about the values of
remaining memory locations?
5) Write the syntax of declaring character array.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
28

13) Write a C program to perform addition of 2 mxn matrices.


Aim: To perform addition of 2 mxn matrices.
Description:
Enter the number of rows r and columns c. Then, the user is asked to enter the elements of the
two matrices (of order rxc).
We then added corresponding elements of two matrices and saved it in another matrix (two-
dimensional array). Finally, the result is printed on the screen.
Matrix addition in C language to add two matrices, i.e., compute their sum and print it. A user
inputs their orders (number of rows and columns) and the matrices. For example, if the order is
2, 2, i.e., two rows and two columns and the matrices are:

First matrix:
12
34
Second matrix:
45
-1 5
The output is:
57
29

Program:
#include <stdio.h>

int main()
{
int i,j,a,b,c,d;
printf("Enter the number of rows and columns of 1st matrix :\n");
scanf("%d%d",&a,&b);
printf("Enter the number of rows and columns of 2nd matrix :\n");
scanf("%d%d",&c,&d);
if(a==c && b==d)
{
int A[a][b],B[c][d], sum[a][b];
printf("Enter the 1st matrix elements");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
scanf("%d", &A[i][j]);
}
}
printf("Enter the 2nd matrix elements");
for(i=0;i<c;i++)
{

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
29

for(j=0;j<d;j++)
{
scanf("%d",&B[i][j]);
}
}
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
sum[i][j]=A[i][j]+B[i][j];
printf("%d\t",sum[i][j]);
}
printf("\n");
}
}
else
printf("\nThe matrices cannot be added. ");
return 0;
}

Output:
Enter the number of rows and columns of 1st matrix: 2 2
Enter the number of rows and columns of 2nd matrix: 2 2
Enter the 1st matrix elements: 1 2 3 4
Enter the 2nd matrix elements: 1 2 3 4
2 4
6 8

Result: The program to add two matrices is executed successfully.


Viva Questions:
1) Write the syntax of 2D array?
2) How many number of elements are there in array A[2][3]?
3) Is two loops are required to read elements into a 2D array?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
30

14) Write a C program to perform multiplication of 2 matrices.


Aim: To write a program to perform multiplication of matrices.
Description:
We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user
for row number, column number, first matrix elements and second matrix elements. Then we are
performing multiplication on the matrices entered by the user.
In matrix multiplication first matrix one row element is multiplied by second matrix all column
elements.
Matrix multiplication in C language to calculate the product of two matrices (two-dimensional
arrays). A user inputs the orders and elements of the matrices. If the multiplication isn't possible,
an error message is displayed. You may have studied the method to multiply matrices in
Mathematics.

Program:
#include <stdio.h>

int main()
{
int i,j,k,a,b,c,d;
printf("Enter the size of row and column of 1st matrix: ");
scanf("%d%d",&a,&b);
printf("Enter the size of row and column of 2nd matrix: ");
scanf("%d%d",&c,&d);
int A[a][b],B[c][d], mul[a][d];
if(b==c)
{
printf("Enter the 1st matrix elements: ");
for(i=0;i<a;i++)
{
for(j=0;j<b;j++)
{
scanf("%d",&A[i][j]);
}
}
printf("Enter the 2nd matrix elements: ");
for(i=0;i<c;i++)
{
for(j=0;j<d;j++)
{
scanf("%d",&B[i][j]);
}
}
printf("multiplication of the matrix=\n");
for(i=0;i<a;i++)
{

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
31

for(j=0;j<d;j++)
{
mul[i][j]=0;
for(k=0;k<b;k++)
{
mul[i][j]+= A[i][k]*B[k][j];
}
}
}
for(i=0;i<a;i++)
{
for(j=0;j<d;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
}
else
printf("The two matrices cannot be multiplied");
return 0;
}

Output:
Enter the size of row and column of 1st matrix: 2 3
Enter the size of row and column of 2nd matrix: 3 2
Enter the 1st matrix elements: 1 2 3 4 5 6
Enter the 2nd matrix elements: 1 2 3 4 5 6
multiplication of the matrix=
22 28
49 64

Result: The program to multiply 2 Matrices are executed successfully.

Viva Questions:
1) What is 2 Dimensional array?
2) Can we have 2D character arrays?
3) Can we have 2D floating point arrays?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
32

15) Write a C program to add three-dimensional array.


Aim: To write a C program to add three-dimensional array.
Description:
A 3D array is a multi-dimensional array(array of arrays). A 3D array is a collection of 2D arrays.
It is specified by using three subscripts:Block size, row size and column size. More dimensions
in an array means more data can be stored in that array.
int arr[3][3][3], now it becomes a 3D array.
int shows that the 3D array is an array of type integer.
arr is the name of array.
first dimension represents the block size(total number of 2D arrays).
second dimension represents the rows of 2D arrays.
third dimension represents the columns of 2D arrays.

i.e; int arr[3][3][3], so the statement says that we want three such 2D arrays which consists of 3
rows and 3 columns.
Declaring a 3D array:
To declare 3D array:
Specify data type, array name, block size, row size and column size.
Each subscript can be written within its own separate pair of brackets.
Syntax: data_type array_name[block_size][row_size][column_size];

example:
int arr[2][3][3]; //array of type integer
//number of blocks of 2D arrays:2 |rows:3 |columns:3
//number of elements:2*3*3=18
Program:
#include <stdio.h>

int main()
{
int MDArray[2][3][2], sum = 0;
printf("Enter 12 values: ");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &MDArray[i][j][k]);
}
}
}
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
33

{
for (int k = 0; k < 2; ++k)
{
sum+=MDArray[i][j][k];
}
}
}
printf("\nThe Sum of Multi-Dimensional Array is: %d", sum);
return 0;
}

Output:
Enter 12 values: 1 2 3 4 5 6 7 8 9 10 11 12
The Sum of Multi-Dimensional Array is: 78

Result: The program to add elements of a multi-dimensional array is executed successfully.

Viva Questions:
1) What is multi-dimensional array?
2) How many elements are there in A[2][3][4][5]?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
34

16) Write a C program to find the length of a given string.


Aim: To find length of the string without using strlen() function.
Description:
Length of a string can be found by scanning the string, character by character until an NULL
character '\0' is encountered. Whenever a string is defined in C then by default the terminating
character of the string is ‘\0’. This character is extremely helpful in C as it can be used to solve
many problems like - to find the length of a string without using any library function (strlen()), to
concatenate two strings without using any library function (strcat()) , to compare two strings
without using any library function (strcmp()) etc. The ‘\0’ is the only character that can be used
as a condition to determine the end of a string.

Program:
#include <stdio.h>

int main()
{
char s[100]; // Declaration of character array
int i, length=0;
// Reading of input string
printf("Enter a string: ");
gets(s);
// set array index to 0
i = 0;
while(s[i] != '\0') // check for NULL character (end of the string)
{
length++; // increment length variable
++i;
}
// Print the length if a string
printf("Length of string: %d", length);
return 0;
}

Output:
Case 1:
Enter a string: Prasad potluri
Length of string: 14
Case 2:
Enter a string: PVPSIT
Length of string: 6
Case 3:
Enter a string: (Press Enter button)
Length of string: 0

Result: The program to find length of a string is executed successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
35

Viva Questions:
1) Explain strlen().
2) What is end of the string character?
3) Explain gets().
4) What is the difference between scanf() and gets().
5) Explain getchar().

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
36

17) Write a C program to compare the given two strings.


Aim: To compare two strings using built-in functions.
Description:
The strcmp() compares two strings character by character. If the strings are equal, the function
returns 0.
C strcmp() Prototype
The function prototype of strcmp() is:
int strcmp (const char* str1, const char* str2);
strcmp() Parameters
The function takes two parameters:
str1 - a string
str2 - a string

Return Value from strcmp()


Return
Remarks
Value

0 if strings are equal

>0 if the first non-matching character in str1 is greater (in ASCII) than that of str2.

<0 if the first non-matching character in str1 is lower (in ASCII) than that of str2.
The strcmp() function is defined in the string.h header file.

Program:
#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
int result;
// comparing strings str1 and str2
result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d", result);
if(result==0)
printf("\nBoth the Strings are Equal");
else
printf("\nBoth the Strings are not Equal");
// comparing strings str1 and str3
result = strcmp(str1, str3);
printf("\nstrcmp(str1, str3) = %d", result);
if(result==0)
printf("\nBoth the Strings are Equal");

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
37

else
printf("\nBoth the Strings are not Equal");
return 0;
}

Output:
strcmp(str1, str2) = 32
Both the Strings are not Equal
strcmp(str1, str3) = 0
Both the Strings are Equal

Result: The program to compare two strings using strcmp() is executed successfully.
In the program,
(strings str1 and str2 are not equal. Hence, the result is a non-zero integer.)
(strings str1 and str3 are equal. Hence, the result is 0.)

Viva Questions:
1) Write the prototype of strcmp().
2) Write the prototype of strncmp().
3) Explain strcpy().
4) Explain strncpy().
5) Explain strcat().

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
38

18) Write a function to calculate area and perimeter of a circle.


Aim: To calculate area and perimeter of a circle using functions.
Description:
A circle is a simple geometrical shape. A circle is a set of all points in a 2D plane that are at a
given distance from a given point called centre. A circle can be uniquely identified by it's center
co-ordinates and radius.
In geometry, the area enclosed by a circle of radius r is πr 2. Here the Greek letter π represents a
constant, approximately equal to 3.14159, which is equal to the ratio of the circumference of any
circle to its diameter.
Circumference is the linear distance around the edge of a circle. It is the length of the curved line
which defines the boundary of a circle. The perimeter of a circle is called the circumference.
Perimeter of a circle = 2 π r = π D
where,
r = radius of the circle
D = diameter of the circle.
Program:
#include <stdio.h>
#define PI 3.14159
// function prototype declaration
float find_area(int);
float find_perimeter(int);

int main() {
int radius;
float area, perimeter;
printf("Enter radius: ");
scanf("%d", &radius);
//call Area function
area = find_area(radius);
//Call Perimeter function
perimeter = find_perimeter(radius);
// Print area and perimeter
printf("Area of the Circle = %f square inches\n", area);
printf("Perimeter of the Circle = %f inches\n", perimeter);
return(0);
}
//called function
float find_area(int r)
{
return (PI*r*r); // return area to calling function
}
float find_perimeter(int r)
{
return (2*PI*r); // return perimeter to calling function
}

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
39

Output:
Case 1:
Enter radius: 6
Area of the Circle = 113.097237 square inches
Perimeter of the Circle = 37.699081 inches
Case 2:
Enter radius: 12
Area of the Circle = 452.388947 square inches
Perimeter of the Circle = 75.398163 inches

Result: The program to calculate area and perimeter of a circle is executed successfully.

Viva Questions:
1) What is a function?
2) What are the different types of functions?
3) What are the categories of user defined functions?
4) What is called function?
5) What is calling function?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
40

19) Write a function to find sum of array elements passing array as an argument.
Aim: To find sum of array elements passing array as an argument.
Description:
The function sumofarray() is the user defined function which calculates the sum of all array
elements of an array.
The main() function calls the sumofarray() function by passing an array, size of an array.
The function sumofarray(int a[], int n) adds the each element of the array to the sum value using
for loop with the structure for(i=0;i<n;i++) and returns the sum value to main() function.
The main() function prints the sum value which contains the sum of all elements of the given
array.

Program:
#include<stdio.h>

int sumofarray(int a[],int n) // formal arguments


{
int i,sum=0; // make sum to zero
for(i=0; i<n; i++)
{
sum+=a[i]; // add array elements to sum
}
return sum; // return the sum value to calling function
}
int main()
{
int a[100],i,n,sum; // Declaration of variables
// read the size of an array as input
printf("Enter size of the array : ");
scanf("%d", &n);
// Read array elements
printf("Enter elements in array : ");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
// call sumofarray function by passing array copy and size
sum=sumofarray(a,n);
// Print the sum of array elements
printf("Sum of array is :%d",sum);
return 0;
}

Output:
Case 1:
Enter size of the array: 5

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
41

Enter elements in array: 1


2
3
4
5
Sum of array is: 15
Case 2:
Enter size of the array: 5
Enter elements in array: -1
-2
-3
-4
-5
Sum of array is: -15

Result: The program to calculate sum of an array elements is executed successfully.

Viva Questions:
1) Can you pass array as argument? Explain.
2) What is the difference between actual arguments and formal arguments?
3) Is providing array size in formal arguments mandatory?
4) How to find the length of an integer array?
5) If array size is 10 and initialized with only 5 elements, then what about the remaining 5
values?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
42

20) Write a recursive function to find Factorial of a given number.


Aim: To find Factorial of a given number using recursion.
Description:
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and such
function calls are called recursive calls. However, it is important to impose a termination
condition of recursion. Recursion code is shorter than iterative code however it is difficult to
understand.
Recursion cannot be applied to all the problems, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting,
searching, and traversal problems.
The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4 *... * n
The factorial of a negative number doesn't exist. And the factorial of 0 is 1.
Suppose the user entered 6.
Initially, factorial() is called from main() with 6 passed as an argument.
Then, 5 is passed to factorial() from the same function (recursive call). In each recursive call, the
value of argument n is decreased by 1.
When the value of n is less than 1, there is no recursive call and the factorial is returned
ultimately to the main() function.

Program:
#include<stdio.h>
long int factorial(int n); // function prototype declaration

int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n); // read the input
printf("Factorial of %d = %ld", n, factorial(n)); // print the result
return 0;
}

long int factorial(int n) {


if (n>1)
return n*factorial(n-1); // recursive case
else
return 1; // base case
}

Output:
Case 1:
Enter a positive integer: 5
Factorial of 5 = 120
Case 2:

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
43

Enter a positive integer: 8


Factorial of 8 = 40320
Case 3:
Enter a positive integer: 0
Factorial of 0 = 1

Result: The program to find out factorial of a given non-negative number is executed
successfully.

Viva Questions:
1) What is recursion?
2) What are the types of recursion?
3) Differentiate between head and tail recursion.
4) What is tree recursion?
5) Differentiate between direct and indirect recursion.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
44

21) Write a C program to demonstrate storage classes.


Aim: To demonstrate different storage classes.
Description:
Storage Classes are used to describe the features of a variable/function. These features basically
include the scope, visibility and life-time which help us to trace the existence of a particular
variable during the runtime of a program.

C language uses 4 storage classes.


Auto Storage Class in C
The variables defined using auto storage class are called as local variables. Auto stands for
automatic storage class. A variable is in auto storage class by default if it is not explicitly
specified.
The scope of an auto variable is limited with the particular block only. Once the control goes out
of the block, the access is destroyed. This means only the block in which the auto variable is
declared can access it.
A keyword auto is used to define an auto storage class. By default, an auto variable contains a
garbage value.
Example: auto int age;
Extern Storage Class in C
Extern stands for external storage class. Extern storage class is used when we have global
functions or variables which are shared between two or more files.
Keyword extern is used to declaring a global variable or function in another file to provide the
reference of variable or function which have been already defined in the original file.
The variables defined using an extern keyword are called as global variables. These variables are
accessible throughout the program. Notice that the extern variable cannot be initialized it has
already been defined in the original file.
Example: extern void display();
Static Storage Class in C
The static variables are used within function/ file as local static variables. They can also be used
as a global variable
Static local variable is a local variable that retains and stores its value between function calls or
block and remains visible only to the function or block in which it is defined.
Static global variables are global variables visible only to the file in which it is declared.
Example: static int count = 10;
Register Storage Class in C
You can use the register storage class when you want to store local variables within functions or
blocks in CPU registers instead of RAM to have quick access to these variables. For example,
"counters" are a good candidate to be stored in the register.
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program.

Program:
#include <stdio.h>
// declaring the variable which is to be made extern an initial value can also be initialized to x

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
45

int x;
void autoStorageClass()
{
printf("\nDemonstrating auto class\n\n");
// declaring an auto variable (simply writing "int a=32;" works as well)
auto int a = 32;
// printing the auto variable 'a'
printf("Value of the variable 'a' declared as auto: %d\n", a);
printf("--------------------------------");
}
void registerStorageClass()
{
printf("\nDemonstrating register class\n\n");
// declaring a register variable
register char b = 'G';
// printing the register variable 'b'
printf("Value of the variable 'b' declared as register: %d\n", b);
printf("--------------------------------");
}
void externStorageClass()
{
printf("\nDemonstrating extern class\n\n");
// telling the compiler that the variable z is an extern variable and has been
// defined elsewhere (above the main function)
extern int x;
// printing the extern variables 'x'
printf("Value of the variable 'x' declared as extern: %d\n", x);
// value of extern variable x modified
x = 2;
// printing the modified values of extern variables 'x'
printf("Modified value of the variable 'x' declared as extern: %d\n", x);
printf("--------------------------------");
}
void staticStorageClass()
{
int i = 0;
printf("\nDemonstrating static class\n\n");
// using a static variable 'y'
printf("Declaring 'y' as static inside the loop.\n But this declaration will occur only");
printf(" once as 'y' is static.\nIf not, then every time the value of 'y' ");
printf("will be the declared value 5 as in the case of variable 'p'\n");
printf("\nLoop started:\n");
for (i = 1; i < 5; i++) {
// Declaring the static variable 'y'
static int y = 5;

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
46

// Declare a non-static variable 'p'


int p = 10;
// Incrementing the value of y and p by 1
y++;
p++;
// printing value of y at each iteration
printf("\nThe value of 'y', declared as static, in %d iteration is %d\n", i, y);
// printing value of p at each iteration
printf("The value of non-static variable 'p', in %d iteration is %d\n", i, p);
}
printf("\nLoop ended:\n");
printf("--------------------------------");
}
int main()
{
printf("\nA program to demonstrate Storage Classes in C");
autoStorageClass(); // To demonstrate auto Storage Class
registerStorageClass(); // To demonstrate register Storage Class
externStorageClass(); // To demonstrate extern Storage Class
staticStorageClass(); // To demonstrate static Storage Class
printf("\nStorage Classes demonstrated");
return 0;
}

Output:
A program to demonstrate Storage Classes in C
Demonstrating auto class

Value of the variable 'a' declared as auto: 32


--------------------------------
Demonstrating register class

Value of the variable 'b' declared as register: 71


--------------------------------
Demonstrating extern class

Value of the variable 'x' declared as extern: 0


Modified value of the variable 'x' declared as extern: 2
--------------------------------
Demonstrating static class

Declaring 'y' as static inside the loop.


But this declaration will occur only once as 'y' is static.
If not, then every time the value of 'y' will be the declared value 5 as in the case of variable 'p'

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
47

Loop started:

The value of 'y', declared as static, in 1 iteration is 6


The value of non-static variable 'p', in 1 iteration is 11

The value of 'y', declared as static, in 2 iteration is 7


The value of non-static variable 'p', in 2 iteration is 11

The value of 'y', declared as static, in 3 iteration is 8


The value of non-static variable 'p', in 3 iteration is 11

The value of 'y', declared as static, in 4 iteration is 9


The value of non-static variable 'p', in 4 iteration is 11

Loop ended:
--------------------------------
Storage Classes demonstrated

Result: The program to demonstrate different storage class is executed successfully.

Viva Questions:
1) What are the different storage classes available in C?
2) What is the scope, life-time, location where the variable will be stored, the initial value of
an auto variable.
3) What is the scope, life-time, location where the variable will be stored, the initial value of
an external variable.
4) What is the scope, life-time, location where the variable will be stored, the initial value of
an static variable.
5) What is the scope, life-time, location where the variable will be stored, the initial value of
an register variable.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
48

22) Write a C program to read n numbers and find out sum, average using command line
arguments.
Aim: To demonstrate command line arguments.
Description:
The arguments passed from command line are called command line arguments. These arguments
are handled by main() function.
To support command line argument, you need to change the structure of main() function as given
below.
int main(int argc, char *argv[] )
Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }

Program:
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])


{
int i, sum = 0;
float avg;
for(i=1;i<argc;i++)
{
sum += atoi(argv[i]);
}
avg = (float) sum / (argc - 1);
printf("The Sum is: %d The Average is: %f", sum, avg);
return 0;
}

Output:
Case 1:
C:\Users\bvina\Desktop\PVPSIT\PPS\PROGRAMS>LAB_22 2 3 4 5
The Sum is: 14 The Average is: 3.500000
Case 2:
C:\Users\bvina\Desktop\PVPSIT\PPS\PROGRAMS>LAB _22 1 2 3 4 5 6 7 8 9 10
The Sum is: 55 The Average is: 5.500000
Case 3:
C:\Users\bvina\Desktop\PVPSIT\PPS\PROGRAMS>LAB_22 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
The Sum is: -55 The Average is: -5.500000

Result: The program to read n numbers and find out sum, average using command line
arguments is executed successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
49

Viva Questions:
1) What is command line arguments?
2) How many number of arguments are allowed in main() function.
3) Explain argc.
4) Explain *argv[] or **argv.
5) Explain atoi() function.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
50

23) Write a C program to demonstrate Stringizing operator (#).


Aim: To demonstrate Stringizing operator.
Description:
The number-sign or "stringizing" operator (#) converts macro parameters to string literals
without expanding the parameter definition. It's used only with macros that take arguments.
The Stringize operator is a preprocessor operator. It sends commands to compiler to convert a
token into string. We use this operator at the macro definition.
Using stringize operator we can convert some text into string without using any quotes.
The operator # is known as Stringize Operator in C language, it is used in conjunction with
#define directive.
Stringize Operator (#) is used to turn the argument into quoted string.
Defining Macro with Stringize Operator
#define macro_function(argument) #argument

Program:
#include<stdio.h>
#define STR_PRINT(x) #x
#define STR_CNT(a, b) #a#b
int main()
{
printf(STR_PRINT(This is a string without double quotes));
printf("\n");
printf(STR_CNT(20, 30));
return 0;
}

Output:
This is a string without double quotes
2030

Result: The program to demonstrate Stringizing operator (#) is executed successfully.

Viva Questions:
1) What is #define?
2) What is the purpose of Stringizing operator (#).
3) Define macro.
4) What is the difference between macro and function?
5) What is parameterized macro?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
51

24) Write a C program on Conditional Compilation.


Aim: To demonstrate conditional compilation.
Description:
Conditional compilation is the process of selecting which code to compile and which code to not
compile. Six directives are available to control conditional compilation. They delimit blocks of
program text that are compiled only if a specified condition is true. These directives can be
nested. The program text within the blocks is arbitrary and may consist of preprocessor
directives, C statements, and so on. The beginning of the block of program text is marked by one
of these directives:
1) #if, 2) #ifdef, 3) #ifndef, 4) #else, 5) #elif, 6) #endif

Program:
#include<stdio.h>
#define X 10

int main()
{
#ifdef X
printf("\nHello.");
#else
printf("\n Hi..")
#endif // X
#ifndef Y
#define Y 20
printf("\n%d", Y);
#endif // Y
#define Z 10
#if X==Z
printf("\n%d", Z);
#elif X==Z
#define Z 20
printf("\n%d", Z);
#else
prinf("\n%d", X);
#endif // Z
return 0;
}

Output:
Hello.
20
10

Result: The program to apply conditional compilation is executed successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
52

Viva Questions:
1) What is conditional compilation.
2) What is #ifdef?
3) What is #ifndef?
4) What is #if?
5) What is #endif?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
53

25) Write a C program to demonstrate call-by-reference.


Aim: To demonstrate call-by-reference.
Description:
There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.
When we call a function by passing the addresses of actual parameters then this way of calling
the function is known as call by reference. In call by reference, the operation performed on
formal parameters, affects the value of actual parameters because all the operations performed on
the value stored in the address of actual parameters.
Call by reference in C
In call by reference, the address of the variable is passed into the function call as the actual
parameter.
The value of the actual parameters can be modified by changing the formal parameters since the
address of the actual parameters is passed.
In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the address of
the actual parameters, and the modified value gets stored at the same address.

Program:
#include <stdio.h>

void swap(int * , int *); //prototype of the function


int main()
{
int a, b;
printf("Enter a, b values: ");
scanf("%d%d", &a, &b);
printf("Before swapping the values are a = %d, b = %d\n",a,b); // printing the value of a and b
before swapping
swap(&a,&b);
printf("After swapping values are a = %d, b = %d\n",a,b); // The value of actual parameters
are changed by changing the formal parameters in call by reference, a = 20, b = 10
}
void swap (int *p, int *q)
{
int temp;
temp = *p;
*p = *q;
*q = temp;
}

Output:
Case 1:
Enter a, b values: 12 15
Before swapping the values are a = 12, b = 15

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
54

After swapping values are a = 15, b = 12


Case 2:
Enter a, b values: -12 -15
Before swapping the values are a = -12, b = -15
After swapping values are a = -15, b = -12
Case 3:
Enter a, b values: -12 15
Before swapping the values are a = -12, b = 15
After swapping values are a = 15, b = -12
Result: The program to swap the values of 2 variables using call-by-reference is executed
successfully.

Viva Questions:
1) What is a pointer?
2) Differentiate call-by-value and call-by-reference?
3) What are Actual parameters?
4) What are Formal parameters?
5) How to get the address of a variable?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
55

26) Write a C program on dynamic memory allocation.


Aim: To demonstrate Dynamic Memory Allocation in C.
Description:
Dynamic Memory Allocation is unique feature of C Programming Language.
In Dynamic Memory Allocation, memory will be allocated while executing programs that means
at run time. The Dynamic Memory Allocation allows us to modify memory size at run time.
The C programming language does not have dynamic array as a language feature.
The C programming language does have sufficient number of powerful features that a C
programmer can implement dynamic array (among other things) using these features !!!
There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate
dynamic memory allocation in C programming. They are:

1. malloc()
The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large
block of memory with the specified size.
Syntax:
ptr = (cast-type*) malloc(byte-size)
Example:
ptr = (int*) malloc(100 * sizeof(int));
2. calloc()
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified
number of blocks of memory of the specified type. it is very much similar to malloc() but has
two different points and these are:
It initializes each block with a default value ‘0’.
It has two parameters or arguments as compare to malloc()
Syntax:
ptr = (cast-type*)calloc(n, element-size);
Example:
ptr = (float*) calloc(25, sizeof(float));
3. realloc()
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of
a previously allocated memory.
re-allocation of memory maintains the already present value and new blocks will be initialized
with the default garbage value.

Syntax:
ptr = realloc(ptr, newSize);
Example:
ptr = realloc(ptr, n * sizeof(int));
4. free()
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used,
whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by
freeing it.
Syntax:

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
56

free(ptr);

Program:
#include<stdio.h>
#include<stdlib.h>

int main()
{
int n;
printf("Enter the size of array: ");
scanf("%d", &n);
int *myArray = (int*) malloc(n*sizeof(int));
for(int i=0; i<n; i++)
{
myArray[i] = i+1;
}
for(int i=0; i<n; i++)
{
printf("%d \t", *myArray+i);
}
printf("\n");
int *myArray1 = (int*) calloc(n, sizeof(n));
for(int i=0; i<n; i++)
{
printf("%d \t", myArray1[i]);
}
int *A = (int*) malloc(n*sizeof(int));
printf("\nPrev. block address= %d", A);
for(int i=0; i<n; i++)
{
A[i]=i+1;
}
A = (int*) realloc(A, 2*n*sizeof(int));
printf("\nNew address= %d \n", A);
for(int i=0; i<2*n; i++)
{
printf("%d \n", A[i]);
}
free(myArray);
free(myArray1);
free(A);
return 0;
}

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
57

Output:
Enter the size of array: 5
1 2 3 4 5
0 0 0 0 0
Prev. block address= 12285424
New address= 12285424
1
2
3
4
5
0
-1677721444
3638
12260384
0

Result: The program to demonstrate dynamic memory allocation in C is executed successfully.

Viva Questions:
1) What is Dynamic Memory Allocation?
2) Differentiate between Static Memory Allocation and Dynamic Memory Allocation?
3) Write the syntax of malloc().
4) Write the syntax of calloc().
5) Write the syntax of realloc().

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
58

27) Write a C program on pointer to an array.


Aim: To demonstrate pointer to an array.
Description:
A pointer that can point to whole array instead of only one element of the array. This pointer is
useful when talking about multidimensional arrays.

Syntax:
data_type (*var_name)[size_of_array];
int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer name
inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.

Program:
#include <stdio.h>

int main()
{
// Pointer to an array of five numbers
int(*a)[5];
int b[5] = { 1, 2, 3, 4, 5 };
int i;
// Points to the whole array b
a = &b;
for (i = 0; i < 5; i++)
printf("%p\n", a + i); // Display Address of 5 Elements
for (i = 0; i < 5; i++)
printf("%d\n", *(*a + i)); // Display 5 Elements
return 0;
}

Output:
000000000061FDF0
000000000061FE04
000000000061FE18
000000000061FE2C
000000000061FE40
1
2
3
4
5

Result: The program to demonstrate pointer to an array is executed successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
59

Viva Questions:
1) What is pointer to an array?
2) What is array of pointers?
3) What is null pointer?
4) What is generic pointer?
5) What is wild pointer?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
60

28) Write a C program on function pointers.


Aim: To demonstrate function pointers.
Description:
As we know that we can create a pointer of any data type such as int, char, float, we can also
create a pointer pointing to a function. The code of a function always resides in memory, which
means that the function has some address. We can get the address of memory by using the
function pointer.
Declaration of a function pointer
Till now, we have seen that the functions have addresses, so we can create pointers that can
contain these addresses, and hence can point them.
Syntax of function pointer
return type (*ptr_name)(type1, type2…);
For example:
int (*ip) (int);
In the above declaration, *ip is a pointer that points to a function which returns an int value and
accepts an integer value as an argument.

Program:
#include <stdio.h>

void Hi_function (int times); /* function prototype*/


int main()
{
void (*function_ptr)(int); /* function pointer Declaration */
function_ptr = Hi_function; /* pointer assignment */
function_ptr (3); /* function call */
return 0;
}
void Hi_function (int times)
{
int k;
for (k = 0; k < times; k++)
printf("Hi\n");
}

Output:
Hi
Hi
Hi

Result: The program to demonstrate function pointer is executed successfully.


Viva Questions:
1) Define function pointer.
2) What is the difference between pointer returns a function and function pointer?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
61

29) Create a student structure to demonstrate structures in C.


Aim: To demonstrate structure in C.
Description:
A structure is a user defined data type in C. A structure creates a data type that can be used to
group items of possibly different types into a single type.
Array allows to define type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows to combine data
items of different kinds.
Structures are used to represent a record.
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member.
struct [structure tag] {
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition.

Program:
#include <stdio.h>

float calculate_cgpa();
// Definition of a structure
struct Student
{// members of the structure
int rollno;
char name[30];
float cgpa;
};

struct Student Stu1; // Declaration of Structure Variables

int main() {
//Initialization
printf("Enter student details: ");
scanf("%d", &Stu1.rollno);
fflush(stdin);
scanf("%s", &Stu1.name);
Stu1.cgpa = calculate_cgpa();
//Accessing
printf("%d %s %.2f", Stu1.rollno, Stu1.name, Stu1.cgpa);
return 0;
}

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
62

float calculate_cgpa()
{
int s1, s2, s3;
printf("Enter marks: ");
scanf("%d%d%d", &s1, &s2, &s3);
int sum = s1+s2+s3;
float cgpa = (float)(sum/3)/10;
return cgpa;
}

Output:
Enter student details: 123
ABC
Enter marks: 89 87 85
123 ABC 8.70

Result: To demonstrate structure in C is executed successfully.

Viva Questions:
1) Define a structure in C?
2) What is the keyword used to define structure?
3) What is nested structure?
4) Can we declare function inside structure of C Programming?
5) Is it necessary that all elements of structure should be different in size?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
63

30) Write a C program to demonstrate bit-fields in structure.


Aim: To demonstrate bit-fields in structure.
Description:
A bit field is a data structure that allows the programmer to allocate memory to structures and
unions in bits in order to utilize computer memory in an efficient manner.
Variables that are defined using a predefined width or size are called bit fields. This bit field can
leave more than a single bit. The format and syntax of bit-field declaration inside a structure is
something like this:
struct {
data – type [nameofmember]: width_of_Bit - field;
};

Program:
#include <stdio.h>

typedef struct Add ADD;


struct Add
{
unsigned int num1:4;
unsigned int num2:4;
};
ADD c;
int main()
{
printf("Demo on Bit Fields of 2 Non-Negative Numbers (Below 10): ");
c.num1 = 9;
c.num2 = 8;
printf("\nThe Sum is: %d", c.num1+c.num2);
return 0;
}

Output:
The Sum is: 17

Result: The program to demonstrate bit fields in structures is executed successfully.

Viva Questions:
1) What is the correct syntax to initialize bit-fields in a structure?
2) Which of data types are accepted while declaring bit-fields?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
64

31) Write a program to demonstrate unions in C.


Aim: To demonstrate unions in C.
Description:
A union is a user-defined type similar to structs in C except for one key difference.
Structures allocate enough space to store all their members, whereas unions can only hold one
member value at a time.
You can define a union with many members, but only one member can contain a value at any
given time. Unions provide an efficient way of using the same memory location for multiple-
purpose.
Need for Union in C programming
C unions are used to save memory. To better understand an union, think of it as a chunk of
memory that is used to store variables of different types. When we want to assign a new value to
a field, then the existing data is replaced with new data.
C unions allow data members which are mutually exclusive to share the same memory. This is
quite important when memory is valuable, such as in embedded systems. Unions are mostly used
in embedded programming where direct access to the memory is needed.

Program:
#include <stdio.h>

typedef union Student Stu; // Aliasing of union


union Student // Definition of union
{
int rno;
char name[25];
float cgpa;
};

int main()
{
Stu s; // Declaration of union variable
printf("Enter student Roll No: ");
scanf("%d", &s.rno);
printf("\nThe Roll No of Student is: %d", s.rno);
printf("\nEnter Name: ");
scanf("%s", s.name);
printf("\nThe name is: %s", s.name);
printf("\nEnter CGPA: ");
scanf("%f", &s.cgpa);
printf("\nThe CGPA is: %.2f", s.cgpa);
return 0;
}

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
65

Output:
Enter student Roll No: 147
The Roll No of Student is: 147
Enter Name: ABC
The name is: ABC
Enter CGPA: 8.7
The CGPA is: 8.70

Result: The program to demonstrate unions is executed successfully.

Viva Questions:
1) What is union?
2) How much memory allocated for union variable?
3) What is the difference between structure and union?
4) What are the advantages of union?
5) What are the drawbacks with union?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
66

32) Write a C program to demonstrate enum.


Aim: To demonstrate enumerations in C.
Description:
Enumeration is a user defined data type in C language. It is used to assign names to the integral
constants which makes a program easy to read and maintain. The keyword “enum” is used to
declare an enumeration.
Here is the syntax of enum in C language,
enum enum_name{const1, const2, ....... };
In C programming, an enumeration type (also called enum) is a data type that consists of integral
constants. To define enums, the enum keyword is used.
The enum keyword is also used to define the variables of enum type. There are two ways to
define the variables of enum type as follows.
enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
enum week day;
enum flag {const1, const2, ..., constN};
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements
during declaration (if necessary).

Program:
#include <stdio.h>

// Definition of Enum
typedef enum month MONTH;
typedef enum week WEEK;
enum month{Jan, Feb, Mar, Apr, May, Jun, July, Aug, Sep, Oct, Nov, Dec};
enum week{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
WEEK w = Friday; // Declaration of enum variable
MONTH m = Mar;
if (m == 3 && w == 5)
printf("\nPay Income TAX.");
else
printf("\n Wait!");
return 0;
}

Output:
Case 1:
Pay Income TAX.
Case 2:
Wait!

Result: The program to demonstrate enumerator is executed successfully.

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
67

Viva Questions:
1) What is enum?
2) What is typedef?
3) What type of constants is permitted by enum?
4) What is the beginning value of enum constant?
5) Is enum allows user defined constants?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
68

33) Write a C program to access a file linearly.


Aim: To demonstrate sequential access to files.
Description:
It is necessary to keep data in the permanent storage because it is difficult to handle the large
volume of data by programs and after execution of program is over all the entered data will be
lost because, the data stored in the variables are temporary.
C supports the concept of file through which the data can be stored in the disk or secondary
storage device. So the data can be read when required. A file is a collection of data or text,
placed on the disk.
There are two types of files- sequential file and random access file. In sequential file, data are
kept sequential. As example if we want to access the forty fourth record, then first forty three
records should be read sequentially to reach the forty fourth record. In the record access file, the
data can be accessed and processed randomly i.e in this case the forty fourth record can be
accessed directly. It takes less time than the sequential file.
Hence depending up on the method of accessing the data stored, there are two types of files.
Sequential file
Random access file
1.Sequential File: In this type of files data is kept in sequential order if we want to read the last
record of the file, we need to read all records before that record so it takes more time.

Program:
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fp; // File pointer declaration
char ch;
fp = fopen("Program.txt", "w"); // Creation/Opening of file
if (fp == NULL) // Check for file opened or not
{
printf("** FILE IS NOT CREATED **");
exit(0);
}
printf("\nEnter some text: (Enter '$' to Terminate) ");
while((ch = getchar())!= '$')
{
fputc(ch, fp);
}
fclose(fp);
fp = fopen("Program.txt","r");
if (fp == NULL)
{
printf("** FILE IS NOT CREATED **");
exit(0);

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
69

}
printf("\nThe File Contents are: ");
while((ch = fgetc(fp))!= EOF)
{
putchar(ch);
}
fclose(fp);
return 0;
}

Output:
Enter some text: (Enter '$' to Terminate) Prasad V. Potluri SIT$
The File Contents are:
Prasad V. Potluri SIT

Result: The program to demonstrate sequential access to files is executed successfully.

Viva Questions:
1) What is a FILE?
2) What are the types of files?
3) What are file modes?
4) What are the different functions used to write to the file?
5) What are the different functions used to read from the file?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
70

34) Write a C program to access a file randomly.


Aim: To demonstrate random access to files in C.
Description:
Random file access means that you can take the file pointer to any part of the file for reading or
writing. In general, with small files, we access the files sequentially. In sequential access, we
access the file record by record or character by character. This approach is appropriate if the file
size is small, but what if the file has tens of thousands of records? In random file access, if a file
has 10,000 records and if you want to go to the 9,999th record, you can directly point the file
pointer to this record using the random file access technique. This can be done using the
functions we are about to mention.
There is no need to read each record sequentially, if we want to access a particular record. C
supports these functions for random access file processing.
fseek()
ftell()
rewind()

fseek():
This function is used for seeking the pointer position in the file at the specified byte.
Syntax: fseek (file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative. This is the number of bytes which are skipped
backward (if negative) or forward (if positive) from the current position. This is attached with L
because this is a long integer.

Pointer position:
This sets the pointer position in the file.

Value Pointer position


0 Beginning of file.
1 Current position
2 End of file

Program:
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *ptr;
char c;
ptr = fopen("Input.txt", "w+");
if(ptr != NULL)
{
printf("\nBefore Writing The Location of Pointer is: %ld", ftell(ptr));

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY


PROGRAMMING FOR PROBLEM SOLVING LAB (20ES1253)
71

fputs("PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY", ptr);


printf("\nAfter Writing The Location of Pointer is: %ld", ftell(ptr));
fseek(ptr, 18, SEEK_SET);
printf("\nAfter seek The Location of Pointer is: %ld\n", ftell(ptr));
while((c = fgetc(ptr))!=EOF)
{
putchar(c);
}
printf("\nThe Location of Pointer is: %ld", ftell(ptr));
rewind(ptr);
printf("\nAfter Rewind() The Location of Pointer is: %ld", ftell(ptr));
}
else
{
printf("Error!");
exit(0);
}
return 0;
}

Output:
Before Writing The Location of Pointer is: 0
After Writing The Location of Pointer is: 52
After seek The Location of Pointer is: 18
SIDDHARTHA INSTITUTE OF TECHNOLOGY
The Location of Pointer is: 52
After Rewind() The Location of Pointer is: 0

Result: The C program to access a file randomly is executed successfully.

Viva Questions:
1) Define Random Access to Files.
2) Explain is fseek() function parameters?
3) Explain ftell() function?
4) What is rewind()?
5) What is an exit(0)?

PRASAD V. POTLURI SIDDHARTHA INSTITUTE OF TECHNOLOGY

You might also like