Advanced C Workbook For Fybcs 2020
Advanced C Workbook For Fybcs 2020
(Computer Science)
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 / /
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).
Pointer
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
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.
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
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);
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.
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’.
#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);
}
}
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;
... };
};
Assignment 4.
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 / /
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
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.
#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
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);
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.
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
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.