Lab Manual Adv C Programming
Lab Manual Adv C Programming
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.
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
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
{
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 :
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
Title: Write a program in C to compare two strings without using string library functions. Justify
whether it is palindrome or not.
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
Algorithm:
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
Run 2:
------------
Enter String:
step on no pets ↲
PALINDROME
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology
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
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
Algorithm :
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
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:
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
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.
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
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
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.).
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
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
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
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};
Visual Representation:
Algorithm:
1. START
2. INITIALIZE arr[] = {1, 2, 3, 4, 5}.
3. length= sizeof(arr)/sizeof(arr[0])
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
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
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
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
/**
* 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
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:
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
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
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
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
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.
For that, we can define an array whose data type will be struct Employee soo that will be easily
manageable.
......
......
};
};
GNU C compilers supports designated initialization for structures so we can also use this in the
initialization of an 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
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
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.
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
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
union uniontag{
datatype member 1;
datatype member 2;
----
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology
----
datatype member n;
};
Example
union sample{
int a;
float b;
char c;
};
Sample program 1
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
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
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
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
Conclusion:
We understood the concept of union within structure for tagging the record of the books.
PIMPRI CHINCHWAD UNIVERSITY
School of Engineering and Technology
Questions: