Pps Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

IPS ACADEMY INDORE

INSTITUTE OF ENGINEERING & SCIENCE


COMPUTER SCIENCE & ENGINEERING
DEPARTMENT

LAB MANUAL
(ESC-CS01)
Programming for Problem
Solving
Name …………………………………………………..

Branch……….Year…………..Semester……………

EnrollmentNo.…………………………………………..
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Contents

1. Vision Mission of the Institute


2. Vision Mission of the Department
3. PEOs
4. POs
5. Laboratory Regulations and Safety Rules
6. Index
7. Experiments

2|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Vision of the Institute

To be the fountainhead of novel ideas & innovations in science & technology & persist to be
a foundation of pride for all Indians.

Mission of the Institute

 To provide value based broad Engineering, Technology and Science where education in
students are urged to develop their professional skills.

 To inculcate dedication, hard work, sincerity, integrity, and ethics in building up overall
professional personality of our student and faculty.

 To inculcate a spirit of entrepreneurship and innovation in passing out students.

 To instigate sponsored research and provide consultancy services in technical, educational,


and industrial areas.

3|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Vision of the Department

Attaining global recognition in computer science and engineering education, research and
training to meet the growing needs of the industry and society.

Mission of the Department

M1: Provide quality education, in both the theoretical and applied foundations of computer science and
train students to effectively apply this education to solve real-world problems.

M2: Amplifying their potential for lifelong high-quality careers.

4|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Program Education Objectives (PEOs)


PEO 1:

To prepare students for successful careers in software industry that meet the needs of Indian and multinational
companies.

PEO 2:

To provide students with solid foundation in mathematical, scientific and engineering fundamentals to solve
engineering problems and required also to pursue higher studies.

PEO 3:

To develop the ability to work with the core competence of computer science & engineering i.e. software
engineering, hardware structure & networking concepts so that one can find feasible solution to real world
problems.

PEO 4:

To inseminate in students effective communication skills, team work, multidisciplinary approach, and an ability to
relate engineering issues to broader social context.

PEO 5:

To motivate students perseverance for lifelong learning and to introduce them to professional ethics and codes of
professional practice.

5|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Program Outcomes (POs)

PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2. Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

PO3.Design/development of solutions: Design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

PO7. Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.

PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

PO10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive

6|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

clear instructions.

PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one‟s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change

7|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Program Specific Outcomes (PSOs)


1. Apply Concepts in core areas of computer science -Data Structures, Database Management
System, Operating System, Computer Networks and Software Engineering to solve technical
issues.

2. Apply Software Engineering principal and practices to provide software solutions.

3. Ability to work in team and apply the knowledge acquired to develop new real-life system
and able to adapt societal need of future.

Course Outcomes (COs)


CO 1: Implement the fundamental programming concepts of C language.

CO 2: Implement C programs using functions and arrays.

CO 3: Implement C programs using Pointer and Strings

CO 4: Demonstrate the ability to write C programs using structures, unions and Enum.

CO 5: Implement the basics of file handling mechanism.

Content beyond Syllabus


1. Write a program to create two structure variables of a structure.

2. Write a program to create two objects of a single class and access their variables

8|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Laboratory Regulations and Safety Rules

1. Without Prior permission do not enter the Laboratory.


2. While entering the LAB students should wear their ID cards.
3. The Students should come with proper uniform.
4. Student should not use mobile phone inside the laboratory.
5. Students should sign in the LOGIN REGISTER before enteringthe laboratory.
6. Students should come with observation and record notebook to the laboratory.
7. Do not change any computer setting.
8. Students should maintain silence inside the laboratory.
9. After completing the laboratory exercise, make sure to SHUTDOWN the system properly.

9|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Index

