Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
109 views

Lab Manual Adv C Programming

Uploaded by

fface5450
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

Lab Manual Adv C Programming

Uploaded by

fface5450
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

PIMPRI CHINCHWAD UNIVERSITY

School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102

Lab Manual Prepared By,

Dr. Pallavi Ahire

Dr. Swati Shirke

Dr. Sagar Pande

Prof. Pujita Venna


PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 1
Title: Implement C Program to multiply two matrices (M x N) and print the result. Accept
details of two matrices as input.

Objective:
 To understand the use of 2D Array.
 To understand matrix operations.

Outcomes:
 At the end of this lab, the student will be able toUse arrays of different data types with
proper declarations.
 Use multi-dimensional arrays to carry out matrix manipulations such as matrix
multiplication.

Aim:
Write a program in C to perform matrix operation for multi_matrix() using appropriate data
structure. Also write how to determine time complexity and space complexity of your program.

Theory:
To Multiplication of matrix,it must be of identical order and for multiplication, the number of
columns in the first matrix equals the number of rows in the second matrix.

Algorithm (Matrix Multiplication)

Start
 Define three matrices A, B, C and read their respective row and column numbers.
 We check if the matrix can be multiplied or not, if n is not equal to q matrix can't be
multiplied and an error message is generated.
 Read matrices A and B.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
 First, start a loop which goes up to giving row elements of A Secondly, inside it
again starts a loop which goes up to giving row elements of B. At last, we define a
loop which goes up to giving column element of B
 Then, store their corresponding multiplication by sum= sum + A[i][k] * B[k][j], which
gets updated each time, and acts as the mathematical formula of multiplication used for
matrix.
 sum is assigned into C[i][j] and likewise, C stores the multiplication result of matrix A
and B
 Finally, display the result for multiplication of given matrices
 Stop

Source Code :

#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

Output :

enter the number of row=3


PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

Conclusion:
Thus, we implemented matrix operations using 2D array.

Questions
1. Define Array? Explain in details types of array.
2. What is the syntax of array?
3. Find out frequency count for multiplication function.
4. What is properties of array in C?
5. What is algorithm in C?
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 2

Title: Write a program in C to compare two strings without using string library functions. Justify
whether it is palindrome or not.

Objective: To Understand and implement string arrays.

Outcomes:
At the end of this lab, the student will be able to
 Use string arrays with proper declaration.
 Use string library functions to compare
 Read characters and strings from terminal and print them back
 Create C programs to manipulate characters
 Apply characters in logic of programs
Aim:
Implementation of C program to compare two strings without using string library functions.
Justify whether it is palindrome or not.

Theory:
Character array is a sequence of zero or more characters surrounded by a double
quoteare. May include letters, digits and various special characters such as +, -, *, / and $.
Internal representations of a string have a null character '\0‘at the end. Here, a string madam.
When we reverse this string again, it forms the same string, madam. If you reverse a string and it
remains the same, it is a palindrome. For example, naman, neven, and anna are examples of
palindrome strings.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

Logic behind code


 The 0th character in the char array, string1, is the same as the 4th character in the same
string.
 1st character is the same as 3rd character.
 2nd character is the same as 2nd character.
 ....
o ith character is the same as the 'length-i-1'th character.
o If any of the above conditions fails, the flag is set to true(1), implying that the
string is not a palindrome.
o By default, the value of the flag is false(0). Hence, the string is a palindrome if all
the conditions are satisfied.

Algorithm:

 Read the string entered by the user


 Calculate the length and store it in a variable
 Initialize high and low indexes
 Compare the characters at low and high index
 Use for loop to keep comparing until a mismatch is found

Source Code:

#include<stdio.h>
int main()
{
char string[40];
int length=0, flag=1,i;
printf("Enter string:\n");
gets(string);
for(i=0;string[i]!='\0';i++)
{
length++;
}
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
for(i=0;i< length/2;i++)
{
if( string[i] != string[length-1-i] )
{
flag=0;
break;
}
}
if(flag==1)
{
printf("PALINDROME");
}
else
{
printf("NOT PALINDROME");
}
return 0;
}
Output:
Run 1:
------------
Enter String:
madam ↲
PALINDROME

