0% found this document useful (0 votes)
104 views54 pages

c labbook

Uploaded by

Sid1
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)
104 views54 pages

c labbook

Uploaded by

Sid1
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/ 54

Savitribai Phule Pune University

F. Y. B. Sc. (Computer Science)


(2019 Pattern)
Semester-II
Work Book
For

CS-123 Lab Course – I & II

Name_______________________________________________________________________

College_____________________________________________________________________
____________________________

Roll No._____________________________ Division________________________

Academic Year________________

1
2
Introduction
1. About the workbook

This workbook is intended to be used by F.Y.B.Sc (Computer Science) students for the Computer Science
laboratory courses in their curriculum. In Computer Science, hands-on laboratory experience is critical to
the understanding of theoretical concepts studied in the theory courses. This workbook provides the
requisite background material as well as numerous computing problems covering all difficulty levels.

The objectives of this book are


1) Defining clearly the scope of the course
2) Bringing uniformity in the way the course is conducted across different colleges
3) Continuous assessment of the course
4) Bring in variation and variety in the experiments carried out by different students in a batch
5) Providing ready reference for students while working in the lab
6) Catering to the need of slow paced as well as fast paced learners

2. How to use this workbook


This workbook is mandatory for the completion of the laboratory course. It is a measure of the performance
of the student in the laboratory for the entire duration of the course.

2.1 Instructions to the students


Please read the following instructions carefully and follow them
1) You are expected to carry this book every time you come to the lab for computer science practicals.
2) Students should prepare oneself beforehand for the Assignment by reading the relevant material.
3) Instructor will specify which problems to solve in the lab during the allotted slot and student should
complete them and get verified by the instructor. However student should spend additional hours in Lab
and at home to cover as many problems as possible given in this book.
4) You will be assessed for each exercise on a scale of5
i) Not done 0 ii) Incomplete
1 iii) Late Complete 2 iv) Needs
improvement 3 v) Complete
4 vi) Well Done 5

2.2 Instructions to the Instructors

1) Explain the assignments and related concepts in around ten minutes using whiteboard if required or by
demonstrating the software.
2) Fill in the blanks with different values for each student.
3) Choose appropriate problems to be solved by student by ticking
Hint :For ‘C’ Language make Set A compulsory, minimum two from Set B and minimum one from
Set C.
For RDBMS: Solve any 3 Sets out of Set A, B, C, D, E 4) Make sure that
students follow the instruction as given above.
5) After a student completes an assignment, the instructor has to verify the outputs and sign in the provided
space after the activity.

3
6) Youshouldevaluateeachassignmentcarriedoutbyastudentonascaleof5asspecifiedabove by ticking
appropriate box.
7) The value should also be entered on assignment completion page of the respective Lab course.

2.3 Instructions to the Lab administrator

You have to ensure appropriate hardware and software is made available to each student. The operating
system and software requirements on server side and also client side are as given below
1) Server Side and client side
a. Operating System
• Linux
b. Software’s to be installed
• C
• PostgreSQL

2) Editors : Any linux based editor like vi, gedit etc.


___________________________________________________________________________

Prepared by:

Ms. Dipita Dhande H.P.T.Arts and R.Y.K. Science College, Nashik


Ms. Varsha Joshi H.P.T. Arts and R.Y.K. Science College, Nashik.
Ms. Chitra Alavani Kaveri College of Arts, Science and Commerce, Pune
Ms. Akhila Kalmad Kaveri College of Arts, Science and Commerce, Pune
Mr. Kudale Gautam V. P. Arts Science and Commerce College, Baramati
Ms. Kadam T.T V. P. Arts Science and Commerce College, Baramati
Mr. Ahire U.B V. P. Arts Science and Commerce College, Baramati

Editors:
Dr. Manisha Bharambe MES Abasaheb Garware College, Pune Dr. Poonam Ponde
Nowrosjee Wadia College, Pune

4
Assignment Completion Sheet

Section I : Advanced ‘C’

Sr. Assignment Name Marks Signature


No (out of 5)
1. Use of Simple Pointers
2. Dynamic Memory Allocation
3. String Handling Using Standard Library Functions.
4. String Handling Using User defined Functions.
5. Structure and Unions.
6. File Handling (Text Files).
7. Command Line Arguments and Pre-processor Directives.

Total Marks ( out of 60 )

Total Marks (out of 15)

This is to certify that Mr / Ms _______________________________________________ having


Seat Number: _____________ has successfully completed the Laboratory course work on
Advanced ‘C’ Programming and Relational Database Management Systems.

Instructor Head

Internal Examiner External Examiner

5
6
Lab Course
Section I
Advanced ‘C’ Programming

7
8
Assignment1: Simple Pointers in C.

A Pointer is a variable that stores the memory address of another variable

Action syntax Example


Involving Pointers
Declaration of data_type * pointer_name int *p1,*p2; float
pointers *temp1;
Initialization of pointer =&variable p1=&n; int a, *p= &a;
pointers
Pointer Arithmetic The C language allow arithmetic an integer pointer
operations to be performed on increments by sizeof(int).
pointers: Increment, Decrement,
Addition, Subtraction
When a pointer is incremented (or
decremented) by 1, it increments by
sizeof(datatype).

Pointers and We can pass the address of a


Functions variable to a function. The function
can accept this address in a pointer
and use the pointer to access the
variable’s value.