S.
ExperimentName Date Grade Signature
No.
Write a C program to calculate the grade of the student
1.
according to the specified marks using if-else
statement. (CO1)
Write a C program to print table for the given number
2.
using while, do while and for loop (CO1)
Write a C program to implement break, goto and
3. continue. (CO1)
Write a C program to perform basic athematic
4.
operation (addition, subtraction, multiplication, division
and average). (CO2)
Write a C program to swap the values of the two
5.
variables by using Call by value and Call by reference.
(CO2)

Write a C program to print Fibonacci Series up to n


6. terms. (CO2)
Write a C program to find the average of n numbers
7. using arrays. (CO2)
Write a C program to find the sum of two matrices of
8.
order 2*2. (CO2)
Write a C program to implement Array of pointers.
9.
(CO3)
Write a C program to implement Pointer to an array.
10.
(CO3)

11. Write a C program to implement Pointers to Functions.


(CO3)
12. Write a C program to implement any 5 string functions.
(CO3)

10|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

13. Write a C program to implement dynamic memory


allocation functions (malloc(), calloc(), realloc(),
free()). (CO3)
14. Write a C program to stores information of 5 employees and
prints it using 'array of structures'. (CO4)

15. Write a C program to demonstrate the use of Enum. (CO4)

16. Write a C program to create a file and write contents, save


and close the file. (CO5)

17. Write a C program to read file contents and display on


console. (CO5)

18. Write a C program to use command line arguments. (CO5)

19.
Write a program to create two structure variables of a
structure.(CBS)
20. Write a program to create two objects of a single class and
access their variables. (CBS)

11|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 1
Aim: Write a C program to calculate the grade of the student according to the specified marks
using if-else statement.
#include <stdio.h>
#include <conio.h>
int main()
{
int marks;
printf("Enter the marks: ");
scanf("%d", &marks);
if (marks >= 90 && marks <= 100)
{
printf("Grade: A\n");
}
else if (marks >= 80 && marks < 90)
{
printf("Grade: B\n");
}
else if (marks >= 70 && marks < 80)
{
printf("Grade: C\n");
}
else if (marks >= 60 && marks < 70)
{
printf("Grade: D\n");
}
else if (marks >= 0 && marks < 60)
{
printf("Grade: F\n");
}
else {
printf("Invalid marks entered. Marks should be between 0 and 100.\n");
}
12|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

getch();
return 0;
}

Output:-

Enter the marks: 99


Grade: A

13|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is syntax error?

Ans.) Syntax errors are associated with mistakes in the use of a programming language. It maybe a
command that was misspelled or a command that must was entered in lowercase mode but was
instead entered with an upper case character. A misplaced symbol, or lack of symbol, somewhere
within a line of code can also lead to syntax error.

Q.2) What is the output of printf("%d")?

Ans.) When we write printf("%d",x); this means compiler will print the value of x. But as here, there
is nothing after %d so compiler will show in output window garbage value.

14|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 2
Aim: Write a C program to print table for the given number using while, do while and for loop

Using While loop-

#include <stdio.h>
#include <conio.h>

void main()
{
int number, i;
printf("Enter the number: ");
scanf("%d", &number);
printf("\nUsing while loop:\n");
i = 1;
while (i <= 10)
{
printf("%d x %d = %d\n", number, i, number * i);
i++;
}
getch();
}

Output:-

Enter the number: 2


Using while loop:
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2x10 = 20

15|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Using do-while loop

#include <stdio.h>
#include<conio.h>
int main() {
int number, i = 1;
printf("Enter a number: ");
scanf("%d", &number);
printf("Table of %d using do-while loop:\n", number);
do {
printf("%d x %d = %d\n", number, i, number * i);
i++;
} while (i <= 10);
getch();
return 0;
}

Output:-

Enter the number: 2


Using do-while loop:
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2x10 = 20

16|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Using for loop-

#include <stdio.h>
#include<conio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Table of %d using for loop:\n", number);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", number, i, number * i);
}
getch();
return 0;
}

Output:-

Enter the number: 2


Using for loop:
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2x10 = 20

17|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) Difference between const char* p and char const* p.