Run 2:
------------
Enter String:
step on no pets ↲
PALINDROME
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Run 3:
------------
Enter String:
PCU↲
NOT PALINDROME

Conclusion:

A 'c program for string palindrome' is a fundamental coding problem that helps you understand
key programming concepts.

Questions
1. What is string? Explain in detail.
2. What is an example of a string palindrome?
3. How to find length of a string in C?
4. How to accept a string in C?
5. How do you find all palindromes in a string?
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 3
Title: Write a program in C to check whether a number is a prime number or not using the
function.

Objective: To Understand and implement functions.


Outcomes:
At the end of this lab, the student will be able to
 Create C programs using functions
 Apply user defined functions with proper definition and declarations

Aim: Implementation of program in C to check whether a number is a prime number or not


using the function

Theory:

A natural number is said to be prime if it is only divisible by itself and 1. In short, a prime
number has only two factors that are 1 and the number itself. The numbers that are not prime are
called composite numbers.
A prime number can be written as a product of only two numbers. For example, consider 3.
Now, 3 can be written in the form of the product of two numbers in only one way i.e., 1 * 3.
Whereas, 8 which is a composite number can be written as 1 * 8 and 2 * 4.
The following diagrammatic illustration shows the prime numbers between 1 and 100. Observe
this table to find some interesting facts about the prime numbers
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

Algorithm :

 Take num as input.


 Initialize a variable temp to 0.
 Iterate a “for” loop from 2 to num/2.
 If num is divisible by loop iterator, then increment temp.
 If the temp is equal to 0,
 Return “Num IS PRIME”.
 Else
 Return “Num IS NOT PRIME”.

Source Code :
#include<stdio.h>
int PrimeOrNot(int);
int main()
{
int n1,prime;
printf("\n\n Function : check whether a number is prime number or not :\n");
printf("---------------------------------------------------------------\n");
printf(" Input a positive number : ");
scanf("%d",&n1);
prime = PrimeOrNot(n1);
if(prime==1)
printf(" The number %d is a prime number.\n",n1);
else
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
printf(" The number %d is not a prime number.\n",n1);
return 0;
}
int PrimeOrNot(int n1)
{
int i=2;
while(i<=n1/2)
{
if(n1%i==0)
return 0;
else
i++;
}
return 1;
}

Output:
Input a positive number : 5
The number 5 is a prime number.

Conclusion:
A basic way to find if a number is prime is to loop from 2 to n-1 and check if the number is
divisible by any number in this range. If it is, then it's not a prime number.

Questions:

1. How do you check whether a number is a prime number or not?


2. How to print prime number in C?
3. What is conditional loop with example?
4. What are examples of while loops?
5. What is for loop in C?
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 4
Title: Write a program to generate Fibonacci series with and without using recursive function.

Objective: To understand and implement recursive function.

Outcomes:
At the end of this lab, the student will be able to
 Create C programs using recursive functions
 Apply user defined functions with proper definition and declarations
Theory:

The Fibonacci series is the sequence of numbers (also called Fibonacci numbers), where every
number is the sum of the preceding two numbers, such that the first two terms are '0' and '1'. In
some older versions of the series, the term '0' might be omitted. A Fibonacci series can thus be
given as, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . It can thus be observed that every term can be
calculated by adding the two terms before it.
Given the first term, F0 and second term, F1 as '0' and '1' respectively, the third term here can be
given as, F2 = 0 + 1 = 1

Similarly,

 F3 = 1 + 1 = 2
 F4 = 2 + 1 = 3
 F5 = 2 + 3 = 5
 F6 = 3 + 5 = 8
 F7 = 5 + 8 = 13
 and so on

Therefore, to represent any (n+1)th term in this series, we can give the expression as, Fn = Fn-
1 + Fn-2.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

Fibonacci Series Formula

The Fibonacci series formula in maths can be used to find the missing terms in a Fibonacci
series. The formula to find the (n+1)th term in the sequence is defined using the recursive
formula such that F0 = 0, F1 = 1 to give Fn.

The Fibonacci formula using recursion is given as follows.

Fn = Fn-1 + Fn-2, where n > 1

