0% found this document useful (0 votes)
426 views23 pages

Advanced C Workbook For Fybcs 2020

This document provides instructions and examples for 6 programming exercises to demonstrate various concepts in the C programming language as part of a laboratory course. The exercises cover: 1) use of pointers, 2) dynamic memory allocation, 3) strings, 4) structures and unions, 5) preprocessor directives, and 6) file handling. For each exercise, the relevant concepts are explained, followed by examples of code implementing the concept.

Uploaded by

Shahnoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
426 views23 pages

Advanced C Workbook For Fybcs 2020

This document provides instructions and examples for 6 programming exercises to demonstrate various concepts in the C programming language as part of a laboratory course. The exercises cover: 1) use of pointers, 2) dynamic memory allocation, 3) strings, 4) structures and unions, 5) preprocessor directives, and 6) file handling. For each exercise, the relevant concepts are explained, followed by examples of code implementing the concept.

Uploaded by

Shahnoor
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

F. Y. B. Sc.

(Computer Science)

Laboratory Course CS-123

Practical Assignments
Exercise 1 ...................................................................................................................................
To demonstrate use of pointers
Exercise 2 ...................................................................................................................................
To demonstrate Dynamic memory allocation.
Exercise 3 ...................................................................................................................................
To demonstrate strings
Exercise 4 ...................................................................................................................................
To demonstrate structures and Unions
Exercise 5 ...................................................................................................................................
To demonstrate preprocessor directives.
Exercise 6 ...................................................................................................................................
To demonstrate file handling (text files)
Exercise 1 Start Date / /

To demonstrate use of pointers in C.

You should read the following topics before starting this exercise
What is a pointer?
How to declare and initialize pointers.
‘*’ and ‘&’ operators.
Pointer to a pointer.
Relationship between array and pointer.
Pointer to array and Array of pointers.
Dynamic memory allocation (malloc, calloc, realloc, free).

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

Actions involving syntax Example


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

Pointers and Functions We can pass the address of a


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 int n;
the first element in the array. It *n , *(n + 0 ) represents 0th
holds the base address of the element
array. Every array expression is n[ j ], *(n+ j ),* (j + n) , j [ n ] :
converted to pointer expression represent the value of the jth
as follows: a[i] is same as element of array n
*(a+i)

Pointer To Pointer int a;


int * p;
int **q;
p = &a;
1. Sample program

/* Program to swap two numbers*/


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;
}
Assignment 1.

Pointer

Set A . Write C programs for the following problems.

1. Write a function which takes hours, minutes and seconds as


parameters and an integer sand increments the time by s seconds.
Accept time and seconds in main and Display the new time in main
using the above function.

2. Write a program to display the elements of an array containing n


integers in the reverse order using a pointer to the array.

3. Write a program to allocate memory dynamically for n integers


such that the memory is initialized to 0. Accept the data from the
user and find the range of the data elements

4) Write a Program to swap two numbers by using pointer.

Set B . Write C programs for the following problems.

1. Accept n integers in array A. Pass this array and two counter


variables to a function whichwill set the first counter to the total
number of even values in the array and the other to the total
number of odd values. Display these counts in main. (Hint: Pass the
addresses of the counters tothe function)

2. Write a function which accepts a number and three flags as


parameters. If the number iseven, set the first flag to 1. If the
number is prime, set the second flag to 1. If the number isdivisible
by 3 or 7, set the third flag to 1. In main, accept an integer and use
this function to checkif it is even, prime and divisible by 3 or 7.
(Hint : pass the addresses of flags to the function)
Exercise 2 Start Date / /

To demonstrate use of Dynamic Memory Allocation in C.

Dynamic memory allocation (malloc, calloc, realloc, free).