Ans.) In const char* p, the character pointed by ‘p’ is constant, so u cant change the value of character
pointed by p but u can make ‘p’ refer to some other location.
in char const* p, the ptr ‘p’ is constant not the character referenced by it, so u cant make ‘p’ to reference
to any other location but u can change the value of the char pointed by ‘p’.

Q.2) What are header files?

Ans.) Header files are file with extension h.


These files contain declarations of library functions and predefined constants and macros.

18|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 3

Aim: Write a C program to implement break, goto and continue.


#include <stdio.h>
#include <conio.h>
int main() {
int i;
printf("Using break statement:\n");
for (i = 1; i <= 10; i++)
{
if (i == 6) {
break;
}
printf("%d ", i);
}
printf("\n\n");
printf("Using goto statement:\n");
i = 1;
loop_with_goto:
if (i <= 10)
{
printf("%d ", i);
i++;
goto loop_with_goto;
}
printf("\n\n");
printf("Using continue statement:\n");
for (i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue;
}
19|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

printf("%d ", i);


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

Output:-

Using break statement:


12345

Using goto statement:


1 2 3 4 5 6 7 8 9 10

Using continue statement:


1 3579

20|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What are the different data types available in C?

Ans.) There are four basic data types available in C,


int,
float,
char and
double

Q.2) what do you mean by variables?

Ans.) A variable is a name given to a memory location. It is the basic unit of storage in a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the variable effects that
memory location.

21|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 4

Aim: Write a C program to perform basic arithmetic operation (addition, subtraction,


multiplication, division and average).

#include <stdio.h>
#include <conio.h>
int main()
{
float num1, num2, result;
char operator;

printf("Enter first number: ");


scanf("%f", &num1);

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


scanf(" %c", &operator);

printf("Enter second number: ");


scanf("%f", &num2);

switch (operator)
{
case '+':

result = num1 + num2;


printf("%.2f + %.2f = %.2f\n", num1, num2, result);
break;

case '-':

result = num1 - num2;


printf("%.2f - %.2f = %.2f\n", num1, num2, result);
break;
case '*':

result = num1 * num2;


printf("%.2f * %.2f = %.2f\n", num1, num2, result);
break;
case '/':

if (num2 != 0)
{
result = num1 / num2;
printf("%.2f / %.2f = %.2f\n", num1, num2, result);
}
else
22|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

{
printf("Error: Division by zero is not allowed.\n");
}
break;

default:
printf("Error: Invalid operator entered.\n");
break;
}
getch();
return 0;
}

Output:-

Enter first number: 11


Enter operator (+, -, *, /): +
Enter second number: 11
11.00 + 11.00 = 22.00

23|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is the difference between "printf(...)" and "sprintf(...)"?

Ans.) sprintf(...) writes data to the character array whereas printf(...) writes data to the
Standard output device.

Q.2) Compilation How to reduce a final size of executable?

Ans.) Size of the final executable can be reduced using dynamic linking for libraries.

24|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 5

Aim: Write a C program to swap the values of the two variables by using Call by value and Call
by reference.

Using Call by Value-

#include <stdio.h>
#include<conio.h>
void swap(int , int);
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
getch();
}

Output:-

Before swapping the values in main a = 10, b = 20


After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

25|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Using Call by Reference-

#include <stdio.h>
#include<conio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1, num2;
printf("Enter value for variable 1: ");
scanf("%d", &num1);
printf("Enter value for variable 2: ");
scanf("%d", &num2);
printf("\nBefore swapping:\n");
printf("Variable 1: %d\n", num1);
printf("Variable 2: %d\n", num2);
swap(&num1, &num2);
printf("\nAfter swapping:\n");
printf("Variable 1: %d\n", num1);
printf("Variable 2: %d\n", num2);
getch();
return 0;
}

Output:-

Enter value for variable 1: 10


Enter value for variable 2: 20

Before swapping:
Variable 1: 10
Variable 2: 20

After swapping:
Variable 1: 20
Variable 2: 10

26|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What are reserved words with a programming language?

Ans.) The words that are a part of the standard C language library are called reserved words. Those
reserved words have special meaning and it is not possible to use them for any activity other than its
intended functionality.

Q.2) What is the difference between abs() and fabs() functions?

Ans.) Both functions are to retrieve absolute value. abs() is for integer values and fabs() is for floating type
numbers. Prototype for abs() is under the library file < stdlib.h > and fabs() is under < math.h >.

27|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 6
Aim: Write a C program to print Fibonacci Series up to n terms.
#include <stdio.h>
#include <conio.h>

void printFibonacci(int n);


int main() {
int n;
printf("Enter the number of terms in the Fibonacci series: ");
scanf("%d", &n);
if (n < 0) {
printf("Please enter a non-negative number.\n");
return 1;
}
printf("Fibonacci series up to %d terms:\n", n);
printFibonacci(n);
getch();
return 0;
}
void printFibonacci(int n) {
int first = 0, second = 1, next;
for (int i = 0; i < n; ++i) {
printf("%d, ", first);
next = first + second;
first = second;
second = next;
}
printf("\n");
}

28|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Output:-

Enter the number of terms in the Fibonacci series: 10


Fibonacci series up to 10 terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

29|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) what is the use of clrscr() ?

Ans.) This is used for clearing the output screen i.e console ,suppose you run a program, alter it and run it
again you may find that the previous output is still stuck there itself, at this time clrscr(); would clean the
previous screen.

Q.2) what is the use of getch() ?

Ans.) getch is used to hold the screen in simple language, if u don't write this the screen will just flash and
go away

30|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 7
Aim: Write a C program to find the average of n numbers using arrays.
#include <stdio.h>
#include <conio.h>
float calculateAverage(int arr[], int n);
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
if (n <= 0) {
printf("Please enter a positive number.\n");
return 1;
}
int numbers[n];
printf("Enter %d numbers:\n", n);
for (int i = 0; i < n; ++i) {
scanf("%d", &numbers[i]);
}
float average = calculateAverage(numbers, n);
printf("Average of the numbers: %.2f\n", average);
getch();
return 0;
}
float calculateAverage(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; ++i) {
sum += arr[i];
}
return (float)sum / n;
}

31|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Output:-

Enter the number of elements: 5


Enter 5 numbers:
30
20
70
80
10
Average of the numbers: 42.00

32|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What are control statements?

Ans.) Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform tasks
repeatedly or to jump from one section of code to another.

Q.2) What are the types of control statements?

Ans.) There are four types of control statements in C:

1. Decision making statements (if else statements)


2. Selection statements (switch case statements)
3. Iteration statements (loops)
4. Jump statements

33|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 8
Aim: Write a C program to find the sum of two matrices of order 2*2.

#include <stdio.h>
#include <conio.h>
void addMatrices(int mat1[][2], int mat2[][2], int result[][2]);
int main()
{
int mat1[2][2], mat2[2][2], result[2][2];
printf("Enter elements of the first matrix (2x2):\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
scanf("%d", &mat1[i][j]);
}
}
printf("Enter elements of the second matrix (2x2):\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
scanf("%d", &mat2[i][j]);
}
}

addMatrices(mat1, mat2, result);


printf("Sum of the two matrices:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
printf("%d ", result[i][j]);
}
printf("\n");
}
getch();
return 0;
}
void addMatrices(int mat1[][2], int mat2[][2], int result[][2]) {
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
result[i][j] = mat1[i][j] + mat2[i][j];
}
34|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

}
}

Output:-
Enter elements of the first matrix (2x2):
25
43
Enter elements of the second matrix (2x2):
35
41
Sum of the two matrices:
5 10
84

35|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is recursion in C?

Ans.) When a function calls itself, and this process is known as recursion. The function that calls itself is
known as a recursive function. recursive function comes in two phases:
Winding phase
Unwinding phase
Winding phase: When the recursive function calls itself, and this phase ends when the condition is
reached.
Unwinding phase: Unwinding phase starts when the condition is reached, and the control returns to the
original call.

Q.2) What are the general description for loop statements and available loop types in C?

Ans.) A statement that allows the execution of statements or groups of statements in a repeated way is
defined as a loop. The following diagram explains a general form of a loop.

There are 4 types of loop statements in C.


While loop
For Loop
Do…While Loop
Nested Loop

36|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 9
Aim:Write a C program to implement Array of pointers.

#include <stdio.h>
#include <conio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *ptrArray[5];
for (int i = 0; i < 5; ++i)
{
ptrArray[i] = &arr[i];
}
printf("Values using the array of pointers:\n");
for (int i = 0; i < 5; ++i) {
printf("Value at index %d: %d\n", i, *ptrArray[i]);
}
getch();
return 0;
}

Output:-
Values using the array of pointers:
Value at index 0: 10
Value at index 1: 20
Value at index 2: 30
Value at index 3: 40
Value at index 4: 50

37|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is the general form of function in C?

Ans.) return_type function_name( parameter list )

body of the function

Return Type: Data type of the return value of the function.

Function Name: The name of the function and it is important to have a meaningful name that describes the
activity of the function.

Parameters: The input values for the function that are used to perform the required action.

Function Body: Collection of statements that performs the required action.

Q.2) What are the valid places to have keyword “Break”?

Ans.) The purpose of the Break keyword is to bring the control out of the code block which is executing. It
can appear only in looping or switch statements.

38|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 10
Aim:Write a C program to implement Pointer to an array.
#include <stdio.h>
#include <conio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int *ptrToArray;
ptrToArray = numbers;
printf("Elements of the array using pointer:\n");
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i + 1, *(ptrToArray + i));
}
getch();
return 0;
}

Output:

Elements of the array using pointer:


Element 1: 1
Element 2: 2
Element 3: 3
Element 4: 4
Element 5: 5

39|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is the behavioral difference when the header file is included in double-quotes (“”) and
angular braces (<>)?

Ans.) When the Header file is included within double quotes (“ ”), compiler search first in the working
directory for the particular header file. If not found, then it searches the file in the include path. But when
the Header file is included within angular braces (<>), the compiler only searches in the working directory
for the particular header file.

Q.2) Is that possible to store 32768 in an int data type variable?

Ans.) Int data type is only capable of storing values between – 32768 to 32767. To store 32768 a modifier
needs to used with the int data type. Long Int can use and also if there are no negative values, unsigned int
is also possible to use.

40|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 11

Aim: Write a C program to implement Pointers to Functions.

#include <stdio.h>
#include <conio.h>
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int main() {
int (*ptrAdd)(int, int);
int (*ptrSubtract)(int, int);
int (*ptrMultiply)(int, int);
ptrAdd = add;
ptrSubtract = subtract;
ptrMultiply = multiply;

int resultAdd = ptrAdd(5, 3);


int resultSubtract = ptrSubtract(5, 3);
int resultMultiply = ptrMultiply(5, 3);

printf("Result of addition: %d\n", resultAdd);


printf("Result of subtraction: %d\n", resultSubtract);
printf("Result of multiplication: %d\n", resultMultiply);
getch();
return 0;
}
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}

41|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

int multiply(int a, int b) {


return a * b;
}

Output:

Result of addition: 8
Result of subtraction: 2
Result of multiplication: 15

42|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1)Explain the difference between gets and fgets.

Ans.) gets reads a string from the standard input, while fgets reads a string from a specified file stream
and allows you to specify the maximum number of characters to read

Q.2)Differentiate between calloc and realloc.

Ans.)calloc allocates memory and initializes it to zero, while realloc changes the size of a previously allo-
cated block of memory.

43|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 12
Aim: Write a C program to implement any 5 string functions.