Algorithm:
1. Add integer value to num variable.
2. Then initialize two variables n1 and n2 with values 0 and 1.
3. Check if the num value is equal to 1, then print n1 only.
4. Else
a. Print the value of n1 and n2.
b. Then run a for loop from range (i = 2; i<num; i++) and inside the for loop
perform the following operations.
i. Initialize n3 with value of n1 + n2.
ii. Update n1 to n2.
iii. Update n2 to n3.
iv. At last print n3.
v.
Source Code :
1. Without Recursive Function:
#include <stdio.h>
void generateFibonacci(int n) {
int a = 0, b = 1, next;
printf("Fibonacci Series: ");
for (int i = 1; i<= n; ++i) {
printf("%d, ", a);
next = a + b;
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
a = b;
b = next;
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of terms in the Fibonacci series: ");
scanf("%d", &n);
generateFibonacci(n);
return 0;
}
2. With Recursive Function:
#include <stdio.h>
int fibonacci(int n) {
if (n <= 1)
return n;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
void generateFibonacciRecursive(int n) {
printf("Fibonacci Series: ");
for (int i = 0; i< n; ++i) {
printf("%d, ", fibonacci(i));
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of terms in the Fibonacci series: ");
scanf("%d", &n);
generateFibonacciRecursive(n);
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
return 0;
}

Output:
1. With and Without Recursive Function:
Enter the number of terms in the Fibonacci series: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Conclusion:
We are able to generate Fibonacci series for a desired range with and without recursive function.

Questions:
1. Explain the concept of recursion with sample C program.
2. What is Fibonacci formula. Elaborate your answer with Fibonacci series.
3. Explain the concept of function in C with sample C code.
4. Explain C function parameters with sample pseudocode.
5. Explain the structure of function declaration in C with sample pseudocode.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 5
Title: A class teacher wants to keep record of 10 students in the class along with the names and
marks obtained in 5 subjects. Write a C program with function that displays:
a) Name of the student with highest marks in a particular subject.
b) Overall percentage result of the class
c) Total number of passing students in the class
d) Total number of students failing in one subject
e) Total number of distinctions in the class.

Objective: To understand and implement function.


Outcomes:
At the end of this lab, the student will be able to
 Create C programs using functions
 Apply user defined functions with proper definition and declarations

Theory:

In this assignment, we are creating a structure as ‘student’ with members as ‘student name’ and
‘marks’.

Structures (also called structs) are a way to group several related variables into one place. Each
variable in the structure is known as a member of the structure.Unlike an array, a structure can
contain many different data types (int, float, char, etc.).

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it. To access members of a structure, use
the dot syntax (.) and use the struct keyword inside the main() method, followed by the name of
the structure and then the name of the structure variable:
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Sample Pseudocode:

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}

