PPS Lab Record
PPS Lab Record
The Data type is a set of value with predefined characteristics. Data types are used to declare
variable, constants, arrays, pointers, and functions.
Program:
#include<stdio.h>
int main()
{
char a='A';
signed char b ='z';
unsigned char c ='!';
int g=-120;
signed int h= -6778382;
unsigned int i=689;
float p=3.456789;
double q = 2.333484873738;
long double r =6727272789.123456789;
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.
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?
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
float 4bytes
double 8bytes
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);
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?
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 long long integer is: %ld", sizeof (long long int));
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));
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?
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);
Output:
Case 1
Enter a year: 1900
1900 is not a leap year.
Case 2
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.
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);
}
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?
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
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(+, -, *, /, ): *
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?
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:
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?
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:
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?
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
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?
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
Case 2:
Enter number of Elements: 8
91357486
Enter an Element to be Search: 2
Element is not Available.
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?
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.
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;
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?
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.
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.
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++)
{
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
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++)
{
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
Viva Questions:
1) What is 2 Dimensional array?
2) Can we have 2D character arrays?
3) Can we have 2D floating point 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)
{
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
Viva Questions:
1) What is multi-dimensional array?
2) How many elements are there in A[2][3][4][5]?
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
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().
>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");
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().
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
}
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?
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>
Output:
Case 1:
Enter size of the array: 5
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?
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;
}
Output:
Case 1:
Enter a positive integer: 5
Factorial of 5 = 120
Case 2:
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.
Program:
#include <stdio.h>
// declaring the variable which is to be made extern an initial value can also be initialized to x
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;
Output:
A program to demonstrate Storage Classes in C
Demonstrating auto class
Loop started:
Loop ended:
--------------------------------
Storage Classes demonstrated
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.
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>
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.
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.
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
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?
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
Viva Questions:
1) What is conditional compilation.
2) What is #ifdef?
3) What is #ifndef?
4) What is #if?
5) What is #endif?
Program:
#include <stdio.h>
Output:
Case 1:
Enter a, b values: 12 15
Before swapping the values are a = 12, b = 15
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?
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:
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;
}
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
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().
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
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?
Program:
#include <stdio.h>
Output:
Hi
Hi
Hi
Program:
#include <stdio.h>
float calculate_cgpa();
// Definition of a structure
struct Student
{// members of the structure
int rollno;
char name[30];
float cgpa;
};
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;
}
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
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?
Program:
#include <stdio.h>
Output:
The Sum is: 17
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?
Program:
#include <stdio.h>
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;
}
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
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?
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!
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?
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);
}
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
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?
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.
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));
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
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)?