#include <stdio.h>
#include <conio.h>
#include <string.h>
int custom_strlen(const char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
void custom_strcpy(char *dest, const char *src) {
while ((*dest++ = *src++) != '\0');
}
void custom_strcat(char *dest, const char *src) {
while (*dest != '\0') {
dest++;
}
while ((*dest++ = *src++) != '\0');
}
int custom_strcmp(const char *str1, const char *str2) {
while (*str1 != '\0'&& *str2 != '\0'&& *str1 == *str2) {
str1++;
str2++;
}
return (*str1 - *str2);
}
void custom_strrev(char *str) {
char temp;
int length = strlen(str);
int i, j;
for (i = 0, j = length - 1; i < j; i++, j--) {
temp = str[i];
44|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

str[i] = str[j];
str[j] = temp;
}
}

int main() {
char str1[50] = "Hello";
char str2[50] = " World!";

printf("Length of str1: %d\n", custom_strlen(str1));

char copy_str[50];
custom_strcpy(copy_str, str1);
printf("Copy of str1: %s\n", copy_str);

custom_strcat(str1, str2);
printf("Concatenated string: %s\n", str1);

printf("Comparison result: %d\n", custom_strcmp(str1, copy_str));

custom_strrev(str1);
printf("Reversed string: %s\n", str1);
getch();
return 0;
}

Output:

Length of str1: 5
Copy of str1: Hello
Concatenated string: Hello World!
Comparison result: 32
Reversed string: !dlroW olleH

45|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is the purpose of the exit function in C?

Ans.) The exit function is used to terminate the program and return a status code to the operating system.

Q.2) How is the sizeof operator used with structures?

Ans.) The sizeof operator returns the size, in bytes, of a structure.

46|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 13
Aim: Write a C program to implement dynamic memory allocation functions (malloc(), calloc(),
realloc(), free()).

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void* my_malloc(size_t size) {


void* ptr = malloc(size);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return ptr;
}

void* my_calloc(size_t num_elements, size_t element_size) {


void* ptr = calloc(num_elements, element_size);
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return ptr;
}

void* my_realloc(void* ptr, size_t size) {


void* new_ptr = realloc(ptr, size);
if (new_ptr == NULL) {
fprintf(stderr, "Memory reallocation failed\n");
exit(EXIT_FAILURE);
}
return new_ptr;
}

void my_free(void* ptr) {


free(ptr);
}

int main() {
int* arr = (int*)my_malloc(5 * sizeof(int));

for (int i = 0; i < 5; i++) {


arr[i] = i + 1;
}

47|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

printf("Initial array elements: ");


for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");

arr = (int*)my_realloc(arr, 10 * sizeof(int));

printf("Array elements after realloc: ");


for (int i = 5; i < 10; i++) {
arr[i] = i + 1;
printf("%d ", arr[i]);
}
printf("\n");

my_free(arr);
getch();
return 0;
}

Output:

Initial array elements: 1 2 3 4 5


Array elements after realloc: 6 7 8 9 10

48|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is variable initialization and why is it important?

Ans.) This refers to the process wherein a variable is assigned an initial value before it is used in the
program. Without initialization, a variable would have an unknown value, which can lead to unpredictable
outputs when used in computations or other operations.

49|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 14
Aim: Write a C program to stores information of 5 employees and prints it using 'array of
structures'.

#include <stdio.h>
#include <conio.h>
struct Employee {
char name[50];
int employeeId;
float salary;
};