Source Code:
#include <stdio.h>
#include <string.h>
#define NUM_STUDENTS 5
#define NUM_SUBJECTS 3
struct Student {
char name[50];
float marks[NUM_SUBJECTS];
};
// Function prototypes
void inputStudentData(struct Student students[]);
void displayHighestInSubject(struct Student students[], int subject);
float calculateOverallPercentage(struct Student students[]);
int countPassingStudents(struct Student students[]);
int countFailingOneSubject(struct Student students[]);
int countDistinctions(struct Student students[]);
int main() {
struct Student students[NUM_STUDENTS];
inputStudentData(students);
// a) Name of the student with the highest marks in a particular subject
displayHighestInSubject(students, 0); // Assuming subject index 0 for the demonstration
// b) Overall percentage result of the class
float overallPercentage = calculateOverallPercentage(students);
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
printf("\nOverall Percentage Result of the Class: %.2f%%\n", overallPercentage);
// c) Total number of passing students in the class
int passingStudents = countPassingStudents(students);
printf("Total Passing Students in the Class: %d\n", passingStudents);
// d) Total number of students failing in one subject
int failingOneSubject = countFailingOneSubject(students);
printf("Total Students Failing in One Subject: %d\n", failingOneSubject);
// e) Total number of distinctions in the class
int distinctions = countDistinctions(students);
printf("Total Distinctions in the Class: %d\n", distinctions);
return 0;
}
void inputStudentData(struct Student students[]) {
printf("Enter details for %d students:\n", NUM_STUDENTS);
for (int i = 0; i< NUM_STUDENTS; ++i) {
printf("Student %d:\n", i + 1);
printf("Enter Name: ");
scanf("%s", students[i].name);
printf("Enter Marks for 3 Subjects:\n");
for (int j = 0; j < NUM_SUBJECTS; ++j) {
printf("Subject %d: ", j + 1);
scanf("%f", &students[i].marks[j]);
}
}
}
void displayHighestInSubject(struct Student students[], int subject) {
float highestMarks = students[0].marks[subject];
int highestIndex = 0;
for (int i = 1; i< NUM_STUDENTS; ++i) {
if (students[i].marks[subject] >highestMarks) {
highestMarks = students[i].marks[subject];
highestIndex = i;
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
}
}
printf("\nStudent with Highest Marks in Subject %d: %s\n", subject + 1, students[highestIndex].name);
}
float calculateOverallPercentage(struct Student students[]) {
float totalMarks = 0.0;
for (int i = 0; i< NUM_STUDENTS; ++i) {
for (int j = 0; j < NUM_SUBJECTS; ++j) {
totalMarks += students[i].marks[j];
}
}
return (totalMarks / (NUM_STUDENTS * NUM_SUBJECTS)) * 100.0;
}
int countPassingStudents(struct Student students[]) {
int passingCount = 0;
for (int i = 0; i< NUM_STUDENTS; ++i) {
int totalMarks = 0;
for (int j = 0; j < NUM_SUBJECTS; ++j) {
totalMarks += students[i].marks[j];
}
if (totalMarks >= 40 * NUM_SUBJECTS) { // Assuming passing marks for each subject is 40
passingCount++;
}
}
return passingCount;
}
int countFailingOneSubject(struct Student students[]) {
int failingCount = 0;
for (int i = 0; i< NUM_STUDENTS; ++i) {
int failCount = 0;
for (int j = 0; j < NUM_SUBJECTS; ++j) {
if (students[i].marks[j] < 40) { // Assuming passing marks for each subject is 40
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
failCount++;
}
}
if (failCount == 1) {
failingCount++;
}
}
return failingCount;
}
int countDistinctions(struct Student students[]) {
int distinctions = 0;
for (int i = 0; i< NUM_STUDENTS; ++i) {
int distinctionCount = 0;
for (int j = 0; j < NUM_SUBJECTS; ++j) {
if (students[i].marks[j] >= 75) { // Assuming distinction marks for each subject is 75
distinctionCount++;
}
}
if (distinctionCount == NUM_SUBJECTS) {
distinctions++;
}
}
return distinctions;
}
Output:
Enter details for 5 students:
Student 1:
Enter Name: Aditya
Enter Marks for 3 Subjects:
Subject 1: 90
Subject 2: 95
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Subject 3: 82
Student 2:
Enter Name: Prerna
Enter Marks for 3 Subjects:
Subject 1: 88
Subject 2: 93
Subject 3: 94
Student 3:
Enter Name: Anushka
Enter Marks for 3 Subjects:
Subject 1: 78
Subject 2: 79
Subject 3: 82
Student 4:
Enter Name: Ritwik
Enter Marks for 3 Subjects:
Subject 1: 92
Subject 2: 90
Subject 3: 89
Student 5:
Enter Name: Pooja
Enter Marks for 3 Subjects:
Subject 1: 90
Subject 2: 91
Subject 3: 93

Student with Highest Marks in Subject 1: Ritwik

Overall Percentage Result of the Class: 88.40%


PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Total Passing Students in the Class: 5
Total Students Failing in One Subject: 0
Total Distinctions in the Class: 5

Conclusion:
Structure in C is a user-defined data type and is created using the struct keyword. It works in
binding the two or more data types together. It also helps organize data effectively and takes less
time to build a better presentation of the stored data

Questions:
1. What is structure? How to create structure in C? elaborate your answer with sample
pseudocode of structure creation.
2. How to access structure members?
3. What is define function in C?
4. What are the four types of functions in C?
5. How to define function using ‘#define’ in C?
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 6
Title: Write a program in C to store n elements in an array and print the elements using a
pointer.

Objective: To Understand and implement array pointer.

Outcomes:
At the end of this lab, the student will be able to
 Use pointers with proper declarations
 Create C programs using pointers for basic integer utilities