Arrays And Pointers An array name is a pointer to the int n[10];


first element in the array. It holds *n , *(n + 0 ) represents
the base address of the array. 0th element
Every array expression is
converted to pointer n[ j ], *(n+ j ),* (j + n) ,
For eg: a) a[i] is same as*(a+i) j[n]: represent the value
b) a[i][j] is same as *(*a+i)+j)
of the jth element of array n
c) &a[i] is same as a+i
d) &a[i][j] is same as a[i]+j

Sample Program 1)
The following program illustrate how to handle integer values using pointers main()
{
int a=10, b=20;
int *pa, *pb;
pa=&a;
pb=&b; *pb=*pa+5;
printf(“a=%d\tb=%d\n”,a,b);
printf(“*pa=%d \t *pb=%d\n”,*pa,*pb);
}

9
Sample Program 2)
The following program illustrate call by value and call by reference methods of passing the values.
main()
{
int a = 10, b = 20;
void swap1( int x, int y);
void swap2( int *ptr1, int *ptr2);

printf(“\nBefore swapping : a=%d, b=%d”, a,b);


swap1(a, b);
printf(“\nAfter swapping by swap1 : a=%d, b=%d”, a,b); swap2(&a,
&b);
printf(“\nAfter swapping by swap2 : a=%d, b=%d”, a,b);
}
void swap1( int x, int y)
{
int temp;
temp = x; x =y;y = temp;
}
void swap2( int *ptr1, int *ptr2)
{
int temp;
temp =*ptr1;*ptr1 =*ptr2;*ptr2 =temp;
}

Sample Program 3)
The following program illustrate displaying array using pointers
main()
{
int a[]={10, 5, 18, 30, 25};
for(i=0; i<5;i++)
printf(”%d\t”,*(a+i));
}

Sample Program 4)
The following program illustrate displaying matrix using pointers main()
{
int a[2][2]={{10, 5}, {18, 25}};
for(i=0; i<2;i++)
{
for(j=0; j<2; j++)
printf(“%d\n”, *(*(a+i)+j));
}
}

10
Set A: Write C programs for the following problems.
1. Write a program to read two integers using pointers and perform all arithmetic operations on them.
2. Write a program to accept an integer using pointer and check whether it is even or odd.
3. Write a program to find maximum from two integers using pointers.
4. Write a program to display the elements of an array containing n integers in the reverse order using a
pointer to the array.

Set B. Write C programs for the following problems.


1. Write a program N integers in an array using pointers and display minimum from them.
2. Write a function that takes radius of as parameter and two variables. Set first variable to
area of circle and second to perimeter of circle. Accept radius in main and also display
area and perimeter in main using the above function
(Hint: Pass the addresses of the variables to the function to get area and perimeter)
3. Write a function which takes distance in kilometer, centimeter and millimeter as
Parameters as an integer d and increments the distance by d millimeters. Accept distance
and d in main and Display the new distance in main using the above function.
4. Accept n integers in array A in main. Write a function which takes this array as
parameter and find minimum and maximum from it. Display these values in main.

Set C. Write programs to solve the following problems


1. Accept date (dd, mm yy). Write a function to add no of days to the date and display the new date. Pass dd,
mm and yy to the function using pointers.
2. Write a function which accepts a number and three flags as parameters. If the number is even,
Set the first flag to 1. If the number is prime,set the second flag to 1.If the number is divisible by3 or 7, set
the third flag to 1. In main, accept an integer and use this function to check if it is even, prime and divisible
by 3 or 7. (Hint : pass the addresses of flags to the function)

11
Set A. Write C programs for the following problems.

1. Write a program to read two integers using pointers and perform all arithmetic operations on them.
➢ #include <stdio.h>
int main()
{
int n1, n2;
int sum,difference,product,remainder;
float quotient;
int *ptr1, *ptr2;
clrscr();
printf("Enter two integer numbers: ");
scanf("%d %d", &n1, &n2);
ptr1 = &n1;
ptr2 = &n2;
sum = *ptr1 + *ptr2;
difference = *ptr1 - *ptr2;
product = *ptr1 * *ptr2;
quotient = (float)(*ptr1) / *ptr2;
remainder = *ptr1 % *ptr2;
printf("\nSum: %d", sum);
printf("\nDifference: %d", difference);
printf("\nProduct: %d", product);
printf(“\nQuotient: %.2f”,quotient);
printf("Remainder: %d", remainder);
return;
}

2. Write a program to accept an integer using pointer and check whether it is even or odd.
➢ #include <stdio.h>
int main()
{
int number;
int *ptr;
clrscr();
printf("Enter an integer: ");
scanf("%d", &number);
ptr = &number;
12
if (*ptr % 2 == 0)
{
printf("%d is even.\n", *ptr);
}
else
{
printf("%d is odd.\n", *ptr);
}
return;
}

3. Write a program to find maximum from two integers using pointers.


➢ #include <stdio.h>
int main()
{
int n1, n2;
int *ptr1, *ptr2;
clrscr();
printf("Enter two integer numbers: ");
scanf("%d %d", &num1, &num2);
ptr1 = &num1;
ptr2 = &num2;
if (*ptr1 > *ptr2)
{
printf("The largest number is %d\n", *ptr1);
}
else if (*ptr2 > *ptr1)
{
printf("The largest number is %d\n", *ptr2);
}
else
{
printf("Both numbers are equal\n");
}
return 0;
}