int main() {
struct Employee employees[5];

for (int i = 0; i < 5; i++) {


printf("Enter details for Employee %d:\n", i + 1);
printf("Name: ");
scanf("%s", employees[i].name);

printf("Employee ID: ");


scanf("%d", &employees[i].employeeId);
printf("Salary: ");
scanf("%f", &employees[i].salary);
printf("\n");
}
printf("Employee Information:\n");
for (int i = 0; i < 5; i++) {
printf("Employee %d:\n", i + 1);
printf("Name: %s\n", employees[i].name);
printf("Employee ID: %d\n", employees[i].employeeId);
printf("Salary: $%.2f\n", employees[i].salary);
printf("\n");
}
getch();
return 0;
50|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Output:

Enter details for Employee 1:


Name: Abhi
Employee ID: 101
Salary: 100000
Enter details for Employee 2:
Name: Gagan
Employee ID: 102
Salary: 100000
Enter details for Employee 3:
Name: Harsh
Employee ID: 103
Salary: 100000
Enter details for Employee 4:
Name: Anushika
Employee ID: 104
Salary: 100000
Enter details for Employee 5:
Name: Anshika
Employee ID: 105
Salary: 200000
Employee Information:
Employee 1:
Name: Abhi
Employee ID: 101
Salary: $100000.00

Employee 2:
Name: Gagan
Employee ID: 102
Salary: $100000.00

Employee 3:
Name: Harsh
Employee ID: 103
Salary: $100000.00

Employee 4:
Name: Anushika
Employee ID: 104
Salary: $100000.00

Employee 5:
Name: Anshika
Employee ID: 105
Salary: $200000.00

51|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) Explain the purpose of the #include directive in C.

Ans.) The #include directive is used to include external files or libraries in a C program. It facilitates code
reuse and modularity.

Q.2) What is the difference between ++i and i++?

Ans.) Both ++i and i++ increment the value of i by 1, but ++i increments the value before the current val-
ue is used, while i++ increments the value after the current value is used.

52|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 15
Aim: Write a C program to demonstrate the use of Enum.

#include <stdio.h>
#include <conio.h>
enum Days {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
};

int main() {
enum Days today;

today = WEDNESDAY;

switch (today) {
case SUNDAY:
printf("It's a relaxing day!\n");
break;
case MONDAY:
printf("The start of the workweek.\n");
break;
case WEDNESDAY:
printf("Halfway through the week!\n");
break;
case FRIDAY:
printf("TGIF - Thank God It's Friday!\n");
break;
default:
printf("It's a regular day.\n");
}
53|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

getch();
return 0;
}

Output:

Halfway through the week!

54|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is the significance of C program algorithms?

Ans.) The algorithm is created first and it contains step by step guidelines on how the solution should be.
Also, it contains the steps to consider and the required calculations/operations within the program.

Q.2) Is it possible to use curly brackets ({}) to enclose a single line code in C program?

Ans.) Yes, it works without any error. Some programmers like to use this to organize the code. But the
main purpose of curly brackets is to group several lines of codes.

55|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo.16

Aim: Write a C program to create a file and write contents, save and close the file.

#include<stdio.h>
#include<conio.h>
void main()
{
FILE *f;
f=fopen("a.txt","w");
printf("File created\n");
fprintf(f,"ips academy");
printf("Content writen=ips academy\n");
fclose(f);
printf("File saved and closed\n");
getch();
}

Output:-

56|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) Describe the modifier in C?

Ans.) Modifier is a prefix to the basic data type which is used to indicate the modification for storage
space allocation to a variable.
Example– In a 32-bit processor, storage space for the int data type is 4.When we use it with modifier the
storage space change as follows:
Long int: Storage space is 8 bit
Short int: Storage space is 2 bit

Q.2) Describe dynamic data structure in C programming language?

Ans.) Dynamic data structure is more efficient to memory. The memory access occurs as needed by the
program.

57|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 17

Aim: Write a C program to read file contents and display on console.

#include<stdio.h>
#include<conio.h>
void main()
{
char a[50],b[50];
clrscr();
FILE *f;
f=fopen("a.txt","r");
printf("File opened\n");
fscanf(f,"%s",a);
fscanf(f,"%s",b);
printf("Content readed=%s %s\n",a,b);
fclose(f);
printf("File closed\n");
getch();
}

Output:-

58|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is a NULL pointer in C?

Ans.) A pointer that doesn't refer to any address of value but NULL is known as a NULL pointer. When
we assign a '0' value to a pointer of any type, then it becomes a Null pointer.

59|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 18
Aim: Write a C program to use command line arguments.

#include <stdio.h>
#include<conio.h>
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("Usage: %s <arg1> <arg2> ... <argN>\n", argv[0]);
return 1;
}
printf("Program Name: %s\n", argv[0]);
printf("Arguments:\n");
for (int i = 1; i < argc; ++i) {
printf("%d: %s\n", i, argv[i]);
}
getch();
return 0;
}

Output:

Program Name: ./command_line_arguments


Arguments:
1: arg1
2: arg2
3: arg3

60|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is dangling pointer in C?

Ans.) If a pointer is pointing any memory location, but meanwhile another pointer deletes the memory
occupied by the first pointer while the first pointer still points to that memory location, the first pointer
will be known as a dangling pointer. This problem is known as a dangling pointer problem.
Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer
points to the de allocated memory.

Q.2) What is pointer to pointer in C?

Ans.) In case of a pointer to pointer concept, one pointer refers to the address of another pointer. The
pointer to pointer is a chain of pointers. Generally, the pointer contains the address of a variable. The
pointer to pointer contains the address of a first pointer.

61|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 19
Aim: Write a program to create two structure variables of a structure.

#include <stdio.h>
#include<conio.h>
#include <string.h>
struct Person {
char name[50];
int citNo;
float salary;
} person1;

int main() {
strcpy(person1.name, "George Orwell");
person1.citNo = 1984;
person1. salary = 2500;
printf("Name: %s\n", person1.name);
printf("Citizenship No.: %d\n", person1.citNo);
printf("Salary: %.2f", person1.salary);
getch();
return 0;
}

Output:

Name: George Orwell


Citizenship No.: 1984
Salary: 2500.00

62|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is the structure?

Ans.) The structure is a user-defined data type that allows storing multiple types of data in a single unit. It
occupies the sum of the memory of all members.
The structure members can be accessed only through structure variables.
Structure variables accessing the same structure but the memory allocated for each variable will be
different.

Q.2) What is a union?

Ans.) The union is a user-defined data type that allows storing multiple types of data in a single unit.
However, it doesn't occupy the sum of the memory of all members. It holds the memory of the largest
member only.
In union, we can access only one variable at a time as it allocates one common space for all the members
of a union.

63|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

ExperimentNo. 20
Aim: Write a program to create two objects of a single class and access their variables.

#include <stdio.h>
#include<conio.h>
struct MyClass {
char name[50];
int age;
};

int main()
{
struct MyClass object1 = {"John", 25};
struct MyClass object2 = {"Alice", 30};

printf("Object 1 - Name: %s\n", object1.name);


printf("Object 1 - Age: %d\n", object1.age);

printf("Object 2 - Name: %s\n", object2.name);


printf("Object 2 - Age: %d\n", object2.age);
getch();
return 0;
}

Output:

Object 1 - Name: John


Object 1 - Age: 25
Object 2 - Name: Alice
Object 2 - Age: 30

64|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

VivaQuestions

Q.1) What is an auto keyword in C?

Ans.) In C, every local variable of a function is known as an automatic (auto) variable. Variables which
are declared inside the function block are known as a local variable. The local variables are also known as
an auto variable. It is optional to use an auto keyword before the data type of a variable. If no value is
stored in the local variable, then it consists of a garbage value.

65|Page
IPSACADEMY,INSTITUTEOFENGINEERINGANDSCIENCEINDORE

Knowledge,Skills,Values

IPSACADEMY
16Collages,71Courses,51AcreCampus

ISO9001:2008CertifiedK

nowledge

VillageRajendraNagar

A.B.Road

Indore452012(M.P.

)India

Ph:0731-4014601-604 Mo:07746000161

EMail:[email protected]:i

es.ipsacademy.org&www.ipsacademy.org

66|Page

You might also like