Theory:

Array elements in memory are stored sequentially. For example, consider the given
array and its memory representation

intarr[]={10,20,30,40,50};

Pointer and array memory representation


PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
If you have a pointer say ptr pointing at arr[0]. Then you can easily apply pointer
arithmetic to get reference of next array element. You can either use (ptr + 1) or ptr++ to
point to arr[1].

Visual Representation:

Algorithm:

1. START
2. INITIALIZE arr[] = {1, 2, 3, 4, 5}.
3. length= sizeof(arr)/sizeof(arr[0])

int *ptr = arr;

4. PRINT "Elements of given array:"


5. REPEAT STEP 6 and STEP 7 UNTIL i<length
6. *(ptr + i));
7. PRINT arr[i]
8. RETURN 0.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

9. END

Source Code:
#include <stdio.h>
int main() {
int n;
// Get the number of elements from the user
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare an array of size n
int arr[n];
// Input elements into the array
printf("Enter %d elements:\n", n);
for (int i = 0; i< n; ++i) {
scanf("%d", &arr[i]);
}
// Use a pointer to print the elements
int *ptr = arr;
// Print the elements using the pointer
printf("Elements in the array: ");
for (int i = 0; i< n; ++i) {
printf("%d ", *(ptr + i));
}
return 0;
}
Output:
Enter the number of elements: 4
Enter 4 elements:
3
5
2
8
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Elements in the array: 3 5 2 8

Conclusion:
In C, a pointer array is a homogeneous collection of indexed pointer variables that are references
to a memory location. It is generally used in C Programming when we want to point at multiple
memory locations of a similar data type in our C program. We can access the data by
dereferencing the pointer pointing to it.

Questions:
1. What is the importance of pointer in array?
2. Explain the syntax of array of pointers in C.
3. How pointer is used to access elements of an array?
4. Explain in short array of pointers to character.
5. Explain with necessary diagram memory representation of pointer and array.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 7
Title: Write a program to swap values of two elements. Use function and pass argument using call by
value and call by reference.
Objective: To Understand and implement pointers.
Outcomes:
At the end of this lab, the student will be able to
 Use pointers with proper declarations
 Create C programs using pointers for basic integer utilities
Theory:

There are two methods to pass the data into the function in C language, i.e., call by value and call
by reference.

Call by value:

o In call by value method, the value of the actual parameters is copied into the formal
parameters.
o In call by value method, we cannot modify the value of the actual parameter by the
formal parameter.
o In call by value, different memory is allocated for actual and formal parameters since the
value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas formal
parameter is the argument which is used in the function definition.

Call by reference
o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and
actual parameters. All the operations in the function are performed on the value stored at
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

the address of the actual parameters, and the modified value gets stored at the same
address.

