KEMBAR78
PSU C Programming Lab Manual - B20EN0308 - ECE | PDF | C (Programming Language) | Pointer (Computer Programming)
0% found this document useful (0 votes)
165 views33 pages

PSU C Programming Lab Manual - B20EN0308 - ECE

This document outlines the contents of a laboratory manual for a Problem Solving Using C Programming lab course. It includes the vision and mission statements of the university and school. It then lists the program educational objectives and outcomes. Finally, it provides a list of 10 experiments that will be covered in the course, ranging from basic programs to arrays, structures, files, and pointers.

Uploaded by

I30 hanush 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)
165 views33 pages

PSU C Programming Lab Manual - B20EN0308 - ECE

This document outlines the contents of a laboratory manual for a Problem Solving Using C Programming lab course. It includes the vision and mission statements of the university and school. It then lists the program educational objectives and outcomes. Finally, it provides a list of 10 experiments that will be covered in the course, ranging from basic programs to arrays, structures, files, and pointers.

Uploaded by

I30 hanush 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/ 33

School of Electronics and

Communication Engineering
Program : B.Tech. in ECE
Problem Solving Using C Programming Lab

LABORATORY MANUAL

B20EN0308

III Semester

2021-25
Rukmini Educational
Charitable Trust www.reva.edu.in
Vision of the University
‘’REVA University aspires to become an innovative university by developing excellent human
resources with leadership qualities, ethical and moral values, research culture and innovative skills
through higher education of global standards”

Mission of the University


• To create excellent infrastructure facilities and state-of-the-art laboratories and incubation
centers
• To provide student-centric learning environment through innovative pedagogy and education
reforms
• To encourage research and entrepreneurship through collaborations and extension activities
• To promote industry-institute partnerships and share knowledge for innovation and
development
• To organize society development programs for knowledge enhancement in thrust areas
• To enhance leadership qualities among the youth and enrich personality traits, promote
patriotism and moral values.

Vision of the School


The School of Electronics and Communication Engineering is envisioned to be a leading center
of higher learning with academic excellence in the field of electronics and communication engineering
blended by research and innovation in tune with changing technological and cultural challenges
supported with leadership qualities, ethical and moral values.

Mission of the School


• Establish a unique learning environment to enable the students to face the challenges in the
field of Electronics and Communication Engineering and explore multidisciplinary which serve
the societal requirements.
• Create state-of-the-art laboratories, resources, and exposure to the current industrial trends
to enable students to develop skills for solving complex technological problems of current
times and provide a framework for promoting collaborative and multidisciplinary activities.
• Promote the establishment of Centers of Excellence in niche technology areas to nurture the
spirit of innovation and creativity among faculty and students.
• Offer ethical and moral value-based education by promoting activities which inculcate the
leadership qualities, patriotism and set high benchmarks to serve the society

Program Educational Objectives (PEOs)

The Program Educational Objectives of B. Tech in B.Tech in ECE/ ECM Engineering are as
follows:

PEO -1: To have successful professional careers in industry, government, academia, and military as
innovative engineers.
PEO -2: To successfully solve engineering problems associated with the lifecycle of B.Tech in
ECE/ ECM Engineering Systems either leading a team or as a team member.
PEO -3: To continue to learn and advance their careers through activities such as participation in
professional organizations, attainment of professional certification for lifelong
Learning and seeking higher education.
PEO -4: To be active members ready to serve the society locally and internationally and will undertake
entrepreneurship for the growth of economy and to generate employment.
Program Outcomes (POs)

On successful completion of the program, the graduates of B. Tech. in ECE/ ECM Engineering
program will be able to:

 PO-1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals for the solution of complex problems in B.Tech in ECE/ ECM Engineering.
 PO-2: Problem analysis: Identify, formulate, research literature, and analyze engineering
problems to arrive at substantiated conclusions using first principles of mathematics, natural,
and engineering sciences.
 PO-3: Design/development of solutions: Design solutions for complex engineering problems
and design system components, processes to meet the specifications with consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
 PO-4: Conduct investigations of complex problems: Use research-based knowledge
including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
 PO-5: 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.
 PO-6: 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.
 PO-7: 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.
 PO-8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
 PO-9: Individual and team work: Function effectively as an individual, and as a member or
leader in teams, and in multidisciplinary settings.
 PO-10: Communication: Communicate effectively with the engineering community and with
society at large. Be able to comprehend and write effective reports documentation. Make
effective presentations, and give and receive clear instructions.
 PO-11: Project management and finance: Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work, as a member and
leader in a team. Manage projects in multidisciplinary environments.
 PO-12: 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.
REVA University School of ECE

Contents

Expt. No. Programs list Page No.


Write a Program to calculate and display the volume of a CUBE by
1 10
reading its height, width and depth from keyboard.
Write a program to take input of name, roll no and marks obtained by a
2 student in 4 subjects of 100 marks each and display the name, Roll no 11-12
With percentage score secured.

NOTE: Also write same program for three students.


a) Write a program to print whether a given number is even or odd.
3 13
b) Write a program to print even numbers from 1 to 10.
a) write a c program to check whether a number is prime or not
4 14-15
b). write a program to find the factorial of a number.
a). write a program to find whether a character is consonant of Vowel
using switch statement
5 16-18
b). Write a program to print the sum of numbers from 1 to 10
Using for loop
a). Write a program to create an integer array of size 5, read values
6 from input device and print the values of the array. 19-20
b). Write a Program to Search an element in array.
a). Write a program to calculate factorial of a number using recursion.
7 b). Write a program to add, subtract, multiply and divide 21-23
two integers using user-defined type function with return type
c). Write a program to swap two integers using call by value and call by
reference methods of passing arguments to a function.
a).write a c program to create declare and initialize structure
8 24-25
b). write a c program to create declare and initialize an UNION
a).write a c program to find biggest among three numbers using
pointers
9 b).write a c program to swap the values of two variables using 26-29
pointer
c). Write a program to swap to array using pointers.
a).Write a program to create a file called ‘record’ and store Information
about a person, in-terms of his name, age, and salary.
10 30-31
b).Write a program to illustrate how a file stored on the disk
is read.

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |3


REVA University School of ECE

Course Title Problem Solving Using C Programming Lab Course Type HC


Course Code B20EN0308 Credits 1 Class III Semester
Contact Work Total Number of
LTP Credits Hours Load Classes Assessment in
Per Semester Weightage
Lecture - - -
Tutorial - - - 9HC)
Practical 1 2 2
Theory Practical IA SEE
- - - -

Total 1 2 2 - 28 50% 50
%

COURSE OVERVIEW:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to
develop the UNIX operating system at Bell Labs. C programming is a general-purpose, procedural
programming language used to develop software like operating systems, databases, compilers, and
so on. The main features of C language include low-level access to memory, a simple set of
keywords, and clean style. Many later languages have borrowed syntax/features directly or indirectly
from C language. Like syntax of Java, PHP, JavaScript, and many other languages are mainly based
on C language.

COURSE OBJECTIVES:
The objectives of this course are:
1. Provide exposure to problem-solving through C procedural programming
2. Explore the structure and syntax of the C programming language
3. Illustrate the applications of data types, operators, arrays, and control flow statements in problem-
solving.
4. Provide insight into concepts like pointers, structures, unions and records.

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |4


REVA University School of ECE

COURSE OUTCOMES (COs)


On successful completion of this course; the student shall be able to:
CO# Course Outcomes POs PSOs

CO1 Develop algorithms/flowcharts to solve computational problems. 1,2,3,5 1,2,3

Solve data processing applications using appropriate data types, operators 1,2,3,5,10
CO2 1,2,3
and control flow statements.
1,2,3,5,10
Write C programs using derived data types like arrays and strings to
CO3 1,2,3
operate on block of data.
Solve complex problems using procedure-oriented (modular) 1,2,3,5,10
CO4 1,2,3
programming approach
Design and develop computer programs using the concept of 1,2,3,5,10
CO5 1,2,3
pointers, structures, unions and records.

C06 Demonstrate the creation of file and file operations in C-language 1,2,3,5,10 1,2,3

BLOOM’S LEVEL OF THE COURSE OUTCOMES


Bloom’s Level
Remember Understand Apply Analyze Evaluate Create
CO# (L1) (L2) (L3) (L4) (L5) (L6)

CO1
CO2
CO3
CO4
CO5
CO6

COURSE ARTICULATION MATRIX


PSO1

PSO2
PO10

PO11

PO12

PSO3

CO#/
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9

POs
CO1 3 3 2 1 2 1 2 2 1

3 3 2 1 3 1 3 2 1
CO2

CO3 3 3 2 1 3 1 3 3 2

CO4 3 3 3 1 3 1 3 3 2

CO5 3 3 3 1 2 1 3 2 3

CO6 3 3 3 1 2 1 3 2 3

Note:1-Low,2-Medium,3-High

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |5


REVA University School of ECE

How To Compile and Execute The Programs:

 Double click on Dev C++ to open

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |6


REVA University School of ECE

 Click on file, Select New source

 Start typing the program code in editor window.

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |7


REVA University School of ECE

 Click on Save as, and save file with your SRN with appropriate extension other than C
drive

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |8


REVA University School of ECE

 Click on Compile Button (under Execute) to compile your source code. If there are any
errors in your program, then a window at the bottom will specify the warnings, after
program is compiled, click on Run button (Below Compile).

 As soon as you Run the program, output window opens momentarily and then closes.

 When you run the program, output window will show the string as below.

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e |9


REVA University School of ECE

LAB EXERCISE #1
Program: Write a Program to calculate and display the volume of a CUBE having its
height (h=10cm), width (w=12cm) and depth (8cm).
Algorithm:
1. Start
2. Define variables: h(int), w(int), d(int), vol(int)
3. Assign value to variables: h = 10, w=12, d=8
4. Calculate the volume as: vol = h*w*d
5. Display the volume (vol)
6. Stop

Flowchart:

START

Define h, w, d, Vol

h = 10, w=12, d=8,


vol=h*w*d

Print Vol

END

Code:

#include<stdio.h>
int main ()
{
//start the program
int h, w, d, vol; //variables declaration
h=10;
w=12;
d=8; //assign value to variables
vol=h*w*d; //calculation using mathematical formula
printf("The Volume of the cube is: %d",vol); //display the volume
return 0;
//end the main program
}

Output:
The Volume of the cube is: 960

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 10


REVA University School of ECE

LAB EXERCISE #2

Program: Write a program to take input of name, roll no and marks obtained
by a student in 4 subjects of 100 marks each and display the name,
Roll no with percentage score secured.

Algorithm:
1. Start
2. Define variables: name, Roll no, sub1, sub2, sub3, sub4, sum, score
3. Take input from keyboard for all the input variables
4. Calculate the sum of marks of 4 subjects and also calculate the percentage score
as:
Sum=sub1+sub2+sub3+sub4;
score = (sum/400) * 100
5. Display the name, roll number and percentage score.
6. Stop

Flowchart:

START

Define Variable: char name (20);


int rollno; float sub1, sub2, sub3, sub4,

Read name, roll no, sub1, sub2, sub3,

Sum=sub1+sub2+sub3+sub4
score=(sum/400)*100

Print name roll no

END

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 11


REVA University School of ECE

Code:
#include<stdio.h>
int main()
{
char name[20];
int rollno;
float sub1,sub2,sub3,sub4,sum,score;
printf("Enter name of student: ");
scanf(“%s”,&name);
printf("\n Enter Roll Number: ");
scanf("%d", &rollno);
printf ("\n Enter Marks in 4 Subjects:\n");
scanf("%f%f%f%f", &sub1, &sub2, &sub3, &sub4);
sum=sub1+sub2+sub3+sub4;
score = (sum/500)*100;
printf("\n Name of student: %s", name);
printf("\n Roll Number: %d", rollno);
printf ("\n Percentage score secured: %2.2f%c", score,'%');
return 0;
}

Output:
Enter name of student: Ajit Singh
Roll Number: 25
Enter Marks in 4 Subjects:
50
75
85
62
Name of student: Ajit Singh
Roll Number: 25
Percentage score secured: 68.00

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 12


REVA University School of ECE

LAB EXERCISE #3