13
4. Write a program to display the elements of an array containing n integers in the reverse order using a
pointer to the array.
➢ #include <stdio.h>
#define N 5
int main()
{
int a[N], i, *ptr;
clrscr();
printf("Enter %d integer numbers:\n", N);
for (i = 0; i < N; i++)
scanf("%d", &a[i]);
ptr = &a[N - 1];
printf("\nElements of the array in reverse order:\n");
for (i = 0; i < N; i++)
printf("%d\n", *ptr--);
return 0;
}

14
Set B. Write C programs for the following problems.
1. Write a program to read N integers in an array using pointers and display minimum from them.
➢ #include <stdio.h>
#define max_size 100
int main()
{
int arr[max_size];
int N, i,min;
int *ptr = arr;
clrscr();
printf("Enter the size of the array: ");
scanf("%d", &N);
printf("Enter %d integers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &ptr[i]);
}
int min = *ptr;
for (i = 1; i < N; i++) {
if (*(ptr + i) < min) {
min = *(ptr + i);
}
}
printf("Minimum value in the array: %d\n", min);
return;
}

2. Accept n integers in array A in main. Write a function which takes this array as
parameter and find minimum and maximum from it. Display these values in main.
➢ #include <stdio.h>
#include <conio.h>
void findMinMax(int A[], int n, int *min, int *max);
int main()
{
int A[100], n, min, max;
printf("Enter the number of integers: ");
scanf("%d", &n);
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++)
15
{
scanf("%d", &A[i]);
}
findMinMax(A, n, &min, &max);
printf("Minimum value: %d\n", min);
printf("Maximum value: %d\n", max);
getch();
return 0;
}
void findMinMax(int A[], int n, int *min, int *max)
{
*min = A[0];
*max = A[0];
for (int i = 1; i < n; i++)
{
if (A[i] < *min)
{
*min = A[i];
}
if (A[i] > *max)
{
*max = A[i];
}
}
getch();

16
Assignment 2:Dynamicmemory allocation in C.

Actions involving syntax Example


Pointers
Pointer To Pointer datatype **pointer_to_pointer; int a; int * p; int **q; p
= &a; q = *p ;
Pointer to array datatype (*var_name)[size] int (*p)[5];

Array of Pointers Datatype *array_name[size]; int *p[5];

To allocate memory The functions used are : malloc, int * p,*p1;


Dynamically calloc, realloc p = (int *) malloc(10 *
sizeof(int));
a. ptr = ( cast-type * ) malloc ( p1 = (int *) calloc(10,
byte-size) ; sizeof(int));
Allocates a block of contiguous p1=realloc(p1,20*
bytes. If the space in heap is not sizeof(int));
sufficient to satisfy request,
allocation fails, returns NULL.

b. ptr1 = ( cast-type * )calloc( byte-


size);
Similar to malloc, but initializes
the memory block allocated to
0.
c. ptr = realloc( ptr, new size );To
increase / decrease memory size.

Sample program 1)
The following program illustrate how to accept N integers and store them dynamically and access them.
main()
{
int *p, n,i;
printf(“How many elements :”);
scanf(“%d”,&n);
p = (int *)malloc(n*sizeof(int));
/* Accepting data */
for(i=0; i<n;i++)
scanf(”%d”,p+i);
/*Displaying data*/
for(i=0; i<n;i++)
printf(”%d\t”,*(p+i));
}

Sample program 2)
17
#include<stdio.h>
#include<stdlib.h> main() {
int *a[10],r,c,i,j;
printf("Enter the order of matrix\n");
scanf("%d%d",&r,&c); printf("Enter matrix
elements\n");
for(i=0;i<r;i++)
{
/**** dynamically allocate memory for every row ****/
a[i]=(int *)malloc(c*sizeof(int)); for(j=0;j<c;j++)
{
scanf("%d",a[i]+j);
}
}
/****** Display Matrix ******/
printf("The matrix is as below\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
}

Set A. Write C programs for the following problems.


1. Type the above sample program 1 and execute it.
2. Type the above sample program 2 and execute it.
3. Write a program to accept N integers and store them dynamically display them in reverse order.
4. Write a program to allocate memory dynamically for n integers such that the memory is initializedto0. And
display it.

Set B. Write C programs for the following problems.


1. Accept N integers in an array using dynamic memory allocation. Find maximum from them and display.
2. Accept n integers in an array. Copy only the non-zero elements to another array (allocated using dynamic
memory allocation). Calculate the sum and average of non zero elements.
3. Accept a matrix of order mXn (Use dynamic memory allocation and array of pointers concept). Display
trace of the matrix.
4. Accept a matrix of order mXn (Use dynamic memory allocation and array of pointers concept). Display
Column wise sum of elements.

Set C. Write programs to solve the following problems


1. There are 5 students numbered 1 to 5. Each student appears for different number of subjects in an exam.
Accept the number of subjects for each student and then accept the marks for each
subject. For each student,calculate the percentage and display.
18
(Hint:Use array of 5 pointers and use dynamic memory allocation)
2. Accept a matrix of order m X n using dynamic memory allocation. Construct new matrix of order m X
(n+1)(Use realloc function)such that (n+1)th column contains the sum of all elements of the corresponding
row. And display new matrix.
Example:

19
Set A. Write C programs for the following problems.

1. Type the above sample program 1 and execute it.


➢ #include<stdio.h>
#include<stdlib.h>
void main()
{
int *p, n,i;
clrscr();
printf(“How many elements:”);
scanf(“%d”,&n);
p = (int *)malloc(n*sizeof(in));
for(i=0; i<n;i++)
scanf(”%d”,p+i);
for(i=0; i<n;i++)
printf(”%d\t”,*(p+i));
getch();
}

2. Type the above sample program 2 and execute it.


➢ #include<stdio.h#include<st
dlib.
void main()
{
int *a[10],r,c,i,j;
clrscr();
printf("Enter the order matrix\n");
scanf("%d%d",&r,&c);
printf("Enter matrix elements\n");
for(i=0;i<r;i++)
{
a[i]=(int *)malloc(c*sizeof(int));
for(j=0;j<c;j++)
{
scanf("%d",a[i]+j);
}

20
}
printf("The matrix is as below\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
}

3. Write a program to accept N integers and store them dynamically display them in reverse order.
➢ #include <stdio.h>
#include <stdlib.h>
void main() {
int n, i;
int *arr;
clrscr();
printf("Enter the number of integers (n): ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
printf("Enter %d integers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Integers in reverse order:\n");
21
for (i = n - 1; i >= 0; i--) {
printf("%d\n", arr[i]);
}
free(arr);
getch();
}

4. Write a program to allocate memory dynamically for n integers such that the memory is initialized to 0. And
display it.
➢ #include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int *arr;
int n;
printf("Enter the number of integers: ");
scanf("%d", &n);
arr = (int *)calloc(n, sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.");
return 1;
}
printf("Initialized memory:\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
getch();
return 0;
}

22
Set B. Write C program for the following problems.

1. Accept N integers in an array using dynamic memory allocation. Find maximum from them and display.
➢ #include <stdio.h>
#include <stdlib.h>
void main()
{
int N, i,max;
int *arr;
clrscr();
printf("Enter the number of integers (N): ");
scanf("%d", &N);
arr = (int *)malloc(N * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
printf("Enter %d integers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
int max = arr[0];
for (i = 1; i < N; i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
printf("Maximum value in the array: %d\n", max);
free(arr);
getch();
}

23
2. Accept n integers in an array. Copy only the non-zero elements to another array (allocated using dynamic
memory allocation). Calculate the sum and average of non zero elements.
➢ #include <stdio.h>
#include <stdlib.h>
int main() {
int N, i, j, count = 0;
int *arr, *nonzeroarr;
double sum = 0.0, average;
clrscr();
printf("Enter the number of integers (N): ");
scanf("%d", &N);
arr = (int *)malloc(N * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed. Exiting...\n");
return 1;
}
printf("Enter %d integers:\n", N);
for (i = 0; i < N; i++) {
scanf("%d", &arr[i]);
if (arr[i] != 0) {
count++;
sum += arr[i];
}
}
nonzeroarr = (int *)malloc(count * sizeof(int));
if (nonzeroarr == NULL) {
printf("Memory allocation failed. Exiting...\n");
free(arr);
return 1;
}
j = 0;
for (i = 0; i < N; i++) {
if (arr[i] != 0) {
nonzeroarr[j] = arr[i];
j++;
}
}
if (count > 0) {
average = sum / count;
printf("Sum of non-zero elements: %.2lf\n", sum);
24
printf("Average of non-zero elements: %.2lf\n", average);
} else {
printf("No non-zero elements found.\n");
}
free(arr);
free(nonzeroarr);
return;
}

25
26
Assignment 3: String handling in C and standard library functions for strings

A string is an array of characters terminated by a special character called NULL character(\0). Each character
is stored in 1 byte as its ASCII code.
An array of strings is a two dimensional array of characters. It can be treated as a 1-D array such that each
array element is a string.
Actions Explanation Example
Involving
strings
Declaring char string_name[size]; char str[80];
Strings
Initializing char str[]= { ’G’, ’o ’, ’o’,
Strings d’,’\0’ };
char str [ ] = “Hello”;
Accepting scanf and gets can be used to accept strings char name[20], address[50];
Strings printf(“\n Enter your
name”);
scanf(“%s”,name);
printf(“\n Enter your
address”); gets(address);

Displaying printf and puts can be used to display strings. Printf(“\n The name is %s:”,
Strings name);
printf(“\n The address is :”);
puts(address);
Declaring char array[size1][size2]; char cities[4][10]
String array

Initializing char cities[4][10] = { “Pune”,


String array “Mumbai”,
“Delhi”, “Chennai”} ;

All string operations are performed using functions in “string.h”. Some of the most commonly used functions
are
a. strlen(str) – Returns the number of characters in the string (excluding \0)
b. strcpy(deststr, srcstr) – Copies one string to another
c. strcmp(str1,str2) – Compares two strings. Returns 0 (equal), +ve (first string > second), -ve (first string
<second ). It is case sensitive.
d. strcmpi(str1,str2) – Same as strcmp but ignores case
e. strcat(str1,str2) – Concatenates the second string to the first. Returns the concatenated string.
f. strchr(str1, ch) – truncate the string before first occurrence of character in the string.
g. strrchr(str1,ch) –truncate the string before last occurrence of character in the string.

Sample program 1)
#include <string.h>
27
main( )
{
char str1[30],str2[30],str3[60];
printf(“\nEnter the first string:”); gets(str1);
printf(“\n Enter the second string string:”);
gets(str2);
if (strlen(str1) == strlen(str2))
{
strcpy(str3,strrev(str1));
strcat(str3,str2);
puts(str3);
}
else
{
strcat(str1,str2);
puts(str1);
}
}

Sample Program 2)
#include <stdio.h> main( )
{
charlist[10][20]; /*list is an array of 10 strings*/
charname[20];
int i,n;
printf(“\n How many names ?:”);
scanf(“%d”, &n);
/* Accepting n names */
for (i=0;i<n; i++)
{
printf(“\n Enter name %d,”i);
gets(list[i]);
}

printf(“\n Enter the name to be searched “); gets(name);


for (i=0; i<n; i++)
{
if(strcmp(list[i],name)==0)
break;
}
if(i==n)
printf(“\nName is in list”);
else
printf(“\nName is not in list”);
}

28
Set A. Write C programs for the following problems.
1. Write a program to read a string and copy it to another sting and display copied string. Also the length of
copied string. (Use built in functions)
2. Write a program to read two strings. If first string is greater than second then concatenate second to first
and display concatenated string, If first string is smaller than second then concatenate first to second, other-
wise display length of string. (use strcmp)
3. Write a program to read a string and one character. Check whether given character is present in the given
string or not? (Hint: use strchr or strrchr)

Set B. Write C programs for the following problems.


1. Write a program which accepts a sentence from the user and alters it as follows: Every space is replaced
by *, case of all alphabets is reversed, digits are replaced by ?.
2. Write a program which accepts a sentence from the user. Find and display reverse of it.
(Don’t use any function).
3. Write a program that accepts n words and outputs them in dictionary order.
4. Define two constant arrays of strings, one containing country names (ex: India, France etc) and
the other containg their capitals. (ex:Delhi,Parisetic). Note that country names and capital names have a
one-one correspondence. Accept a country name from the user and display its capital. Example: Input:
India, Output: Delhi.

Set C. Write programs to solve the following problems


1. Write a program that accepts a string and displays it in the shape of a kite. Example:
“abc” will be displayed as:
aa abab abcabc
abab
aa
2. Write a program that accepts a string and generates all its permutations. For example: ABC, ACB, BAC,
BCA, CAB,CBA
3. Write a menu driven program to perform the following operations on strings using standard library
functions:
1.Length 2. Copy 3.Concatenation 4. Compare

29
Set A. Write C programs for the following problems.
1. Write a program to read a string and copy it to another sting and display copied string. Also the length of
copied string. (Use built in functions)
➢ #include <stdio.h>
#include <string.h>
int main() {
char source[100];
char destination[100
int length;
printf("Enter a string: ");
gets(source);
strcpy(destination, source);
length = strlen(destination);
printf("Copied string: %s\n", destination);
printf("Length of copied string: %d\n", length);
return 0;
}

2. Write a program to read two strings. If first string is greater than second then concatenate second to first
and display concatenated string, If first string is smaller than second then concatenate first to second, other-
wise display length of string. (use strcmp)
➢ #include <stdio.h>
#include <string.h>
int main() {
char str1[100];
char str2[100];
int compareresult;
printf("Enter the first string: ");
gets(str1);
printf("Enter the second string: ");
gets(str2);
compareresult = strcmp(str1, str2);
if (str1<str2)
{
30
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
}
else if (str1>str2)
{
strcat(str2, str1);
printf("Concatenated string: %s\n", str2);
}
else
{
printf("Length of the string: %d\n", strlen(str1));
}
return 0;
}

3. Write a program to read a string and one character. Check whether given character is present in the given
string or not? (Hint: use strchr or strrchr)
➢ #include <stdio.h>
#include <string.h>
int main() {
char str[100];
char ch;
char *result;
printf("Enter a string: ");
gets(str);
printf("Enter a character to search for: ");
scanf(" %c", &ch);
result = strchr(str, ch);
if (result) {

31
printf("Character '%c' is present in the string.\n", ch);
printf("First occurrence found at index: %d\n", result - str);
}
else {
printf("Character '%c' is not present in the string.\n", ch);
}
return 0;
}

32
Set B. Write C programs for the following problems.
1. Write a program which accepts a sentence from the user. Find and display reverse of it.
(Don’t use any function).
➢ #include <stdio.h>
#include <conio.h>
int main() {
char sentence[100];
int length = 0, i;
printf("Enter a sentence: ");
gets(sentence);
while (sentence[length] != '\0') {
length++;
}
printf("Reverse of the sentence: ");
for (i = length - 1; i >= 0; i--) {
printf("%c", sentence[i]);
}

getch();
return 0;
}

2. Write a program that accepts n words and outputs them in dictionary order.
➢ #include<stdio.h>
#include<string.h>
#define size 100
void order(int n);
void main()
{
int n;
printf("\n How many words/names do you want to sort:- ");
scanf("%d",&n);
printf("\n");
order(n);
printf("\n");
}
void order(int n)
{
char list[5][20],temp[20];
int i,j;
33
for(i=0;i<n;i++)
scanf("%s",list[i]);
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(strcmp(list[i],list[j])>0)
{
strcpy(temp,list[i]);
strcpy(list[i],list[j]);
strcpy(list[j],temp);
}
}
printf("\n Words/Names in sorted alphabetical order:- ");
for(i=0;i<n;++i)
printf("\n %s",list[i]);
}

34
Assignment 4: String handling using user defined function and pointers.

Sample program 1)
The following program illustrate user defined function for converting string to lower case without
using pointers
#include<stdio.h>
void string_lower(char t[20], char s[20])
{
int i=0;
while(s[i] != ’\0’)
{
if (‘A’ <= s[i] && s[i] <=’Z’)
t[i]=s[i]-32;
else
t[i]=s[i];
}
t[i]=’\0’; /* terminate target string */
}
main()
{
char str1[30],str2[30];
printf(“Enter string: ”);
gets(str1);
string_lower(str2,str1);
printf(“Converted string is : %s\n”,str2);
}

Sample program 2)
The following program illustrate function for string copy using pointers
#include<stdio.h>
void string_copy(char *t, char *s)
{
while(*s != ’\0’)
{
*t=*s;
s++; t++;
}
*t=’\0’; /* terminate target string */
}
main()
{ char str1[30],str2[30];
printf(“Enter string: ”);
string_copy(str2,str1);
gets(str1);

35
printf(“Copied string is : %s\n”,str2);
}

Set A . Write C programs for the following problems.


1. Write a program to accept a string and find its length using user defined function.
(Don’t use pointers)
2. Write a function that takes a string as parameterand returns the same string in upper case(use pointes).
Accept this string in main and display converted string in main only.
3. Write a function to find reverse of the string and use it in main.

Set B. Write C programs for the following problems.


1. Write a function to compare two strings. Write another function to reverse the string.
In main function a string and check whether it is palindrome or not using above functions. (Hint: A
palindrome string is a string which reads same in forward as well as backward direction for example:
madam, nitin, etc.)
2. Write a program that will accept a string and character to search. The program will call a function, which
will search for the occurrence of the character in the string and return its position. Function should return
–1 if the character is not found in thestring. Display this position in main() function.
3. Write a program that will accept a string and character to search. The program will call a function, which
will find occurrence of given character in the string. Display this count in main() function.

Set C. Write programs to solve the following problems


1. Write a Menu driven program to perform following operations on strings till user selects exit.
1. Copy 2. Concatenate 3. Length 4. Reverse
2. Write a function to find occurrence of every character in the string. Use it in main.
For. example if input string is “This is Monitor” then output should be
Character t occurs 2 times
Character h occurs 1 times
Character i occurs 3 times
Character s occurs 2 times
Character m occurs 1 times
Character o occurs 2 times
Character n occurs 1 times
Character r occurs 1 times

36
3. Write a function, which displays a given number in words. Use it in main() function.
For Example: 129 One Hundred Twenty Nine
2019 Two Thousand Nineteen

37
Set A. Write C programs for the following problems.
1. Write a program to accept a string and find its length using user defined function.
(Don’t use pointers)
➢ #include <stdio.h>
int find(char input[]);
int main()
{
char str[100];
int len,length;
clrscr();
printf("Enter a string: ");
scanf("%s", str);
len = find(str);
printf("Length of the string: %d\n", len);
return 0;
}
int find(char input[])
{
int length=0;
while (input[length] != '\0')
{
length++;
}
return length;
}

2. Write a function that takes a string as parameter and returns the same string in upper case(use pointers).
Accept this string in main and display converted string in main only.
➢ #include <stdio.h>
#include <ctype.h>
void convert(char *str);
int main()
{
char input[100];
clrscr();
38
printf("Enter a string: ");
scanf("%s", input);
convert (input);
printf("Converted string: %s\n", input);
return 0;
}
void convert(char *str);
{
while (*str != '\0') {
*str = toupper(*str);
str++;
}
getch();
}

3. Write a function to find reverse of the string and use it in main.


➢ #include <stdio.h>
#include <conio.h>
#include <string.h>
void reverseString(char *str);
int main()
{
char str[100];
clrscr();
printf("Enter a string: ");
gets(str);
reverseString(str);
printf("Reverse of the string: %s\n", str);
getch();
return 0;
}
void reverseString(char *str)
{
int length = strlen(str);
int i, j;
char temp;

for (i = 0, j = length - 1; i < j; i++, j--)


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

Set B. Write C programs for the following problems.


1. Write a function to compare two strings. Write another function to reverse the string.
In main function a string and check whether it is palindrome or not using above functions. (Hint: A
palindrome string is a string which reads same in forward as well as backward direction for example:
madam, nitin, etc.)
➢ #include <stdio.h>
#include <conio.h>
#include <string.h>
int compareStrings(char *str1, char *str2);
void reverseString(char *str);
int main() {
char str[100];
char reverseStr[100];
clrscr();
printf("Enter a string: ");
gets(str);
strcpy(reverseStr, str);
reverseString(reverseStr);
if (compareStrings(str, reverseStr) == 0) {
printf("The string \"%s\" is a palindrome.\n", str);
} else {
printf("The string \"%s\" is not a palindrome.\n", str);
}
getch();
return 0;
}
void reverseString(char *str) {
int length = strlen(str);
int i, j;
char temp;
40
for (i = 0, j = length - 1; i < j; i++, j--) {
// Swap characters at positions i and j
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int compareStrings(char *str1, char *str2) {
return strcmp(str1, str2);
}

41
42
Assignment 5: Structures and union in C

Structure: A structure is a composition of variables possibly of different data types, grouped together under a
single name. Each variable within the structure is called a ‘member’.

Nested structures: The individual members of a structure can be other structures as well. This is called nesting
of structures.

Union : A union is a variable that contains multiple members of possibly different data types grouped together
under a single name. However, only one of the members can be used at a time. They occupy the same memory
area.
Operations performed Syntax / Description Example

Declaring a structure struct structure-name struct student


{ {
type member-1 ; type char name[20];
member-2; int roll no; int
….. type marks;
member-n ; };
};
Creating structure struct structure_name variable; struct student stud1;
variables
Accessing structure variable.member stud1.name stud1.rollno
members stud1.marks

initializing a structurethe initialization values have to be struct student stud1 =


variable given in {} and in order {“ABCD”,10,95};
Pointer to a structure struct structure-name *pointer- struct student *ptr; ptr
name; = &stud1;
Accessing members pointer-name-> member-name; ptr->name; ptr->rollno;
using Pointer
Array of structures struct structure-name array- struct student stud[10];
name[size];
passing Structures to return-type function-name (struct void display(struct student s);
Functions structure-name variable);
pass an array of return-type function-name ( struct void display(struct student
structures to a function structure-name array[size]); stud[10]);
Creating a nested struct structure1 { struct student
structure Method ... {
1 struct structure2 { int rollno; char
... name[20];
} variable; struct date
... { int dd, mm,
}; yy;
} admdate;
};

43
Creating a nested struct structure2 { struct date
structure ... {
Method 2 }; int dd, mm, yy;
};
struct structure1 {
... struct student
struct structure2 {
variable; int rollno; char
... name[20]; struct date
}; admdate;
};

Accessing nested nested structure members can stud1.bdate.dd, stud1.bdate.mm


structure members be accessed using the
(.)operator repeatedly.
self-referential structure A structure containing a struct node
pointer to the same structure { int info;
struct node *next; };

Unions union union-name union u {


{ char a; int b;
type member-1 ; type };
member-2;
…..
type member-n ;
};

Sample Program 1)
The following program illustrate array of structures.
#include<stdio.h>
struct student
{
int rollno;
char name[20]:
int marks[3];
floatperc;
};
void main()
{
int i, sum j;
struct student s[10];
printf("n Enter the details of the 10 students \n");
for (i=0;i<10;i++)
{
printf("\n Enter the name and roll number \n");
scanf("%s%d",s[i].name, &s[i].rollno);
44
printf("\n Enter marks for three subjects:");
sum=0;
for (j=0;j<3:j++)
{
scanf("%d", &s[i].marks[j]);
sum = sum + s[i].marks[j];
}
s[i].perc= (float)sum/3;
}
/* Display details of students */
printf("\n\n Name it Roll not Percentage");
printf("\n=====================================\n”);
for(i=0;i<10;i++)
{
printf("\n%s\t%d\t%f",s[i].name,s[i].rollno,s[i].pere);
}
}

Sample Program 2)
The following program illustrate union.
structure is for a library book with the following details : id, title, publisher, code ( 1 – Text book, 2 – Magazine,
3 – Reference book). If the code is 1, store no-of-copies. If code = 2, store the issue month name. If code = 3,
store edition number. Also store the cost.

struct library_book
{
int id;
char title[80],publisher[20] ;
int code;
union u
{
int no_of_copies; char month[10]; int edition;
}info;
intcost;
};
void main( )
{
struct library_book book1;
printf(“\n Enter the details of the book \n”);

printf(“\n Enter the id, title and publisher \n”);


scanf(“%d%s%s”,&book1.id, book1.title, book1.publisher);
printf(“\nEnterthecode:1-TextBook,2-Magazine,3-Reference”);
scanf(“%d”,book1.code);

45
switch(book1.code)
{
casel: printf("Copies = %d:",book1.info.no_of_copies);
break;
case2: printf("Issue month name=%s", book1.info.month);
break;
case3:printf("Edition number-%d:",book1.info.edition);
break;
} printf(“\n Cost = %d”, book1.cost);
}

Set A . Write C programs for the following problems.


1. Create a structure employee (id, name, salary). Accept details of n employees and display display it in
summary format.
2. Type sample program 2 and execute it.

Set B . Write C programs for the following problems.


1. Create a structure item(item number, item name, rate, qty, total). Accept details of n items (calculate total
as qty * rate). And display Bill in the following format

Sr. No. Item Name Rate Qty Total


1 Pen 10 3 30.00
2 Eraser 5 1 05.00
Grand Total : 35.00

2. Create a structure car (car number, model name, colour, cost). Accept details of n cars and write amenu
driven program to perform the following operations. Write separate functions for the different options.
i) Search byname
ii) Displayall

3. Create a structure movie (name, release year, duration). Accept details of n movies.
Write a function to sort them according to release year. Display them in main() function.
(Hint: Use dynamic memory allocation.)

Set C. Write programs to solve the following problems

1. Create a structure Fraction (numerator, denominator). Accept details of n fractions and write a menu driven
program to perform the following operations. Write separate functions for the different options. Use
dynamic memoryallocation.
i)Display the largestfraction
ii) Display the smallestfraction
iii) Sortfractions
iv) Displayall
Note: While accepting fractions, store the fractions in the reduced form.

46
2. Modify the sample program 2 above to accept details for n books and write a menu driven program for the
following:
3. i.)Display all referencebooks
ii) Search magazine according for specification
iii)Find the total cost of all the books
(Hint : Useno)

4. Create a structure employee(id, name, joiningdate(dd, mm, yyyy)). Accept the details for n employees.
Accept month and display the details of employee having birthdate in that month. (Hint : Use
Nestedstructure)

47
Set A . Write C programs for the following problems.

1. Create a structure employee (id, name, salary). Accept details of n employees and display display it in
summary format.
#include <stdio.h>
#include <conio.h>
struct employee {
int id;
char name[50];
int salary;
};
int main() {
struct employee emp[100];
int n, i;
clrscr();
printf("Enter the number of employees: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter details for employee %d:\n", i + 1);
printf("ID: ");
scanf("%d", &emp[i].id);
printf("Name: ");
scanf("%s", emp[i].name); // Note: No spaces allowed in name
printf("Salary: ");
scanf("%d", &emp[i].salary);
}
printf("\nEmployee Summary:\n");
printf("ID\tName\t\tSalary\n");
for (i = 0; i < n; i++) {
printf("%d\t%s\t\t%d\n", emp[i].id, emp[i].name, emp[i].salary);
}
getch();
return 0;
}

48
2. Type sample program 2 and execute it.
struct library_book
{
int id;
char title[80],publisher[20] ;
int code;
union u
{
int no_of_copies; char month[10]; int edition;
}info;
int cost;
};
void main( )
{
struct library_book book1;
clrscr();
printf(“\n Enter the details of the book \n”);
printf(“\n Enter the id, title and publisher \n”);
scanf(“%d%s%s”,&book1.id, book1.title, book1.publisher);
printf(“\nEnterthecode:1-TextBook,2-Magazine,3-Reference”);
scanf(“%d”,book1.code);
switch(book1.code)
{
casel: printf("Copies = %d:",book1.info.no_of_copies);
break;
case2: printf("Issue month name=%s", book1.info.month);
break;
49
case3: printf("Edition number-%d:",book1.info.edition);
break;
}
printf(“\n Cost = %d”, book1.cost);
getch();
}

50
Set B . Write C programs for the following problems.

1. Create a structure car (car number, model name, colour, cost). Accept details of n cars and write amenu
driven program to perform the following operations. Write separate functions for the different options.
i) Search byname
ii) Displayall
➢ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#define MAX_CARS 100
#define MAX_NAME_LENGTH 50
struct car {
int carNumber;
char modelName[MAX_NAME_LENGTH];
char colour[MAX_NAME_LENGTH];
float cost;
};
void searchByName(struct car cars[], int n, char name[]);
void displayAll(struct car cars[], int n);
int main() {
struct car cars[MAX_CARS];
int n, choice;
char modelName[MAX_NAME_LENGTH];
clrscr();
printf("Enter the number of cars: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("\nEnter details for car %d:\n", i + 1);
printf("Car Number: ");
scanf("%d", &cars[i].carNumber);
printf("Model Name: ");
scanf("%s", cars[i].modelName);
printf("Colour: ");
scanf("%s", cars[i].colour);
printf("Cost: ");
scanf("%f", &cars[i].cost);
}
do {
printf("\nMenu:\n");
printf("1. Search by model name\n");
printf("2. Display all cars\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
51
switch (choice) {
case 1:
printf("Enter the model name to search: ");
scanf("%s", modelName);
searchByName(cars, n, modelName);
break;
case 2:
displayAll(cars, n);
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 3);
getch();
return 0;
}
void searchByName(struct car cars[], int n, char name[]) {
int found = 0;
for (int i = 0; i < n; i++) {
if (strcmp(cars[i].modelName, name) == 0) {
printf("Car Number: %d\n", cars[i].carNumber);
printf("Model Name: %s\n", cars[i].modelName);
printf("Colour: %s\n", cars[i].colour);
printf("Cost: %.2f\n", cars[i].cost);
found = 1;
break;
}
}
if (!found) {
printf("Car with model name '%s' not found.\n", name);
}
}
void displayAll(struct car cars[], int n) {
printf("Details of all cars:\n");
for (int i = 0; i < n; i++) {
printf("Car Number: %d\n", cars[i].carNumber);
printf("Model Name: %s\n", cars[i].modelName);
printf("Colour: %s\n", cars[i].colour);
printf("Cost: %.2f\n", cars[i].cost);
printf("\n");
}
getch();
52
}

53
2. Create a structure movie (name, release year, duration). Accept details of n movies.
Write a function to sort them according to release year. Display them in main() function.
(Hint: Use dynamic memory allocation.)

➢ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
int release_year;
int duration;
} Movie;
int compare(const void *a, const void *b) {
return (((Movie *)a)->release_year - ((Movie *)b)->release_year);
}
int main() {
int n, i;
printf("Enter the number of movies: ");
scanf("%d", &n);
Movie *movies = (Movie *)malloc(n * sizeof(Movie));
for(i = 0; i < n; i++) {
printf("Enter details for movie %d\n", i+1);
printf("Name: ");
scanf("%s", movies[i].name);
printf("Release Year: ");
scanf("%d", &movies[i].release_year);
printf("Duration: ");
scanf("%d", &movies[i].duration);
}
qsort(movies, n, sizeof(Movie), compare);
printf("\nMovies sorted by release year:\n");
for(i = 0; i < n; i++) {
printf("Name: %s, Release Year: %d, Duration: %d\n", movies[i].name,
movies[i].release_year, movies[i].duration);
}
free(movies);
getch();
}

54

You might also like