Source Code:
//C program to swap two numbers using call by value
#include <stdio.h>
/* Swap function definition */
void swap(int num1, int num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", num1, num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("In Function values after swapping: %d %d\n\n", num1, num2);
}
/* main() function definition */
int main()
{
int n1, n2;
/* Input two integers from user */
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
/* Print value of n1 and n2 in before swapping */
printf("In Main values before swapping: %d %d\n\n", n1, n2);
/* Function call to swap n1 and n2 */
swap(n1, n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
Output:
Before swapping the values in main a = 10, b = 20
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

/**
* C program to swap two numbers using call by reference
*/
#include <stdio.h>
/**
* *num1 - pointer variable to accept memory address
* *num2 - pointer variable to accept memory address
*/
void swap(int * num1, int * num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", *num1, *num2);
temp = *num1;
*num1 = *num2;
*num2 = temp;
printf("In Function values after swapping: %d %d\n\n", *num1, *num2);
}
/* main() function declaration */
int main()
{
int n1, n2;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
printf("In Main values before swapping: %d %d\n\n", n1, n2);
/*
* &n1 - & evaluate memory address of n1
* &n2 - & evaluate memory address of n2
*/
swap(&n1, &n2);
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
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

Conclusion:
In call by value A copy of the value is passed into the function and in call by reference
an address of value is passed into the function.

In call by value Actual and formal arguments are created at the different memory
location and in call by reference Actual and formal arguments are created at the same memory
location.

Questions:

1. What is an argument in a function?


2. How do you pass arguments using call by value?
3. How do you pass arguments using call by reference?
4. Differentiate call by value and call by reference.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 8
Title: Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc( )/ calloc( ) function.

Objective: To Understand and implement pointers.


Outcomes:
At the end of this lab, the student will be able to
 Use pointers with proper declarations
 Create C programs using pointers for basic integer utilities
 Use malloc(), realloc() and free functions to dynamically allocate and deallocate
memory involving pointers
 Apply appropriate dynamic memory allocation methods in programs
Theory:

An array is a collection of a fixed number of values. Once the size of an array is declared, it
cannot be changed.

In some cases the size of array declared may be insufficient. To solve this issue, memory can be
allocated manually during run-time. This is known as dynamic memory allocation in C
programming.
To allocate memory dynamically, library functions malloc() , Calloc(), Realloc() and free() are
used. These functions are defined in the <stdlib.h> header file.
malloc() : The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it
returns a pointer of void which can be casted into pointers of any form.
malloc syntax:
ptr=(castType*)malloc(size);

calloc():
The name "calloc" stands for contiguous allocation.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
The malloc() function allocates memory and leaves the memory uninitialized, whereas the
calloc() function allocates memory and initializes all bits to zero.
Calloc() syntax:
ptr=(castType*)calloc(n,size);

Source Code:
// Program to calculate the sum of n numbers entered by the user. Using malloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
// Program to calculate the sum of n numbers entered by the user. Using Calloc ()
#include <stdio.h>
#include <stdlib.h>
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Output of malloc():
Enter number of elements: 3
Enter elements: 100
20
36
Sum=156
Output of calloc():
Enter number of elements: 3
Enter elements: 100
20
36
Sum=156
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Conclusion:
Use malloc() when you need to allocate a block of memory without initialization or when
you need to customize the initialization values manually. Use calloc() when you need to allocate
memory for arrays, especially for numeric or pointer arrays, and require the memory to be
initialized to zero.
malloc() and calloc() are both useful functions for dynamic memory allocation in C, but
understanding their differences and appropriate use cases can help you choose the right one for

your program.
Questions:
1. What is dynamic memory allocation?
2. What is the purpose of malloc() and calloc() in C?
3. What does malloc() stands for?
4. What is the syntax for malloc()?
5. What is the syntax for calloc()?
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 9
Title: Write a C program using an array of structures to store records of N students in a subject.
Each record should contain Name of type char, Roll No of type char, and marks of type int.
calculate the average marks of N students.

Objective: To Understand and implement array of structures.


Outcomes:
At the end of this lab, the student will be able to
 Use structures with proper declarations
 Create C programs using structures to store records
Theory:

An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used
to store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Need for Array of Structures

Suppose we have 50 employees and we need to store the data of 50 employees. So for that, we
need to define 50 variables of struct Employee type and store the data within that. However,
declaring and handling the 50 variables is not an easy task. Let’s imagine a bigger scenario, like
1000 employees.

So, if we declare the variable this way, it’s not possible to handle this.

struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;

For that, we can define an array whose data type will be struct Employee soo that will be easily
manageable.

Declaration of Array of Structures

struct structure_namearray_name [number_of_elements];

Initialization of Array of Structures

We can initialize the array of structures in the following ways:

struct structure_namearray_name [number_of_elements] = {

{element1_value1, element1_value2, ....},

{element2_value1, element2_value2, ....},

......

......

};

The same initialization can also be done as:


PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
struct structure_namearray_name [number_of_elements] = {

element1_value1, element1_value2 ....,

element2_value1, element2_value2 .....

};

GNU C compilers supports designated initialization for structures so we can also use this in the
initialization of an array of structures.

struct structure_namearray_name [number_of_elements] = {

{.element3 = value, .element1 = value, ....},

{.element2 = value, .elementN = value, ....},

......

......

};

Aim: Implementation of C program to store the data using array of structure.

Source Code Screenshots:

/* Program to understand array of structures*/

#include <stdio.h>
#define MAX_STUDENTS 100
// Structure for student record
struct Student {
char name[50];
char rollNo[15];
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
int marks;
};
int main() {
struct Student students[MAX_STUDENTS];
int N;
// Input the number of students
printf("Enter the number of students: ");
scanf("%d", &N);
// Input student details
for (int i = 0; i< N; i++) {
printf("\nEnter details for Student %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]s", students[i].name);
printf("Roll No: ");
scanf(" %[^\n]s", students[i].rollNo);
printf("Marks: ");
scanf("%d", &students[i].marks);
}
// Calculate average marks
int totalMarks = 0;
for (int i = 0; i< N; i++) {
totalMarks += students[i].marks;
}
float averageMarks = (float)totalMarks / N;
// Display results
printf("\nStudent Records and Average Marks:\n");
printf("%-20s%-15s%-10s\n", "Name", "Roll No", "Marks");
printf("-----------------------------------------\n");

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


printf("%-20s%-15s%-10d\n", students[i].name, students[i].rollNo, students[i].marks);
}
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
printf("\nAverage Marks: %.2f\n", averageMarks);
return 0;
}

Result Screenshots:
Enter the number of students: 2
Enter details for Student 1:
Name: sdp
Roll No: 10
Marks: 20
Enter details for Student 2:
Name: guruji
Roll No: 20
Marks: 30
Student Records and Average Marks:
Name Roll No Marks
-----------------------------------------
sdp 10 20
guruji 20 30

Average Marks: 25.00


Conclusion: We understood the concept ofarray of structure for storing the record of the
students.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Questions:

1. Explain the concept of array of structure with sample C program.


2. What is the need for Array of Structures. Elaborate your answer with example.
3. Explain the concept of structure in C with sample C code.
4. Explain Advantages and Disadvantages of using array of structure.
5. Explain the array of structure declaration in C with sample pseudocode.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Assignment No. 10
Title: Write a program using array of structure for maintaining departmental library information book
record (Accession number, title, edition, author and tag). The tag can be either purchase cost or name of
the donor. Use union within structure for tag & display list of purchased and donated books separately.

Objective: To Understand and implement array of structure.


Outcomes:
At the end of this lab, the student will be able to
 Use structures with proper declarations
 Create C programs using structures to store records
Theory:

Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many
members, but only one member can contain a value at a particular point in time.

Union is a user-defined data type, but unlike structures, they share the same memory location.

Let's understand this through an example.

1. struct abc
2. {
3. int a;
4. char b;
5. }

The above code is the user-defined structure that consists of two members, i.e., 'a' of type int and
'b' of type character. When we check the addresses of 'a' and 'b', we found that their addresses are
different. Therefore, we conclude that the members in the structure do not share the same
memory location.
When we define the union, we found that union is defined in the same way as the structure is
defined but the difference is that union keyword is used for defining the union data type, whereas
the struct keyword is used for defining the structure. The union contains the data members, i.e.,
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
'a' and 'b', when we check the addresses of both the variables then we find that both have the
same addresses. It means that the union members share the same memory location.

In union, members will share the memory location. If we try to make changes in any of the
member then it will be reflected to the other member as well. Let's understand this concept
through an example.

1. union abc
2. {
3. int a;
4. char b;
5. }var;
6. int main()
7. {
8. var.a = 66;
9. printf("\n a = %d", var.a);
10. printf("\n b = %d", var.b);
11. }

In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of union abc
type. In the main() method, we assign the 66 to 'a' variable, so var.a will print 66 on the screen.
Since both 'a' and 'b' share the memory location, var.b will print 'B' (ascii code of 66).

Syntax

The syntax for union of structure is as follows −

union uniontag{
datatype member 1;
datatype member 2;
----
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

----
datatype member n;
};

Example

The following example shows the usage of union of structure −

union sample{
int a;
float b;
char c;
};

Sample program 1

The following program shows the usage of union of structure.

union sample{
int a;
float b;
char c;
}
main ( ){
union sample s = {10, 20.5, "A"};
printf("a=%d",s.a);
printf("b=%f",s.b);
printf("c=%c",s.c);
}

Output

When the above program is executed, it produces the following result −

a = garbage value
b = garbage value
c=A

Union of structures
 A structure can be nested inside a union, and it is called union of structures.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

 It is possible to create a union inside a structure.

Aim: Implementation of C program to tag the data using union within structure.
Source Code Screenshots:
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
// Union for the tag field in the structure
union Tag {
float purchaseCost;
char donorName[50];
};
// Structure for book record
struct Book {
int accessionNumber;
char title[100];
char edition[20];
char author[50];
union Tag tag;
};
// Function to display list of purchased books
void displayPurchasedBooks(struct Book library[], int n) {
printf("\nList of Purchased Books:\n");
printf("%-15s%-30s%-20s%-20s%-20s\n", "Accession No.", "Title", "Edition", "Author",
"Purchase Cost");
printf("------------------------------------------------------------------------\n");
for (int i = 0; i< n; i++) {
if (library[i].tag.purchaseCost> 0) {
printf("%-15d%-30s%-20s%-20s$%-19.2f\n", library[i].accessionNumber, library[i].title,
library[i].edition, library[i].author, library[i].tag.purchaseCost);
}
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
}
}
// Function to display list of donated books
void displayDonatedBooks(struct Book library[], int n) {
printf("\nList of Donated Books:\n");
printf("%-15s%-30s%-20s%-20s%-20s\n", "Accession No.", "Title", "Edition", "Author", "Donor
Name");
printf("------------------------------------------------------------------------\n");
for (int i = 0; i< n; i++) {
if (strlen(library[i].tag.donorName) > 0) {
printf("%-15d%-30s%-20s%-20s%-20s\n", library[i].accessionNumber, library[i].title,
library[i].edition, library[i].author, library[i].tag.donorName);
}
}
}
int main() {
struct Book library[MAX_BOOKS];
int n;
// Input the number of books
printf("Enter the number of books in the library: ");
scanf("%d", &n);
// Input book details
for (int i = 0; i< n; i++) {
printf("\nEnter details for Book %d:\n", i + 1);
printf("Accession Number: ");
scanf("%d", &library[i].accessionNumber);
printf("Title: ");
scanf(" %[^\n]s", library[i].title);
printf("Edition: ");
scanf(" %[^\n]s", library[i].edition);
printf("Author: ");
scanf(" %[^\n]s", library[i].author);
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
// Choose whether the book is purchased or donated
printf("Is it a purchased book or a donated book? (Enter 'P' for purchased, 'D' for donated): ");
char choice;
scanf(" %c", &choice);
if (choice == 'P' || choice == 'p') {
printf("Enter Purchase Cost: $");
scanf("%f", &library[i].tag.purchaseCost);
} else if (choice == 'D' || choice == 'd') {
printf("Enter Donor Name: ");
scanf(" %[^\n]s", library[i].tag.donorName);
} else {
printf("Invalid choice. Defaulting to purchased book.\n");
printf("Enter Purchase Cost: $");
scanf("%f", &library[i].tag.purchaseCost);
}
}
// Display lists of purchased and donated books
displayPurchasedBooks(library, n);
displayDonatedBooks(library, n);
return 0;
}

Result Screenshots:
Enter the number of books in the library: 2
Enter details for Book 1:
Accession Number: 111
Title: ss
Edition: 1
Author: sdp
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:
Is it a purchased book or a donated book? (Enter 'P' for purchased, 'D' for donated): p
Enter Purchase Cost: $100

Enter details for Book 2:


Accession Number: 121
Title: sp
Edition: 1
Author: guruji
Is it a purchased book or a donated book? (Enter 'P' for purchased, 'D' for donated): d
Enter Donor Name: sagar

List of Purchased Books:


Accession No. Title Edition Author Purchase Cost
------------------------------------------------------------------------
111 ss 1 sdp $100.00
121 sp 1 guruji $266763739829431697408.00

List of Donated Books:


Accession No. Title Edition Author Donor Name
------------------------------------------------------------------------
121 sp 1 guruji sagar

Conclusion:
We understood the concept of union within structure for tagging the record of the books.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology

Academic Year:2023-2024 Sem: II


Course: Advanced C Programming Laboratory Course code: CSE102
Name: Roll No:

Questions:

1. Explain the concept of union with sample C program.


2. What is the significance of Array of Structures. Elaborate your answer with an example.
3. Explain the concept of union within structure in C with sample C code.
4. Explain Advantages and Disadvantages of using union.
5. Explain the difference between structure and union in C.

You might also like