Program: 3a) Write a program to print whether a given number is even or odd.
3b) Write a program to print even numbers from 1 to 10.

Algorithm:
1. Start
2. [ Take Input ] Read: Number
3. Check: If Number%2 == 0 Then
4. N is an Even Number.
5. Else
6. N is an Odd Number.
7. Step 4: stop

Code:
#include<stdio.h>
int main()
{
int num;
printf("Enter the number: ");
scanf("%d",&num);
if(num%2==0)
printf("\n %d is even", num);
else printf("\n %d is odd", num);
return 0;
}

Output:
Enter the number: 6
6 is even

b). Write a program to print even numbers from 1 to 10.

Code:
#include <stdio.h>
int main()
{
int i;
printf("Even numbers between 1 to 10 (inclusive):\n");
for (i = 1; i <= 10; i++)
{
if(i%2 == 0)
{
printf("%d ", i);
}
}
return 0;
}

Output:
Even numbers between1 to 10 (inclusive):
2 4 6 9 8 10

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 13


REVA University School of ECE

LAB EXERCISE #4

Program: 4a) write a c program to check whether a number is prime or not


4b). write a program to find the factorial of a number.

Algorithm:

1. Start
2. Declare a variable
3. Initialize the variable.
4. Use a for loop that iterates from 2 to N
5. Declare the count and initialize it to 0.
6. If the number is divisible by any of the numbers in between the loop then increment the count.
7. If the count is not equal to 0 then, it is not a prime number.
8. If the count is equal to 0, then it is a prime number.
9. Stop.

Code:
#include <stdio.h>
int main ()
{
int n, i, flag = 0;
printf ("Enter a positive integer: ");
scanf("%d", &n);

for (i = 2; i <= n / 2; ++i)

{
// condition for non-prime
if (n % i == 0)
{
flag = 1;
break;
}
}

if (n == 1)
{
printf("1 is neither prime nor composite.");
}
else
{
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}

return 0;
}

Output:
Enter a positive integer: 29
29 is a prime number.

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 14


REVA University School of ECE

4b). write a program to find the factorial of a number.

#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}

Output:
Enter a number: 5
Factorial of 5 is: 120

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 15


REVA University School of ECE

LAB EXERCISE #5

Program: 5a). Write a program to find whether a character is consonant of


Vowel using switch statement
5b). Write a program to print the sum of numbers from 1 to 10
Using for loop

Algorithm:
1. Start
2. Declare character type variable ch
3. Read ch from User
4. // Checking both lower and upper case vowel
IF (ch == 'a' || ch == 'A' ||
ch == 'e' || ch == 'E' ||
ch == 'i' || ch == 'I' ||
ch == 'o' || ch == 'O' ||
ch == 'u' || ch == 'U' )
5. Print "Vowel"
6. ELSE
7. Print "Consonant"
8. Stop

Flowchart:

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 16


REVA University School of ECE

5a. Write a program to find whether a character is consonant or vowel using switch
statement.

Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Enter any Alphabet\n");
scanf("%c",&ch);
switch(ch)
{
//check lower case vowel letters
case 'a':
printf("%c is a vowel",ch);
break;
case 'e':
printf("%c is a vowel",ch);
break;
case 'i':
printf("%c is a vowel",ch);
break;
case 'o':
printf("%c is a vowel",ch);
break;
case 'u':
printf("%c is a vowel",ch);
break;
case 'A':
printf("%c is a vowel",ch);
break;
case 'E':
printf("%c is a vowel",ch);
break;
case 'I':
printf("%c is a vowel",ch);
break;
case 'O':
printf("%c is a vowel",ch);
break;
case 'U':
printf("%c is a vowel",ch);
break;
default:
printf("%c is a consonant",ch);
break;
}
return 0;
}

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 17


REVA University School of ECE

Output:

When the above code is executed, it produces the following result

case 1

Enter any Alphabet a

a is a vowel

case 2

Enter any Alphabet


M
M is a consonant

5b.Write a program to print the sum of numbers from 1 to 10 using for loop