q = *p ;
To allocate memory The functions used are : malloc, int * p,*p1;
dynamically calloc, realloc p = (int *) malloc(10 *
ptr = ( cast-type * ) malloc ( sizeof(int));
byte-size) ; p1 = (int *) calloc(10,
Allocates a block of contiguous sizeof(int));
bytes. If the space in heap is p1=realloc(p1,20*sizeof(int));
not sufficient to satisfy request,
allocation fails, returns NULL.
ptr1 = ( cast-type * ) calloc (
byte-size);
Similar to malloc, but initializes
the memory block allocated to
0.
ptr = realloc ( ptr, new size );
To increase / decrease memory
size.

1. Sample program

/* Program to allocate memory for n integers dynamically*/


#include <stdlib.h>
void 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));
}
Assignment 2.

Dynamic Memory Allocation.

1) Program to calculate the sum of 10 numbers. Declare a pointer to integer.


Allocate the memory using malloc() to it for n integers. Accept the
integers, Calculate and print the sum. Lastly release the allocated
memory.

2) Declare a pointer to character. Allocate them memory for n characters


(string) using calloc(). Accept the string and count the number of vowels
and consonants in it. Lastly free the pointer.

3) Declare a pointer to float. Allocate the memory for five float numbers.
Accept these five numbers and print them. Expand the same memory for
three more float numbers. Also accept the three numbers and calculate
the sum and average of all numbers. Lastly remove the expanded block
from memory.
Exercise 3 Start Date / /

To demonstrate strings in C.

You should read the following topics before starting this exercise
String literals
Declaration and definition of string variables
The NULL character
Accepting and displaying strings
String handling functions

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.

Actions Involving Explanation Example


Strings
Declaring Strings char message[80];
Initializing Strings char message[]= { ’H’, ’e’, ’l’, ’l’,
’o’, ’\0’ } ;
char message [ ] = “Hello”;

Accepting Strings scanf and gets can be used char name[20], address[50];
to accept strings printf(“\n Enter your name :);
scanf(“%s”, name);
printf(“\n Enter your address :);
gets(address);

Displaying Strings printf and puts can be used to printf(“\n The name is %s:”,
display strings. name);
printf(“\n The address is :”);
puts(address);

String functions All string operations are #include <string.h>


performed using functions in main( )
“string.h”. Some of the most {
commonly used functions are char str1[50], str2[50],str3[100];
a. strlen – Returns the printf(“\n Give the first string:”);
number of characters in gets(str1);
the string (excluding \0) printf(“\n Give the second string
b. strcpy – Copies one string:”);
string to another gets(str2);
c. strcmp – Compares two if (strlen(str1) == strlen(str2)
strings. Returns 0 (equal), {strcpy(str3, strrev(str1));
+ve (first string > strcat(str3, strupr(str2));
second), -ve (first string < puts(strupr(str3));
second ). It is case }
sensitive else
d. strcmpi – Same as puts(strlwr(str2);
strcmp but ignores case }
e. strcat – Concatenates the
second string to the first.
Returns the concatenated
string.
strrev – Reverses a string
and returns the reversed
string.
strupr – Converts a string
to uppercase.
strlwr - Converts a string
to lowercase
Sample program :
The following program demonstrates how to pass two strings to a user defined function and copy
one string to other using pointers
voidstring_copy (char *t,char *s)
{
while (*s !=’\0’) /* while source string does not end */
{*t=*s; s++;
t++;
}
*t =’\0’; /* terminate target string */
}

void main()
{
char str1[20], str2[20];
printf(“Enter a string :”);
gets(str1);
string_copy(str2, str1);
printf(“The copied string is :”);
puts(str2);
}

Assignment 3.

String handling using standard library functions

Set A . Write C programs for the following problems.


1. Write a menu driven program to perform the following
operations on strings using standardlibrary functions:
LengthCopyConcatenationCompare
ReverseUppercaseLowercase Check case

2. Write a program that will accept a string and character to search.


The program willcall a function, which will search for the
occurrence position of the character in thestring and return its
position. Function should return –1 if the character is not found
inthe string.

3. A palindrome is a string that reads the same-forward and reverse.


Example: “madam” is aPalindrome. Write a function which accepts
a string and returns 1 if the string is a palindrome and0 otherwise.
Use this function in main.
4. For the following standard functions, write corresponding user
defined functions and write amenu driven program to use them.
strcat, strcmp, strrev, strupr
5. 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 ?

6. Write a program in C to reverse each word in a sentence.


7. Write a function which displays a string in the reverse order. (Use
recursion)

8. Write a program that accepts n words and outputs them in


dictionary order.

9. Write a program that accepts n strings and displays the longest


string.
Exercise 4 Start Date / /

Structures and Union in C

You should read the following topics before starting this exercise
Concept of structure
Declaring a structure
Accessing structure members
Array of structures
Pointer to a structure.
Passing structures to functions

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’.

Operations Syntax / Description Example


performed
Declaring a structure struct structure-name struct student
{ {
type member-1 ; char name[20];
type member-2; introllno;
. int marks;
. };
type member-n ;
};
Creating structure structstructurename variable; struct student stud1;
variables
Accessing structure variable.member stud1.name
members stud1.rollno
stud1.marks

initializing a structure the 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;


name; ptr = &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]);
Sample Code:

/* Program for student structure */

#include<stdio.h>
struct student
{char name[20];
introllno;
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);
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 \t Roll no\t 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].perc);
}
}

Nested Structures and Unions

You should read the following topics before starting this exercise
Creating and accessing structures
Array of structures
Dynamic memory allocation
Structure within a structure
Creating and accessing unions

Nested structures: The individual members of a structure can be other structures as well. This is
called nesting of structures.
Operations Syntax Example
performed
Creating a nested struct structure1 struct student
structure { {
... introllno; char name[20];
struct structure2 struct date
{ {
... intdd, mm, yy;
} variable; } bdate, admdate;
... };
};

Method 2 struct date


struct structure2 {
{ intdd, mm, yy;
... };
};
struct student
struct structure1 {
{ introllno; char name[20];
... struct date bdate, admdate;
struct structure2 };
variable;
...
};
Accessing nested nested structure members can stud1.bdate.dd, stud1.bdate.mm
structure members be accessed using the (.)
operator repeatedly.
self referential A structure containing a pointer struct node
structure to the same structure {
int info;
struct node *next;
printf(“\n Title = %s”, book1.title);
printf(“\n Publisher = %s”, book1.publisher);
switch(book1.code)
{
case 1: printf(“Copies = %d:”, book1.info.no_of_copies);
break;
case 2: printf(“Issue month name = %s”,book1.
info.month); break;
case 3: printf(“Edition number =%d:”,book1.info.edition);
break;
}
printf(“\n Cost = %d”, book1.cost);
}

Assignment 4.

Structure and Unions.

1. Write a program to store and print the information of a student


using a structure
2. Write a program to add two distances using a structure. (in inch-
feet)
3. Write a program to add two complex numbers by passing
structures to a function
4. Write a program to calculate the difference between two time
periods
5. Write a program to store information of 10 students using
structures

Set A . Write C programs for the following problems.


1. Create a structure student (roll number, name, marks of 3
subjects, percentage). Acceptdetails of n students and write a
menu driven program to perform the following operations.
Writeseparate functions for the different options.
i) Search
ii) Modify
iii) Display all student details
iv) Display all student having percentage > _____
2. Create a structure employee (id, name, salary). Accept details
of n employees and write amenu driven program to perform the
following operations. Write separate functions for thedifferent
options.
i) Search by name
ii) Search by id
iii) Display all
iv) Display all employees having salary > _____
v) Display employee having maximum salary
Instructor should fill in the blanks with appropriate values.

Set A . Write C programs for the following problems.


1. Modify the sample program 1 above to accept details for n
books and write a menu drivenprogram for the following:
i) Display all text books
ii) Search Text Book according to Title
iii) Find the total cost of all books (Hint: Use no_of_copies).
2. Modify the sample program 1 to accept details for n books
and write a menu driven programfor the following:
i) Display all magazines
ii) Display magazine details for specific month.
iii) Find the “costliest” magazine.
3. Modify the sample program 1 to accept details for n books
and write a menu driven programfor the following:
i) Display all reference books
ii) Find the total number of reference books
iii) Display the edition of a specific reference book.

Unions
1. Write a program in C to declare a union named student having members
roll number, name, percentage and category. Accept and print the data
for one student.
Exercise 5 Start Date / /

To demonstrate text files using C

You should read the following topics before starting this exercise
Concept of streams
Declaring a file pointer
Opening and closing a file
Reading and Writing to a text file
Command line arguments

Operations Syntax Example


performed
Declaring File pointer FILE * pointer; FILE *fp;
Opening a File fopen(“filename”,mode); fp=fopen(“a.txt”, “r”);
where mode = “r”, “w”,
“a”, “r+”, “w+”, “a+”
Checking for if (pointer==NULL) if(fp==NULL)
successful open exit(0);
Checking for end of file feof if(feof(fp))
printf(“File has ended”);
Closing a File fclose(pointer); fclose(fp);
fcloseall();
Character I/O fgetc, fscanf ch=fgetc(fp);
fputc, fprintf fscanf(fp, ”%c”,&ch);
fputc(fp,ch);
String I/O fgets, fscanf fgets(fp,str,80);
fputs, fprintf fscanf(fp, ”%s”,str);
Reading and writing fscanf fscanf(fp, ”%d%s”,&num,str);
formatted data fprintf fprintf(fp, “%d\t%s\n”, num, str);
Random access to ftell, fseek, rewind fseek(fp,0,SEEK_END); /* end of file*/
files long int size = ftell(fp);

Sample Code 1
The following program reads the contents of file named a.txt and displays its contents on the
screen with the case of each character reversed.
/* Program revrese case of characters in a file */

#include <stdio.h>
#include <ctype.h>
void main()
{
FILE * fp;
fp = fopen(“a.txt”, “r”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
while( !feof(fp))
{
ch = fgetc(fp);
if(isupper(ch))
putchar(tolower(ch));
else
if(islower(ch))
putchar(toupper(ch));
else
putchar(ch);
}
fclose(fp);
}

Sample Code 2
The following program displays the size of a file. The filename is passed as command line
argument.

/* Program to display size of a file */

#include <stdio.h>
void main(intargc, char *argv[])
{
FILE * fp;
longint size;
fp = fopen(argv[1], “r”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
fseek(fp, 0, SEEK_END); /* move pointer to end of file
*/ size = ftell(fp);
printf(“The file size = %ld bytes”, size);
fclose(fp);
}

Sample Code 3
The following program writes data (name, roll number) to a file named student.txt , reads the
written data and displays it on screen.

#include <stdio.h>
void main()
{
FILE * fp;
charstr[20]; intnum;
fp = fopen(“student.txt”, “w+”);
if(fp==NULL)
{
printf(“File opening error”);
exit(0);
}
fprintf(fp,“%s\t%d\n”, “ABC”, 1000);
fprintf(fp,“%s\t%d\n”, “DEF”, 2000);
fprintf(fp,“%s\t%d\n”, “XYZ”, 3000);
rewind(fp);
while( !feof(fp))
{
fscanf(fp,“%s%d”, str, &num);
printf(“%s\t%d\n”, str, num);
}
fclose(fp);
}
To demonstrate binary file handling using C.

You should read the following topics before starting this exercise
Concept of streams
Declaring a file pointer
Opening and closing files
File opening modes
Random access to files
Command line arguments

In binary files, information is written in the form of binary . All data is written and read with no
interpretation and separation i.e. there are no special characters to mark end of line and end of
file.
I/O operations on binary files

Reading from a fread(address,size-of-element,number fread (&num,sizeof(int),1,fp);


binary file of elements,pointer); fread
(&emp,sizeof(emp),1,fp);
fread(arr,sizeof(int),10,fp);
Writing to a binary fwrite(address,size-of-element,number fwrite (&num,sizeof(int),1,fp);
file of elements,pointer); fwrite
(&emp,sizeof(emp),1,fp);

Sample Code
/* Program to demonstrate binary file */

struct employee
{char name[20]; float
sal;
};
main( )
{
FILE *fp;
struct employee e;
int i;
if((fp=fopen (“employee.in”,“wb”))==NULL)
{printf(“Error opening file”); exit( );
}

for(i=0;i<5;i++)
{
printf(”\n Enter the name and salary”);
scanf(“%s%f”,e.name,&e.sal);
fwrite(&e,sizeof(e),1,fp);
}
fclose(fp);

fp=fopen(“employee.in”,”rb”); /* reopen file */


if(fp==NULL)
{ fprintf(stderr, “Error opening file); exit( );
}
for(i=0;i<5;i++)
{
fread(&e,sizeof(e),1,fp);
printf(“\n Name = %s Salary = %f”,e.name,e.sal);
}
fclose(fp);
}

Assignment 5.

File Handling.

1] Write a program in C that reads the contents of file named a.txt and
displays its contents on thescreen with the case of each character
reversed.
2]Write a program in C thatdisplays the size of a file. The filename is
passed as command lineargument.
3]Write a program in C thatwrites data (name, roll number) to a file
named student.txt , reads thewritten data and displays it on screen.

Set A . Write C programs for the following problems.


1. Write a program to accept two filenames as command line
arguments. Copy the contents ofthe first file to the second such that the
case of all alphabets is reversed.
2. Write a program to accept a filename as command line argument
and count the number ofwords, lines and characters in the file.
3. Write a program to accept details of n students (roll number, name,
and percentage) and write itto a file named “student.txt”. Accept roll
number from the user and search the student in the file.Also display the
student details having the highest percentage
Exercise 6 Start Date / /

Assignment to demonstrate preprocessor directives.

You should read the following topics before starting this exercise
Passing arguments from the command line to main
Accessing command line arguments
File inclusion, macro substitution and conditional compilation directives.
Argumented and Nested macros

Preprocessor They begin with a # which must


directives be the first non-space character
on the line.
They do not end with a
semicolon.
Macro Substitution # define MACRO value # define PI 3.142
Directive
Argumented # define MACRO(argument) # define SQR(x) x*x
macro value #define LARGER(x,y) ((x)>(y)?(x):(y))

Nested macro one macro using another #define CUBE(x) (SQUARE(x)*(x))

File Inclusion #include <filename> #include <stdio.h>


directive #include “filename”
Conditional # if, # else, # elif, # endif #ifdef #ifdef PI
Compilation #undef PI
directive #endif
Command Line intargc - argument counter void main(intargc, char *argv[])
Arguments char *argv[]-argument vector {
printf(“There are %d arguments in all”,
argc);
for (i=0; i<argc; i++)
printf(”Argument %d =%s”,i,argv[i]);
}

To run a program Compile the program using cc Example: a.out ABC 20


using command Execute the program using Here, ABC and 20 are the two command
line arguments a.out followed by command line line arguments which are stored in the
arguments form of strings. To use 20 as an integer,
use function atoi .
Example: intnum = atoi(argv[2]);
Assignment 5.

Preprocessor

1. Define a macro EQUALINT which compares two parameters x and y and gives 1 if
equal and 0 otherwise. Use this macro to accept pairs of integers from the user.
Calculate the sum of digits of both and continue till the user enters a pair whose sum
of digits is not equal.

2. Define a macro EQUALSTR which compares two strings x and y and gives 1 if
equal and 0 otherwise. Use this macro to accept two strings from the user and check if
they are equal.
3. Create a header file “mymacros.h” which defines the following macros.
i. SQR(x) ii. CUBE(x) - nested iii. GREATER2(x,y) iv. GREATER3 (x,y,z) – nested
Include this file in your program. Write a menu driven program to use macros SQR,
CUBE, GREATER2 and GREATER3.
4. Write a program in C that uses a macro SWAP to interchange the values of two
variables. Use the same macro to sort an array of ten integers using bubble sort.
5. Define two macros UPPERCASE and LOWERCASE to check whether the
character is upper case or lower case. Also accept a string and reverse the case of
each character in it.

You might also like