Code:
#include <stdio.h>
int main()
{
int j, sum = 0;

printf("The first 10 natural number is :\n");

for (j = 1; j <= 10; j++)


{
sum = sum + j;
printf("%d ",j);
}
printf("\nThe Sum is : %d\n", sum);
}

Output :
The first 10 natural number is:
1 2 3 4 5 6 7 8 9 10
The Sum is : 55

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 18


REVA University School of ECE

LAB EXERCISE #6

Program: 6a). Write a program to create an integer array of size 5,


read values from input device and print the values of the
array.
6b). Write a Program to Search an element in array.
Code:
#include <stdio.h>
int main()
{
int arr[5];
int i;
printf("\n\n Read and Print elements of an array:\n");
printf(" \n");
printf("Input 5 elements in the array :\n");
for(i=0; i<5; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
printf("\nElements in array are: ");
for(i=0; i<5; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Read and Print elements of an array:

Input 5 elements in the array :


element - 0 : 1
element - 2 : 2
element - 3 : 3
element - 4 : 1
element - 5 : 5

Elements in array are: 1 2 3 1 5

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 19


REVA University School of ECE

6b. Write a Program to Search an element in array.


#include<stdio.h>
int main()
{
int a[100], n, element, pos=0;
int i;
printf("Enter array size [1-100]: ");
scanf("%d", &n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("Enter element to search: ");
scanf("%d",&element);
for(i=0; i<n; i++)
{
if(a[i]==element)
{
printf("%d found at position %d", element, i+1);
return 0;
}
}
printf("%d not found.", element);
return 0;
}

Output:

Enter array size [1-100]:5


Enter array elements: 1 2 3 4 5
Enter element to search: 5
5 found at position 5

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 20


REVA University School of ECE

LAB EXERCISE #7

Program: 7a). Write a program to calculate factorial of a number using


Recursion.
7b). Write a program to add, subtract, multiply and divide two
Defined type function with return type
7c). Write a program to swap two integers using call by value
and call by reference methods of passing arguments to a
function.

7a). Write a program to calculate factorial of a number using recursion.

Code:
#include<stdio.h>

int fact(int);
int main()
{
int x,n;
printf(" Enter the Number to Find Factorial :");
scanf("%d",&n);

x=fact(n);
printf(" Factorial of %d is %d",n,x);

return 0;
}
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}

Output :
Enter the Number to Find Factorial :5
Factorial of 5 is 120

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 21


REVA University School of ECE

7b. Write a program to add, subtract, multiply and divide two integers using user-defined type
function with return type.

Code:
#include<stdio.h>
int main()
{
int num1, num2, res;
printf("Enter any two number: ");
scanf("%d%d", &num1, &num2);
res = num1+num2;
printf("Addition = %d", res);
res = num1-num2;
printf("Subtraction = %d", res);
res = num1*num2;
printf("Multiplication = %d", res);
res = num1/num2;
printf("Division = %d", res);
return 0;
}

Output :
Enter any two number: 5 7
Addition : 12
Subtraction: -2
Multiplication: 35
Division: 0

7c). Write a program to swap two integers using call by value and call by
reference methods of passing arguments to a function.

Call by Value Example: Swapping the values of the two variables


Code:
#include <stdio.h>
void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}

int main(){
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(x,y);
printf("Values after swap: x = %d, y = %d", x,y);
}

Output :
Values before swap: x = 10, y = 11
Values after swap: x = 10, y = 11

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 22


REVA University School of ECE

Call by Reference Example: Swapping the values of the two variables

Code:

#include <stdio.h>
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

int main(){
int x = 10;
int y = 11;
printf("Values before swap: x = %d, y = %d\n", x,y);
swap(&x,&y);
printf("Values after swap: x = %d, y = %d", x,y);
}

Output :
Values before swap: x = 10, y = 11
Values after swap: x = 11, y = 10

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 23


REVA University School of ECE

LAB EXERCISE #8

Program: 8a).write a c program to create declare and initialize structure


8b).write a c program to create declare and initialize an UNION

8a).write a c program to create declare and initialize structure

Code:
#include <stdio.h>

/*structure declaration*/
struct employee
{
char name[30];
int empId; float salary;

};

int main()
{ /*declare and initialization of structure variable*/
struct employee emp={"Mike",1120,76909.00f};

printf("\n Name: %s" ,emp.name);


printf("\n Id: %d"emp.empId); printf("\n
Salary: %f\n",emp.salary);
return 0;

Output
Name: Mike
Id: 1120
Salary: 76909.000000

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 24


REVA University School of ECE

8b) write a c program to create declare and initialize an UNION

Code:
#include <stdio.h>

// union declaration
union pack {
char a;
int b;
double c;
};

int main()
{
pack p; //union object/variable declaration

printf("\nOccupied size by union pack: %d", sizeof(pack));

// assign value to each member one by one other it will replace last value
p.a = 'A';
printf("\nValue of a:%c", p.a);

p.b = 10;
printf("\nValue of b:%d", p.b);

p.c = 12345.6790;
printf("\nValue of c:%f", p.c);

// see, what will happen? if u will assign values together


p.a = 'A';
p.b = 10;
p.c = 12345.6790;

// here the last value of p.c will be accessed by all members


printf("\nValue of a:%c, b:%d, c:%f", p.a, p.b, p.c);

return 0;
}
Output:
Occupied size by union pack: 8
Value of a:A
Value of b:10
Value of c:12345.679000
Value of a:�, b:-377957122, c:12345.679000

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 25


REVA University School of ECE

LAB EXERCISE #9

Program: 9a). write a c program to find biggest among three numbers using
pointers
9b). write a c program to swap the values of two variables using
pointer
9(c). Write a program to swap to array using pointers.

9a). write a c program to find biggest among three numbers using


pointers

Code:
#include <stdio.h>
int main()
{
int num1, num2, num3;
int *p1, *p2, *p3;

//taking input from user


printf("Enter First Number: ");
scanf("%d",&num1);
printf("Enter Second Number: ");
scanf("%d",&num2);
printf("Enter Third Number: ");
scanf("%d",&num3);

//assigning the address of input numbers to pointers


p1 = &num1;
p2 = &num2;
p3 = &num3;
if(*p1 > *p2)
{
if(*p1 > *p3)
{
printf("%d is the largest number", *p1);
}
else
{
printf("%d is the largest number", *p3);
}
}
else
{

if(*p2 > *p3)


{
printf("%d is the largest number", *p2);
}
else
{
printf("%d is the largest number", *p3);
}
}

return 0;
}

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 26


REVA University School of ECE

Output:
Enter the first number: 10
Enter the second number: 5
Enter the third number:
15 is the largest number

9b) write a c program to swap the values of two variables using pointer

Code:

# include < stdio.h >


int main ( )
{

int a, b, temp ;
int *p1, *p2 ;
printf(" Enter the first number : ") ;
scanf("%d ", & a) ;
printf("\n Enter the second number : ") ;
scanf("%d ", & b) ;
printf("\n Two Number before swapping :%d, %d ", *p1, *p2) ;
temp = *p1 ;
*p1 = *p2 ;
*p2 = temp ;

printf("\n Two Number after swapping :%d, %d ", *p1, *p2) ;


return ( 0 );

Output:
Enter the first number: 10
Enter the second number: 15
Two Number before swapping: 10, 15
Two Number after swapping: 15, 10

9(c). Write a program to swap to array using pointers.

Code:
#include <stdio.h>

#define MAX_SIZE 100 // Maximum array size

/* Function declarations */
void inputArray(int *arr, int size);
void printArray(int *arr, int size);
void swapArray(int *sourceArr, int *destArr, int size);

int main()
{
int sourceArr[MAX_SIZE];
int destArr[MAX_SIZE];

int size;

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 27


REVA University School of ECE

// Input array size


printf("Enter size of array: ");
scanf("%d", &size);

// Input elements of destination array


printf("Enter %d elements in source array: ", size);
inputArray(sourceArr, size);

// Input element of destination array


printf("Enter %d elements in destination array: ", size);
inputArray(destArr, size);

/*
* Print elements of both arrays before swapping
*/
printf("\n\nSource array before swapping: ");
printArray(sourceArr, size);

printf("\nDestination array before swapping: ");


printArray(destArr, size);
/* Swap elements of both arrays. */
swapArray(sourceArr, destArr, size);

/*
* Print elements of both arrays after swapping
*/
printf("\n\nSource array after swapping: ");
printArray(sourceArr, size);

printf("\nDestination array after swapping: ");


printArray(destArr, size);

return 0;
}

/**
* Function used to read input from user in an array.
*
* @arr Pointer to array to store input
* @size Size of the array
*/
void inputArray(int *arr, int size)
{
// Pointer to last element of array.
int *arrEnd = (arr + (size - 1));

// Input elements in array using pointer


while(arr <= arrEnd)
scanf("%d", arr++);
}

/**

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 28


REVA University School of ECE

* Function used to print elements of array.


*
* @arr Pointer to array, which is to print.
* @size Size of the array
*/
void printArray(int *arr, int size)
{
// Pointer to last element of array.
int *arrEnd = (arr + (size - 1));

// Print elements of array one by one


while(arr <= arrEnd)
printf("%d, ", *(arr++));
}

/**
* Function to swap elements of two arrays.
*
* @sourceArr Pointer to source array to swap.
* @destArr Pointer to destination array to swap.
* @size Size of array.
*/
void swapArray(int * sourceArr, int * destArr, int size)
{
// Pointer to last element of source array
int * sourceArrEnd = (sourceArr + (size - 1));

// Pointer to last element of destination array


int * destArrEnd = (destArr + (size - 1));

/*
* Swap individual element of both arrays
*/
while(sourceArr <= sourceArrEnd && destArr <= destArrEnd)
{
*sourceArr ^= *destArr;
*destArr ^= *sourceArr;
*sourceArr ^= *destArr;

// Increment source array to point to next element


sourceArr++;

// Increment destination array to point to next element


destArr++;
}
}

Output:
Enter size of array: 10
Enter 10 elements in source array: 1 2 3 4 5 6 7 8 9 10
Enter 10 elements in destination array: 10 20 30 40 50 60 70 80 90 100

Source array before swapping: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,


Destination array before swapping: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,

Source array after swapping: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
Destination array after swapping: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 29


REVA University School of ECE

LAB EXERCISE #10

Program: 10(a). Write a program to create a file called ‘record’ and store
Information about a person, in-terms of his name, age,
and salary.
10(b). Write a program to illustrate how a file stored on the disk
is read.

10(a). Write a program to create a file called ‘record’ and store


Information about a person, in-terms of his name, age, and salary.

Code:
#include <stdio.h>
#include <conio.h>
void main()
{
FILE *fptr;
char name[20];
int age;
float salary;
fptr = fopen("emp.rec", "w");
if (fptr == NULL)
{
printf("File does not exists \n");
return;
}
printf("Enter the name \n");
scanf("%s", name);
fprintf(fptr, "Name = %s\n", name);
printf("Enter the age\n");
scanf("%d", &age);
fprintf(fptr, "Age = %d\n", age);
printf("Enter the salary\n");
scanf("%f", &salary);
fprintf(fptr, "Salary = %.2f\n", salary);
fclose(fptr);
getch();
}
Output:
Enter the name
Enter the age
Enter the salary

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 30


REVA University School of ECE

10(b). Write a program to illustrate how a file stored on the disk is read.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *fptr;
char filename[15];
char ch;
clrscr();

printf("Enter the filename to be opened\n");


gets(filename);

fptr = fopen (filename, "r"); /*open for reading*/

if (fptr == NULL)
{
printf("Cannot open file\n");
exit(0);
}

ch = fgetc(fptr);

while (ch != EOF)


{
printf ("%c", ch);
ch = fgetc(fptr);
}

fclose(fptr);
getch();
}

Output
Enter the filename to be opened
emp.rec
Name = Prabhu
Age = 25
Salary = 25000.00

Problem Solving Using C Programming – B20EN0308 Sem : III P a g e | 31


Rukmini Knowledge Park, Kattigenahalli
Yelahanka, Bengaluru - 560 064
Karnataka, India.

Ph: +91- 90211 90211, +91 80 4696 6966


E-mail: admissions@reva.edu.in

Follow us on

/REVAUniversity

You might also like