You are on page 1of 79

C Programming

Lab Guide

© Infosys Technologies Ltd


No. 350, Hebbal Electronics City, Hootagalli
Mysore – 571186

Author(s) Venkatesh N.V.


Vani V
Authorized by Dr. M.P. Ravindra
Creation Date March -2005
Version 1.00
Document Revision Summary
Version Date Author Reviewed by Comments
0.00a Mar-05 Venkatesh N.V. Sujith Samuel Initial Draft
Vani V Mathew
1.00 Aug-05 Sujith Samuel Incorporated review
Mathew Comments

Page i
Table Of Contents

1 BACKGROUND........................................................................................................1

2 ASSIGNMENTS FOR DAY 1 .........................................................................................1

2.1 WRITING YOUR FIRST C PROGRAM IN UNIX ........................................................................ 1


2.2 DETERMINING THE TYPE OF THE CHARACTER ....................................................................... 6
2.3 UNDERSTANDING THE MENU DRIVEN PROGRAM ..................................................................... 8
2.4 COMPUTING SUM OF THE DIGITS OF A NUMBER ..................................................................... 9
2.5 DISPLAYING WORDS OF THE DIGITS OF A NUMBER .................................................................. 9
2.6 FORMATTING THE TEXT CASES ..................................................................................... 9
2.7 SEARCH FOR A PATTERN IN A TEXT ............................................................................... 10
2.8 COUNTING OF CHARACTERS, WORDS AND LINES IN A TEXT........................................................ 10
2.9 COUNT OF VOWELS, DIGITS, ALPHABETS AND SPECIAL CHARACTERS .............................................. 10
2.10 POINTERS ....................................................................................................... 10
2.11 HANDLING OF STRINGS USING POINTERS ......................................................................... 12
2.12 REVERSING A STRING ............................................................................................ 14
2.13 PALINDROME .................................................................................................... 14
2.14 TRIMMING OF SPACES IN THE STRING ............................................................................. 14
2.15 SEARCHING OF CHARACTER IN A STRING ......................................................................... 15
2.16 UNDERSTANDING STRUCTURES................................................................................... 15
2.17 ARRAYS OF STRUCTURES ........................................................................................ 17
2.18 UNDERSTANDING THE CONCEPT OF LINKED LIST ................................................................. 20
2.19 OPERATIONS ON LINKED LIST TO PROCESS EMPLOYEE DETAILS .................................................... 31
2.20 OPERATIONS ON LINKED LIST TO PROCESS LINES OF TEXT......................................................... 31

3 ASSIGNMENTS FOR DAY 2 ....................................................................................... 32

3.1 UNDERSTANDING COMMAND LINE ARGUMENTS ................................................................... 32


3.2 HANDLING COMMAND LINE ARGUMENTS .......................................................................... 33
3.3 UNDERSTANDING UNION ......................................................................................... 34
3.4 ARRAY OF STRUCTURES .......................................................................................... 36
3.5 UNDERSTANDING STACKS ........................................................................................ 36
3.6 UNDERSTANDING QUEUES ....................................................................................... 41
3.7 OPERATIONS ON FILES ........................................................................................... 46
3.8 OPERATIONS ON FILES USING COMMAND LINE .................................................................... 48
3.9 REMOVAL OF COMMENT LINES ................................................................................... 50
3.10 COUNTING THE NUMBER OF WORDS IN A FILE .................................................................... 50
3.11 CREATION AND MAINTENANCE OF CONCORDANCE................................................................. 50
3.12 FILE HANDLING – BANK APPLICATION ............................................................................ 50
3.13 FILE HANDLING - EMPLOYEE DETAILS ............................................................................ 57

4 ASSIGNMENTS FOR DAY 3 ....................................................................................... 58

4.1 STORAGE CLASS SPECIFIERS ...................................................................................... 58


4.2 UNDERSTANDING PREPROCESSOR DIRECTIVES .................................................................... 61

Page ii
4.3 UNDERSTANDING CONDITIONAL COMPILATION ................................................................... 63

5 ASSIGNMENTS FOR DAY 4 ....................................................................................... 65


5.1 ARRAY OPERATIONS USING POINTERS ............................................................................ 65
5.2 UNDERSTANDING FUNCTION POINTERS ........................................................................... 65
5.3 PASSING FUNCTION AS AN ARGUMENT ........................................................................... 67
5.4 ARRAY OF FUNCTION POINTERS .................................................................................. 69
5.5 ARRAY OF VOID POINTERS ....................................................................................... 70
5.6 RUN-TIME ERRORS IN C (1)...................................................................................... 70
5.7 RUN-TIME ERRORS IN C (2)...................................................................................... 72
5.8 RUN-TIME ERRORS IN C (3)...................................................................................... 74

Page iii
C Programmin Lab Guide Version 1.0

1 Background
This document contains the assignments to be completed as part of the hands on for Unix.

Note: All assignments in this document must be completed in the sequence in this document
in order to complete the course. It is advisable to study & practice the examples incorporated
in the Slides before starting with the below assignments/exercises.

2 Assignments for Day 1

2.1 Writing your first C program in UNIX


Objective: To learn how to write a C program, compile and execute it

Background: The UNIX has a variety of tools to help write code in C

Step 1: Click on Start - > select Run ->type telnet 172.21.103.44 (use IP address of the UNIX
server that has been assigned to you)
Step 2: The login window appears

Step 3: Type your login name and password, a $ prompt appears

Education & Research Department Page 1


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

At the prompt, type vi and a filename with extension .c. Example: vi hello.c

The editor, vi appears

Education & Research Department Page 2


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Step 4: Press the keys Esc+I or Esc+o or Esc+a, and type the following C program

/************************************************************
* Filename: hello.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
* Description: First C Program. Uses function printf
*************************************************************/
#include <stdio.h>
/************************************************************
* Function main
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv) {

printf ("Hello World\n");

/* Return a code back to OS!*/


return 0;
}

/************************************************************
* End of hello.c
*************************************************************/

Education & Research Department Page 3


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Step 5: Save and quit the program by pressing the Esc:wq

Step 5: Use a compiler to compile the program. Either cc or gcc can be used, two compilers
provided on UNIX. At the prompt type cc and filename with the extension .c. If the
compilation and linking is successful, the $ prompt appears

Example: cc hello.c.

Education & Research Department Page 4


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Step 6: An executable file a.out is created. At the prompt type the name of the executable
file to run the program

Education & Research Department Page 5


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Note: Some of the options used with cc command

Syntax: cc <options> <object file> <source file>

Options
-c : Compiles and no linking would be done
-o : Creates an final executable file.
Examples:
(i) cc hello.c
The above command creates an executable file for the file named
hello.c. The object file is said to be the default file named a.out. To
execute the program we need to give ./a.out.
(ii) cc –o hello.exe hello.c (or) cc hello.c –o hello.exe
The above is same as that of the previous one, but the only difference is
instead of executing the file using ./a.out,here we create an object file
named hello.exe for execution.
(iii) cc –o main.exe main.c sub.c wish.c
The above command creates an executable file for the file named main.c,
sub.c , wish.c. All the files are compiled based on their
dependencies.Then they are linked together and creates an object file for
execution by the name main.exe.
(iv) cc –c sub.c wish.c
The above command is used to create the object files (i.e., in Assembly
Language) with the file named sub.o & wish.o. Then we link it with cc
main.c sub.o wish.o

Summary of this exercise:


You have just learnt
• How to login into UNIX
• How to type code vi editor and quit from it
• How to compile, link a C program
• How to execute your program in UNIX
• Various options in cc tool

Deliverables of the exercise:


• hello.c – the source code
• hello.exe – the executable file

2.2 Determining the type of the character


Objective: To understand various character handling functions.

Background: C has the built-in header file ctype.h, which provides all the character handling
functions.

Step 1: Type the following program in vi editor

Education & Research Department Page 6


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Filename: case.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: Uses character Handling functions present in
<ctype.h> to check the character entered
*************************************************************/
#include <stdio.h>
#include <ctype.h>

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv)


{
char ch;
ch = getchar();

if(isupper(ch))
printf("%c - is upper case letter",ch);
else if(islower(ch))
printf("%c -is lower case letter",ch);
else if(isdigit(ch))
printf("%c - is digit",ch);
else
printf("%c - is a special char",ch);

/* Return a code back to OS!*/


return 0;
}

/*********************************************************************
* end of case.c
*********************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Education & Research Department Page 7


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Summary of this exercise:


You have just learnt
• How to use character handling functions

Deliverables of the exercise:


• case.c – the source code

2.3 Understanding the menu driven program


Objective: To understand the use of switch case and do… while

Problem Description: A menu driven C program which accepts an integer iNum and provides
the following options:
1. Determine the factorial of iNum
2. Determine if iNum is a prime number
3. Determine if iNum is odd or even
4. Exit

Step 0: Declare the integer variables iNum, iOpt


Step 1: Read the value of iNum using scanf()
Step 2: Display the Menu and read the choice in iOpt
Step 3: Use switch case structure to perform the specific operation based on the choice
entered
Step 4: Iterate the processes using do..while loop till the user chooses the “Exit” option

Use exit(0) built-in function to exit from the program and include <stdlib> header file

Education & Research Department Page 8


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

2.4 Computing Sum of the digits of a number

Objective: To learn how to extract the individual digits from a given number

Problem Description:
Write a C program to determine the sum of digits of a 5 digit positive integer iNum accepted
from the user

Step 0: Declare the unsigned integer variables iSum,iNum


Step 1: Initialise the variable iSum to 0.
Step 2: Read the value of iNum using scanf()
Step 3: Use while loop until the iNum value becomes zero
Step 4: Inside while loop extract individual digits by using % operator with denominator as 10
and add it with iSum and store it in iSum
Step 6: Decrement the value of iNum by dividing it by 10 and store it.
Step 7: When iNum becomes “0”, exit from while loop and Display the iSum

2.5 Displaying words of the digits of a number

Objective: To learn how to use two dimensional arrays

Problem Description:
Write a C program to display the words for each digit in a given number

Hint: Store the words from “zero” to “nine” in two dimensional array starting from 0th
location and extract each and every digit using % operator and print the corresponding words

2.6 Formatting the text cases

Objective: To get more familiarized with the concept of switch structures and loops

Problem Description:
Write a C program to convert the read text to
• Lower Case
• Upper Case
• Title Case

Step 1: Read a line of text using gets( ) as well as include <string.h> header file.
Step 2: Display the menu and read the choice.
Step 3: Based on the choice using while/for loop convert the text into corresponding case

Education & Research Department Page 9


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

2.7 Search for a pattern in a text

Objective: To get more familiarized with string handling

Problem Description:
Write a C program to read a pattern and a text and find the number of occurrences as well as
the position of each occurrence

Hint: Input Text: “AAAAAAAAAA”,


Input Pattern: “AA”
Output: Number of occurrences: 9
Position of occurrences : 1,2,3,4,5,6,7,8,9

2.8 Counting of characters, words and lines in a text

Objective: To get more familiarized with getchar( ) function and loops

Problem Description:
Write a C program to count the number of characters, words and lines in the given text.

2.9 Count of vowels, digits, alphabets and special characters

Objective: To get the count of vowels, digits, alphabets and special characters in a given text
using the getchar( ) function and loops

Problem Description:
Write a C program to count the number of characters, words and lines in the given text

2.10 Pointers

Objective: To understand the concept of accessing variables values through pointers.

Step 1: Type the following program in vi editor

/************************************************************
* Filename: ptraccess.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: Demo program to understand the concept of pointers

Education & Research Department Page 10


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

*************************************************************/
#include <stdio.h>
/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv)


{
/* Declaration of variables and pointers */
char ch,*cPtr;
int iNum, *iPtr;
float fNum, *fPtr;

/* Initialization of variables */
ch = ‘A’;
iNum = 7;
fNum = 123.45;

/* Printing variable’s address and content */


printf("ch: address=0x%p, content=%c\n", &ch, ch);
printf("iNum: address=0x%p, content=%d\n", &iNum, iNum);
printf("fNum: address=0x%p, content=%5.2f\n", &fNum, fNum);

/* Initializing Pointer Variable and printing its address and content*/


cPtr = &c;
printf("cPtr: address=0x%p, content=0x%p\n", &cPtr, cPtr);
printf("*cPtr => %c\n", *cPtr);

/* Initializing Pointer Variable and printing its address and content */


iPtr = &iNum;

printf("iPtr: address=0x%p, content=0x%p\n", &iPtr, iPtr);


printf("*iPtr => %d\n", * iPtr);
/* Initializing Pointer Variable and printing its address and content */
fPtr = &fNum;
printf("fPtr: address=0x%u, content=0x%p\n", &fPtr, fPtr);
printf("*fPtr => %5.2f\n", * fPtr);
/* Return a code back to OS!*/
return 0;
}

Education & Research Department Page 11


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/*********************************************************************
* end of ptraccess.c
*********************************************************************/

Step 2: Compile and execute the program using cc and a.out by default

Summary of this exercise:


You have just learnt
• How to initialize and access pointer variables

Deliverables of the exercise:


ptraccess.c – the source code

2.11 Handling of strings using pointers

Objective: To understand the concept of accessing arrays using pointers.

Step 1: Type the following program in vi editor

/************************************************************
* Filename: ptr_string.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: Demo program to illustrate handling of strings using pointers
*************************************************************/

#include <stdio.h>
/************************************************************
* Function main

Education & Research Department Page 12


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
int main (int argc, char**argv)
{
/* Declaration of array variables and and pointers and initializing it*/

char str1[] = {'A', ' ',


's', 't', 'r', 'i', 'n', 'g', ' ',
'c', 'o', 'n', 's', 't', 'a', 'n', 't', '\0'};
char str2[] = "Another string constant";
char *PtrStr;
int iCount;

/* print out str2 */


for (iCount=0; str1[iCount]; iCount++)
printf("%c", str1[iCount]);
printf("\n");

/* print out str2 */


for (iCount=0; str2[iCount]; iCount++)
printf("%c", str2[iCount]);

printf("\n");

/* assign a string to a pointer */

PtrStr = "Assign a string to a pointer.";


for (iCount=0; *PtrStr; iCount++)
printf("%c", *PtrStr++);
/* Return a code back to OS!*/
return 0;
}

/*********************************************************************
* end of ptr_string.c
*********************************************************************/

Step 2: Compile and execute the program using cc and a.out by default

Education & Research Department Page 13


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Summary of this exercise:


You have just learnt
• How to access string using pointer
Deliverables of the exercise:
• ptr_string.c – the source code

2.12 Reversing a String

Objective: To explore the concept of pointer and its notations

Problem Description:
Write a C Program which accepts a string from the user and reverses it. Use pointer notation
to access the elements of the string

Step 1: Declare a character type pointer variable and an integer iCount


Step 2: Read value for the string from keyboard
Step 3: Iterate a loop and print the characters in the reverse order by initializing the iCount
value to strlen(str) and decrement it till it becomes zero

2.13 Palindrome

Objective: To get more familiarize the concept of pointer and its notations.

Problem Description:
Write a C Program which accepts a string from the user and determines its length and also
determines if it is a palindrome. Use pointer notation to access the elements of the string.

Step 1: Declare a character type pointer variable and integers, iCount and iLen.
Step 2: Read value for string from keyboard
Step 3: Find the length of the string using strlen() as well as include the corresponding header
file <string.h>
Step 4: Iterate the loop for len/2 times to compare the characters by extracting a character
from left and at the same time a character from right
Step 5: Display whether the given string is a palindrome or not

2.14 Trimming of spaces in the string

Problem Description:
Write 3 different functions fnLtrimSpaces() fnRtrimSpaces() fnTrimSpaces() which accepts a
string from the user and removes left side spaces, right side spaces and all the spaces
respectively from the string. Use pointer notation to access the elements of the string.

Education & Research Department Page 14


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Hint: Define 3 functions and pass an argument of type character pointer which in turn
contains the string to be trimmed according to the function call.

2.15 Searching of character in a string

Problem Description:
Write a function fnSearchChar() which accepts a string and a character. The function should
search for the occurrence of the character in the string. If the character is found then it
should return a pointer to the first occurrence of the given character otherwise it should
return a NULL. Use pointer notation to access the elements of the string.

Hint: Define a function


char * fnSearchChar(char *str,char ch);

If the character is found, return a character pointer which points to that matched position
character else return NULL

2.16 Understanding Structures

Objective: To understand how to use structures

Step 1: Type the following C code in vi Editor

/****************************************************************************
* Filename: structureexample.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstrate
* the usage of structures in C
****************************************************************************/
#include<stdio.h>

/* Declare the structures date and employee */

struct date
{
int day;
int month;
int year;
};

Education & Research Department Page 15


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

typedef struct date DATE;

struct employee
{
int empno;
char empname[20];
DATE birthdate;
int yearsofservice;
};

/****************************************************************************
* Function printEmployeeInformation
*
* DESCRIPTION: Prints the employee information available in a structure
* PARAMETERS: Accepts employee object as input
****************************************************************************/
void printEmployeeInformation(struct employee e)
{
printf("\n printing Employee details ");
printf("\n Employee number : %d ",e.empno);
printf("\n Employee Name : %s ",e.empname);
printf("\n Employee Birth Date : %d / %d / %d ",e.birthdate.day,
e.birthdate.month, e.birthdate.year);
printf("\n Years of service : %d ",e.yearsofservice);
}

/****************************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
****************************************************************************/

int main(char **argv,int argc)


{
/* create an structure employee and initialize the
values to the members */

DATE d = {10,2,1974};
struct employee e ={100,"Venkat"};
e.birthdate = d;
e.yearsofservice =10;

/* print employee information by passing employee object to


printEmployeeInformation function */

Education & Research Department Page 16


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

printEmployeeInformation(e);

/* Returns value to OS */
return 0;
}
/****************************************************************************
* end of structureexample.c
***************************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use the structures in C.

Deliverables of the exercise:


• structureexample.c – the source code

2.17 Arrays of Structures

Objective: To understand how to use an array of structures in C

Step 1: Type the following C code in vi editor

/****************************************************************************
* Filename: arrayOfStructure.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstrate
the usage of array of structures in C
****************************************************************************/

#include<stdio.h>

/*Declare structure to hold trainee information */

typedef struct trainee


{
int empnumber;
char empname[25];
int age;
}Trainee;

Education & Research Department Page 17


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

#define SIZE 2

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main(char **argv,int argc)


{

/* create an array of SIZE trainees for a particular trainee batch */

Trainee trainee_batch[SIZE];
Trainee tmp;
int i;
int index1,index2;

/* Read data for Trainees */

printf("Enter details of Traines \n");

for(i =0 ;i < SIZE ;i++)


{
printf("\n Enter employee number : ");
scanf("%d", &trainee_batch[i].empnumber);
printf("\n Enter employee name : ");
scanf("%s", trainee_batch[i].empname);
printf("\n Enter employee age : ");
scanf("%d", &trainee_batch[i].age);
}

/* print the details of Trainees */

for(i =0 ;i < SIZE ;i++)


{

printf("Employee %d\n",i+1);
printf("Employee Number : %d\n", trainee_batch[i].empnumber);
printf("Employee Name : %s\n", trainee_batch[i].empname);
printf("Employee Age : %d\n", trainee_batch[i].age);
}

/*get the record numbers for swapping */

Education & Research Department Page 18


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

printf("\n Enter the record numbers of the employees to be swapped ");


printf("\n The allowed record numbers are from 1 to %d : ",SIZE);
scanf("%d%d",&index1,&index2);
index1--;
index2--;

/* check for validity of record numbers */

if(index1 > SIZE || index2 > SIZE )


{
printf("Invalid record number ");
return -1;
}

printf("\n employee information before swapping ");

/*Display Employee number for record number index1 before swapping*/

printf("\n Employee %d\n",index1+1);


printf("Employee Number : %d\n", trainee_batch[index1].empnumber);
printf("Employee Name : %s\n", trainee_batch[index1].empname);
printf("Employee Age : %d\n", trainee_batch[index1].age);

/*Display Employee number for record number index2 before swapping*/


printf("\n Employee %d\n",index2+1);
printf("Employee Number : %d\n", trainee_batch[index2].empnumber);
printf("Employee Name : %s\n", trainee_batch[index2].empname);
printf("Employee Age : %d\n", trainee_batch[index2].age);

/*Swap the two structures*/


tmp = trainee_batch[index1];
trainee_batch[index1] = trainee_batch[index2];
trainee_batch[index2] = tmp;

printf("\n employee information after swapping ");

/*Display Employee number for record number index1 after swapping*/

printf("\n Employee %d\n",index1+1);


printf("Employee Number : %d\n", trainee_batch[index1].empnumber);
printf("Employee Name : %s\n", trainee_batch[index1].empname);
printf("Employee Age : %d\n", trainee_batch[index1].age);

/*Display Employee number for record number index2 before swapping*/

Education & Research Department Page 19


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

printf("\n Employee %d\n",index2+1);


printf("Employee Number : %d\n", trainee_batch[index2].empnumber);
printf("Employee Name : %s\n", trainee_batch[index2].empname);
printf("Employee Age : %d\n", trainee_batch[index2].age);

/* Returns value to OS */
return 0;
}
/******************************************************************
* end of arrayOfStructure.c
******************************************************************/

Step 2: Compile and execute the program using cc and a.out by default

Summary of this exercise:


You have just learnt
• How to use the array of structures in C

Deliverables of the exercise:


• arrayOfStructure.c - the source code

2.18 Understanding the concept of Linked List

Objective: To understand how to implement various operations of linked list in C

Step 1: Complete the following C code

/****************************************************************************
* Filename: linkedlist.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstrate the
* implementation of linked list in C
* This demo program does the following operations:
* 1. creation of the linked list
* 2. addition of an element at the begining and end
* 3. print the linked list
* 4. count the number of elements in the linked list
* 5. remove the first element from the linked list
* 6. remove a node with the given value
* 7. search for a given value
* 8. search and replace the the given value with another value

Education & Research Department Page 20


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* 9. insertion of a value before, after a given value


****************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>

/* Declare the node for the linked list*/


typedef struct node
{
int data;
struct node *next;
}NODE;

/* Initialize the head pointer to NULL to indicate empty list */

NODE *head=NULL;

/************************************************************
* Function createnode
*
* DESCRIPTION: creates a node with the given data and link
*
* PARAMETERS:
* accepts data and link as inputs
* RETURNS
* A pointer to the node created
*************************************************************/
NODE* createnode(int x, NODE* lnk)
{
NODE *ptr;
ptr = (NODE*) malloc(sizeof(NODE));
ptr->data =x;
ptr->next =lnk;
return ptr;
}

/************************************************************
* Function destroynode
*
* DESCRIPTION: deallocates space for given node
*
* PARAMETERS:
* accepts pointer to the node to be removed

Education & Research Department Page 21


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

*************************************************************/

void destroynode(NODE* ptr)


{
free(ptr);
}

/************************************************************
* Function addfirst
*
* DESCRIPTION: adds the given integer to the front of the list
*
* PARAMETERS:
* accepts an integer value to be inserted at the front
*************************************************************/
void addfirst(int x)
{
NODE *ptr = createnode(x,NULL);

if(!head) // if list is empty


{
head=ptr;
}
else //update the head
{
ptr->next = head;
head=ptr;
}
}

/************************************************************
* Function addlast
*
* DESCRIPTION: adds the given integer to the end of the list
*
* PARAMETERS:
* accepts an integer value to be inserted at the last
*************************************************************/
void addlast(int x)
{

NODE *ptr =createnode(x,NULL);

/* Complete this function to ensure that a

Education & Research Department Page 22


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* node is added to the end of the list


*/
}

/************************************************************
* Function search
*
* DESCRIPTION: searches the linked list for the given integer
*
* PARAMETERS:
* accepts the data to be searched in the linked list
* RETURNS
* 1(true) if the given element is found 0(false) otherwise
*************************************************************/
int search(int x)
{
NODE* ptr = head;
while(ptr)
{
if(ptr->data == x)
return 1;
ptr=ptr->next;

}
return 0;
}

/************************************************************
* Function print
*
* DESCRIPTION: prints the linked list
*
*************************************************************/
void print()
{
NODE* ptr=head;
printf("\n");

while(ptr)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}

Education & Research Department Page 23


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Function count
*
* DESCRIPTION: counts the number of elements in the linked list
*
* RETURNS
* an integer value indicating the count of elements in the list
*************************************************************/
int count()
{

NODE* ptr=head;
int ct=0;
while(ptr)
{
ct++;
ptr=ptr->next;
}
return ct;
}

/************************************************************
* Function find
*
* DESCRIPTION: searches the linked list for the given integer
* and returns a pointer to the node
* PARAMETERS:
* accepts the data to be searched in the linked list
* RETURNS
* a pointer to the node if found else NULL
*************************************************************/
NODE* find(int x)
{
NODE* ptr =head;

/* Complete this function to search for the value in


* the list and return a pointer to the node
*/

return ptr;
}

/************************************************************
* Function findprev
*

Education & Research Department Page 24


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* DESCRIPTION: searches the linked list for the given integer


* and returns a pointer to the previous node
* PARAMETERS:
* accepts the data to be searched in the linked list
* RETURNS
* a pointer to the previous node if found else NULL
*************************************************************/
NODE* findprev(int x)
{
if(head->data ==x)
return NULL;
else
{

NODE *ptr =head;


NODE *prev =NULL;
while(ptr->data !=x && ptr !=NULL)
{
prev=ptr;
ptr=ptr->next;
}
return prev;
}
}

/************************************************************
* Function insertbefore
*
* DESCRIPTION: inserts the given integer y before the integer x
* in the linked list
* PARAMETERS:
* the value (x) before which the value (y) to be inserted
*************************************************************/

void insertbefore(int x,int y)


{

NODE* prev;
NODE* ptr;
NODE* nn;
prev = findprev(x);

/*if x itself is not in the linked list


dont do anything return */
ptr=find(x);

Education & Research Department Page 25


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

if(ptr==NULL)
{
return;
}
if(prev == NULL)
{
addfirst(y);
}
else
{
ptr=find(x);
nn=createnode(y,NULL);
nn->next =ptr;
prev->next =nn;
}

/************************************************************
* Function insertafter
*
* DESCRIPTION: inserts the given integer y after the integer x
* in the linked list
* PARAMETERS:
* the value (x) after which the value (y) to be inserted
*************************************************************/
void insertafter(int x,int y)
{

/* Complete the function to insert an integer "y"


* in the appropriate location after a given integer "x"
*/
}

/************************************************************
* Function removefirst
*
* DESCRIPTION: removes the first element of the linked list
*************************************************************/
void removefirst()
{
if(!head)
return;
else
{

Education & Research Department Page 26


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

NODE* ptr=head;
head = head->next;
destroynode(ptr);
}
}

/************************************************************
* Function removenode
*
* DESCRIPTION: removes the node with the given value x
* from the linked list
* PARAMETERS:
* the value (x) to be removed from the list
*************************************************************/
void removenode(int x)
{
/* Complete the fucntion to remove the node
* with value x from the list
*/
}

/************************************************************
* Function createlist
*
* DESCRIPTION: creates a linked list
*************************************************************/
void createlist()
{
char choice='Y';
int data;
while(choice == 'Y')
{
printf("\n Enter the number : ");
scanf("%d",&data);
addlast(data);
printf("\n Element added to the list");
printf("\n Press Y to continue any key to stop");
choice=getch();
}
}

/************************************************************
* Function menu
*
* DESCRIPTION: displays menu to get the choice for
* various linked list operatiosn

Education & Research Department Page 27


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* RETURNS
* an integer value indicating the choice entered by the user
*************************************************************/
int menu()
{
int ch;

printf("\n Linked list operations ");


printf("\n Please select from the choice list");
printf("\n 1.create linked list");
printf("\n 2.print the linked list");
printf("\n 3.count the number of elements");
printf("\n 4.add an element at the first");
printf("\n 5.add an element at the last");
printf("\n 6.remove the first element");
printf("\n 7.remove any element with the given value");
printf("\n 8.Insert before an element");
printf("\n 9.Insert after an element");
printf("\n 10.Search for an element");
printf("\n 11.Search and Replace an element");
printf("\n 12.Quit");
printf("\n Enter your choice : ");
scanf("%d",&ch);

return ch;
}

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
int main()
{
int choice;
int no,no1;
NODE* ptr;

/* get the choice from the user and


invoke various linked list operations */

while((choice=menu()) != 12)
{
switch(choice)

Education & Research Department Page 28


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

{
case 1:
createlist();
break;
case 2:
printf("\n The contents of the
linked list are given below");
print();
break;
case 3:
printf("\n The number of elements
in the linked list is %d",count());
break;
case 4:
printf("\n enter the element to be
added at first : ");
scanf("%d",&no);
addfirst(no);
break;
case 5:
printf("\n enter the element to be
added at last : ");
scanf("%d",&no);
addlast(no);
break;
case 6:
removefirst();
break;
case 7:
printf("\n enter the number to be deleted");
scanf("%d",&no);
removenode(no);
break;
case 8:
printf("\n enter the number x ");
scanf("%d",&no);
printf("\n enter the number to be inserted y");
scanf("%d",&no1);
insertbefore(no,no1);
break;
case 9:
printf("\n enter the number x ");
scanf("%d",&no);
printf("\n enter the number to be inserted y");
scanf("%d",&no1);
insertafter(no,no1);

Education & Research Department Page 29


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

break;
case 10:
printf("\n enter the element to be searched : ");
scanf("%d",&no);
if(!search(no))
printf("\n number is not found ");
else
printf("\n number is found");
break;
case 11:

printf("\n enter the element to be searched : ");


scanf("%d",&no);
ptr =find(no);
printf("\n enter the element to be replace : ");
scanf("%d",&no1);
ptr->data = no1;
break;
case 12 :
break;
default :
printf("\n Invalid choice");
}
}
/* Returns value to OS */
return 0;
}

/******************************************************************
end of linkedlist.c
*******************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to implement various operations of linked list in C.

Deliverables of the exercise:


• linkedlist.c - the source code

Education & Research Department Page 30


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

2.19 Operations on linked list to process employee details

Problem Description:

Create a linked list to store employee information (Employee ID, Name, and Age). The
program should use following functions:
• Append a node to the list
• Delete a node from the list (function must take employee id to be deleted as the
argument)
• Sort the existing list on employee id
• Insert a node into the sorted list (Function takes the position to be inserted at as the
argument)

2.20 Operations on linked list to process lines of text

Problem Description: Write a Program to read lines from keyboard and store it in a linked
list. Perform the following operations over the linked list

• Print all the lines read with line numbers


• Count the total number of lines
• For each line print the line number and number of words in that line

Education & Research Department Page 31


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

3 Assignments for Day 2

3.1 Understanding Command Line Arguments

Objective: To understand the usage of command line arguments

Step 1: Type the following program in vi editor

/****************************************************************************
* Filename: cmdarg.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstrate
The usage of command line arguments
****************************************************************************/
#include <stdio.h>

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv)


{
/*Declaration of Variables */

int iCount;
printf("\n Total number of arugments is : %d ", argc);
printf("\n The command line arguments are ");

for(iCount =0; iCount <argc; iCount ++)


printf("%s\t ", argv[iCount]);

printf("\n");

/* Returns value to OS */

Education & Research Department Page 32


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

return 0;

}
/******************************************************************
*end of cmdarg.c
******************************************************************/

Step 2: Compile and execute the program using cc. While executing this program, give the
command line arguments also along with a.out.

Summary of this exercise:


You have just learnt
• How to use the command line arguments

Deliverables of the exercise:


cmdarg.c – source code

3.2 Handling command line arguments

Problem Description:

Write a C program using command line arguments to design a simple calculator. The program
accepts 4 arguments
a. Operand 1
b. Operand 2
c. Operator
d. type(F,I & D indicating Float, Interger and Double)
Example: Input: 10.5 20.5 + F
Output: 31.0
The program must validate if the required number of arguments are given or not.

Education & Research Department Page 33


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

3.3 Understanding Union

Objective: To understand how to use unions in C and also to understand the difference in the
way the memory locations are allotted to the data members of the union and structure.

Step 1: Type the following C code in Vi Editor

/****************************************************************************
* Filename: unionexample.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstrate
the usage of unions in C
****************************************************************************/

#include<stdio.h>

/* declare tags for Different shapes*/


enum shape_tag
{
CIRCLE,
RECTANGLE
};

typedef enum shape_tag shapetype;

/*Structure Defining Geometrical shape*/

struct figure_tag
{
float area; /* Fixed part of the structure*/
shapetype shapeinfo; /* Tag to keep track of what is stored*/
union
{
float radius; /* 1. Incase of CIRCLE*/
struct
{ /* 2. Incase of RECTANGLE*/
float height;
float width;
}rectangle;
}u;
};

/************************************************************

Education & Research Department Page 34


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main(char **argv,int argc)


{
/* create an shape structure for circle
and initialize the values to the members */

struct figure_tag shape;

shape.shapeinfo = CIRCLE;
shape.u.radius = 2.0;
shape.area = 3.14f * shape.u.radius *shape.u.radius;
printf("\n area of shape(circle) : %f ",shape.area);

/* create an shape structure for rectangle


and initialize the values to the members */

shape.shapeinfo = RECTANGLE;
shape.u.rectangle.height = 10;
shape.u.rectangle.width = 20;
shape.area = shape.u.rectangle.height*shape.u.rectangle.width;
printf("\n area of shape(rectangle) : %f ",shape.area);

/* Returns value to OS */

return 0;

/******************************************************************
* end of unionexample.c
******************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Education & Research Department Page 35


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Summary of this exercise:


You have just learnt
• How to use the unions in C.

Deliverables of the exercise:


unionexample.c – the source code

3.4 Array of structures

Problem Description: Write a C program that will accept the following information for each
team in a cricket or a football league.

General Information
1. Team name
2. Number of wins
3. Number of losses

For a cricket team, add the following information:


1. No. of fours
2. No. of sixes
3. No. of runs
4. No. of ties

For a football team, add the following information:


1. No. of goals
2. No. of ties
3. No. of penalties

Enter this information for all of the teams in the league. Then reorder and print the list of
teams according to their win-lose records. Store the information in an array of structures,
where each array elements (i.e. each structure) contains the information for a single team.
Make use of a union to represent the variable information (either cricket or football) that is
included as a part of the structure. This union should itself contain two structures, one for
cricket – related statistics and the other for football related statistics.

3.5 Understanding Stacks

Objective: To understand how to implement stacks using linked list C

Step 1: Type the following C code in Vi Editor

/****************************************************************************
* Filename: stacklist.c
* Date: 30-Mar-2005

Education & Research Department Page 36


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* Author: E&R, Infosys


*
* Description: This file is the demo program used to demonstrate
* the implementation of stack using linked list in C
* This demo program creates an integer stack
* for the following operations:
* 1.creation of the stack
* 2.add an element to the stack(push)
* 3.remove an element from the stack(pop)
* 4.return the top most element
* 5.check for stack is empty
* 6.Empty the stack
****************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>

/* declare the node which contains the data and address of next node */

typedef struct node


{
int data;
struct node *next;
}NODE;

/* initialize the top pointer to NULL to indicate empty stack */

NODE *topptr=NULL;

/************************************************************
* Function push
*
* DESCRIPTION: adds an elment to the stack
*
* PARAMETERS:
* accepts the data to be pushed onto the stack
* RETURNS
* 1(true) if the given element is added to the stack 0(false) otherwise
*************************************************************/
int push(int x)
{

NODE *ptr;

Education & Research Department Page 37


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

//allocate a node
ptr = (NODE*) malloc(sizeof(NODE));

//in case of allocation failure return 0


if(!ptr)
return 0;

//else add the element to the top


else
{
ptr->data =x;
ptr->next =topptr;
topptr=ptr;
return 1;
}
}

/************************************************************
* Function pop
*
* DESCRIPTION: removes an element from the stack
*************************************************************/
void pop()
{
if(!topptr)
{
printf("\n Stack is empty");
return;
}
else
{
NODE* ptr=topptr;
topptr = topptr->next;
free(ptr);
}
}

/************************************************************
* Function top
*
* DESCRIPTION: returns the top most element of the stack
*
* RETURNS
* top element of the stack
*************************************************************/

Education & Research Department Page 38


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

int top()
{
if(!topptr)
{
printf("\n stack is empty");
exit(EXIT_FAILURE);

}
else
{
return topptr->data;
}
}

/************************************************************
* Function isEmpty
*
* DESCRIPTION: checks whether the stack is empty or not
*
* RETURNS
* 0 if stack is not empty 1 if stack is empty
*************************************************************/
int isEmpty()
{
return !topptr;
}

/************************************************************
* Function makeEmpty
*
* DESCRIPTION: clears the stack
*************************************************************/
void makeEmpty()
{
if(isEmpty())
return;
else
{
while(!isEmpty())
pop();
}
}

/************************************************************
* Function createStack
*

Education & Research Department Page 39


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* DESCRIPTION: creates a stack of integers got from keyboard


*************************************************************/
void createstack()
{
char choice='Y';
int data;
while(choice == 'Y')
{
printf("\n Enter the number to be added to stack: ");
scanf("%d",&data);
push(data);
printf("\n Element added to the stack");
printf("\n Press Y to continue any key to stop");
choice=getch();
}
}

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
int main(char **argv,int argc)
{
createstack();
printf("\n created Stack using linked list");
printf("\n printing the contents of the stack ");
printf("\n");
while(!isEmpty())
{
printf("\t %d",top());
pop();
}

/* Returns value to OS */

return EXIT_SUCCESS;
}

Step 2: Compile and execute the program using cc and a.out by default

Education & Research Department Page 40


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

Summary of this exercise:


You have just learnt
• How to implement stack using linked list in C
Deliverables of the exercise:
stacklist.c - the source code

3.6 Understanding Queues

Objective: To understand how to implement queues using linked list C

Step 1: Type the following C code in Vi Editor

/****************************************************************************
* Filename: queuelist.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstrate
* the implementation of queue using linked list in C
* This demo program creates an an integer queue
* for the following operations
* 1.creation of the queue
* 2.add an element to the queue
* 3.remove an element from the queue
* 4.return the front element
* 5.return the last element
* 6.check if queue is empty
* 7.printing the contents of the queue
****************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>

/* declare the node which contains the data and address of next node */

typedef struct node


{
int data;
struct node *next;
}NODE;

Education & Research Department Page 41


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/* initialize both front and rear pointers to NULL to indicate empty queue */

NODE *frontptr = NULL;


NODE *rear = NULL;

/************************************************************
* Function addElement
*
* DESCRIPTION: adds an elment to the queue
*
* PARAMETERS:
* accepts the data to be inserted onto the queue
* RETURNS
* 1(true) if the given element is added to the queue 0(false) otherwise
*************************************************************/
int addElement(int x)
{

NODE *ptr;
ptr = (NODE*) malloc(sizeof(NODE));
ptr->data =x;
ptr->next = NULL;

if(!ptr)
return 0;

if(!frontptr)
{
frontptr = rear = ptr;
return 1;

}
else
{
rear->next=ptr;
rear=rear->next;
return 1;
}
}

/************************************************************
* Function removeElement
*
* DESCRIPTION: removes an element from the queue
*************************************************************/
void removeElement()

Education & Research Department Page 42


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

{
/* Complete this function to remove element
from the front of queue*/
}

/************************************************************
* Function front
*
* DESCRIPTION: returns the first element of the queue
*
* RETURNS
* first element of the queue
*************************************************************/
int front()
{
/* Complete this function to return the
data of the node in front */
}

/************************************************************
* Function back
*
* DESCRIPTION: returns the last element of the queue
*
* RETURNS
* last element of the queue
*************************************************************/
int back()
{
/* Complete this function to return the data
of the node in the rear */
}

/************************************************************
* Function isEmpty
*
* DESCRIPTION: checks whether the queue is empty or not
*
* RETURNS
* 0 if queue is not empty 1 if queue is empty
*************************************************************/
int isEmpty()
{
return !frontptr;
}

Education & Research Department Page 43


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Function createQueue
*
* DESCRIPTION: creates an queue of integers got from keyboard
*************************************************************/
void createQueue()
{
char choice='Y';
int data;
while(choice == 'Y')
{
printf("\n Enter the number to be added to queue: ");
scanf("%d",&data);
addElement(data);
printf("\n Element added to the queue");
printf("\n Press Y to continue any key to stop");
choice=getch();
}

/************************************************************
* Function printQueue
*
* DESCRIPTION: prints the contents of the queue
*************************************************************/
void printQueue()
{
NODE* ptr=frontptr;
printf("\n");

while(ptr)
{
printf("%d\t",ptr->data);
ptr=ptr->next;
}
}

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
int main(char **argv,int argc)
{

Education & Research Department Page 44


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

//create an queue of integers

createQueue();
printf("\n created Queue using linked list");
printf("\n printing the contents of the Queue");
printf("\n");

//print the contents of the queue created


printQueue();

printf("\n First element %d ",front());


printf("\n Last element %d",back());

//add an element to the queue

addElement(-111);

//print the contents of the queue after adding the element


printf("\n");
printQueue();
printf("\n First element %d ",front());
printf("\n Last element %d",back());

//remove an element from the queue


removeElement();

//print the contents of the queue after removing an element


printf("\n");
printQueue();
printf("\n First element %d ",front());
printf("\n Last element %d",back());

/* Returns value to OS */

return EXIT_SUCCESS;
}

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to implement queue using linked list in C.
Deliverables of the exercise:
• queuelist.c - the source code

Education & Research Department Page 45


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

3.7 Operations on Files

Objective: To understand how to use files in C in text mode

Step 1: Type the following C code in vi Editor

/****************************************************************************
* Filename: linenumbers.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: demo program for reading a file and printing with line numbers
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>

/* declare the maximum length of a line of the text file */

#define MAX_LEN 1024

/************************************************************
* Function printWithLineNumbers
*
* DESCRIPTION: prints the given file with line numbers
*
* PARAMETERS:
* file to be printed (file pointer is given as input)
*************************************************************/
void printWithLineNumbers(FILE *fin)
{

/* declare character array to hold line read from the file */

char buff[MAX_LEN];

int linenumber = 1;

/* read the file line by line and print with line numbers onto the
console */

while (fgets(buff, MAX_LEN, fin) != NULL){

printf("%d : %s", linenumber,buff);


linenumber++;
}

Education & Research Department Page 46


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
int main(int argc,char* argv[])
{

/* declare a pointer to the file buffer */

FILE *fptr;

/* check for proper number of arguments to the file


an input file must be given as an argument
*/
if(argc != 2)
{
printf("\n Invalid usage");
printf("\n Usage %s filename ",argv[0]);
return EXIT_FAILURE;
}
else
{
/* open the file to be printed with line numbers
if unable to open the file exit with an error message
*/

if ((fptr = fopen(argv[1], "r")) == NULL)


{
printf("Cannot open %s for Reading. \n", argv[1]);
return EXIT_FAILURE;
}

/* print the given file with line


numbers using the function
printWithLineNumbers */

printWithLineNumbers(fptr);

/* close the file */

Education & Research Department Page 47


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

fclose(fptr);

/* Return a code back to OS!*/

return 0;

}
}

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use files in C in text mode

Deliverables of the exercise:


linenumbers.c - the source code

3.8 Operations on files using Command Line

Objective: To understand how to use files in C in text mode and how to get filenames from
Command line arguments

Step 1: Type the following C code in vi editor

/****************************************************************************
* Filename: copyfile.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
* Description: demo program for copying the contents of a text file to
another text file
****************************************************************************/
#include <stdio.h>

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

Education & Research Department Page 48


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

int main(int argc,char* argv[])


{
/* declare two file pointers to input and output file */
FILE *fp1, *fp2;
int c;

/* Check for proper number of arguments


* input file (source) and output file (destination) must be given
*/
if(argc != 3)
{
printf("\n Invalid usage ");
printf("\n proper usage is %s sourcefilename
destinationfilename",argv[0]);
/* Return a code back to OS!*/
return -1;
}
else
{
/* open both the files source and destination */
fp1 = fopen(argv[1], "r");
fp2 = fopen(argv[2], "w");

/* copy character by character */


while ((c = getc(fp1)) != EOF)
putc(c,fp2);

/* close both the files */


fclose(fp1);
fclose(fp2);

/* Return a code back to OS!*/


return 0;
}
}

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use files in C in text mode and using command line arguments for
Getting filenames

Deliverables of the exercise:


copyfile.c - the source code

Education & Research Department Page 49


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

3.9 Removal of Comment lines

Problem Description:
Write a C program which recreates a C program after removing all the comments from the
program. The name & path of the input & output files will be passed as command line
arguments.

3.10 Counting the number of words in a file

Problem Description:
Write a C Program that will count the number of words in a given text file. The name & path
of the input file will be passed as command line arguments.

3.11 Creation and maintenance of concordance

Problem Description:
Write a C program to create a concordance. The program will open a file and create an
concordance (for each word it should maintain a list of the line numbers in which the word
occurs). Thereafter the program will accept a word and prints the line numbers on which the
word appears.
Hint:
You need to create a linked list of concordance entries where each entry contains
A string and an array which maintains the linenumbers in which the word appears
Follow the algorithm given below
1. Read a line from the file
2. Split the line into words
3. Search in the linked list of concordance if the word is already there if it is already
there add to the array the new line number if it is not there then this linenumber
should be added as the first element in the array

Assumption: The text will be a maximum of 50 lines. A word appears only in a maximum of 50
lines

3.12 File handling – Bank application

Objective: To understand the file operations in binary mode


Step 1: Type the following C code in Vi Editor

/****************************************************************************
* Filename: personalinfo.c
* Date: 30-Mar-2005
* Author: E&R, Infosys

Education & Research Department Page 50


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

*
* Description: demo program for reading and writing to files in binary mode
* This demo program uses the following files
* personal.dat stores personal information such as first name, last name,
* account no., address of a customer
* accounts.dat stores account information such as account number, balance,
* and date of opening the account
****************************************************************************/

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

/* define the date structure */


struct date
{
int day;
int month;
int year;
};

typedef struct date DATE;

/* personal record */
struct Personal
{
char FirstName[25];
char LastName[25];
char Address[150];
int accno;

};

/* account record */
struct AccountInfo
{
int accno;
float Balance;
DATE acctopendate;
};

/* pointers to personal record and account record to find the


personal and account info for the given account number
*/

Education & Research Department Page 51


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

struct Personal *pers=NULL;


struct AccountInfo *acct=NULL;

/*
indicators where the account and personal information is found for the
given account number
*/

int acctinforead=0;
int persinforead=0;

/************************************************************
* Function createPersonalFile
*
* DESCRIPTION: creates the personal file
* reads the personal record from the user
* and stores it in binary mode
*************************************************************/
void createPersonalFile()
{

/* declare file pointer to the personal file */

FILE *fp;

int choice=1;

/* the structure a holds one record of personal information */

struct Personal a;

char FirstName[25];
char LastName[25];
char Address[150];
int accno;

/* open personal file in binary mode */

fp=fopen("personal.dat","wb");

while(choice)
{
printf("\n Enter personal details");
printf("\n enter accountno : ");
scanf("%d",&accno);

Education & Research Department Page 52


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

printf("\n enter First Name : ");


scanf("%s",FirstName);
printf("\n Enter Last Name : ");
scanf("%s",LastName);
printf("\n Enter the Address : ");
scanf("%s",Address);

/* assign values to the personal record */

a.accno=accno;
strcpy(a.Address,Address);
strcpy(a.FirstName,FirstName);
strcpy(a.LastName,LastName);

/* write the personal record to the file */

fwrite(&a,sizeof(struct Personal),1,fp);
fflush(stdin);
printf("\n continue/quit[1/0] :" );
scanf("%d",&choice);
}

/* close the personal file */


fclose(fp);
}

/************************************************************
* Function GetAccountInformation
*
* DESCRIPTION: gets the account information for the given
* account number
* PARAMETERS:
* account number to be searched
* RETURNS
* pointer to the account record with the given account no
*************************************************************/
struct AccountInfo* GetAccountInformation(int acct)
{

/* declare a file pointer to point to the accounts file */

FILE *fp;

/* open the accounts file */

Education & Research Department Page 53


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

fp=fopen("accounts.dat","rb");

/* check for file open error */

if(!fp)
{
printf("\n could not open accounts file");
return NULL;
}
else
{
/* read record by record and check for the given account no */
struct AccountInfo *a=
(struct AccountInfo*)malloc(sizeof(struct AccountInfo));
while(fread(a,sizeof(struct AccountInfo),1,fp))
{
if(a->accno == acct)
{
acctinforead=1 ;
return a;
}
}

/* record with given account number not found so return NULL */


return NULL;
}
}

/************************************************************
* Function GetPersonalInformation
*
* DESCRIPTION: gets the personal information for the given
* account number
* PARAMETERS:
* account number to be searched
* RETURNS
* pointer to the personal record with the given account no
*************************************************************/
struct Personal* GetPersonalInformation(int acct)
{
/* Complete the function to get Personal information
of a given account number*/

Education & Research Department Page 54


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Function createAccountFile
*
* DESCRIPTION: creates the accounts file
* reads the accounts record from the user
* and stores it in binary mode
*************************************************************/
void createAccountFile()
{

/* Complete the function to create Accounts file*/


}

/************************************************************
* Function printPersonalFile
*
* DESCRIPTION: prints the contents of the personal file
*
*************************************************************/

void printPersonalFile()
{
FILE *fp;

fp=fopen("personal.dat","rb");

printf("\n printing the contents of the personal file");

if(!fp)
{
printf("\n could not open personal file ");
}
else
{
struct Personal *a=
(struct Personal*)malloc(sizeof(struct Personal));
while(fread(a,sizeof(struct Personal),1,fp))
{
printf("\n Account Number : %d \t First Name : %s \t
Last Name : %s", a->accno,a->FirstName,a->LastName);
printf("\n Address : %s", a->Address );
}
}
}

Education & Research Department Page 55


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Function printAccountFile
*
* DESCRIPTION: prints the contents of the account file
*
*************************************************************/
void printAccountFile()
{
/* Complete the function to print the account file */
}

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
************************************************************/
int main(char **argv,int argc) {

int account;

/* create the personal and account files */


createPersonalFile();
createAccountFile();

/* print the contents of created accounts and personal files */

printPersonalFile();
printAccountFile();

/* get the account number to search */

printf("\n Enter the account number of the customer : ");


scanf("%d",&account);

/* get the personal and accounts record for the given account number */

pers = GetPersonalInformation(account);
acct = GetAccountInformation(account);

/* check if the customer information is read from both the files


if so print the customer information both personal and accounts
information
*/

Education & Research Department Page 56


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

if(persinforead && acctinforead)


{
printf("\n Details of customer with account number %d",account);
printf("\n Account Number : %d \t First Name : %s \t
Last Name : %s", acct->accno,pers->FirstName,
pers->LastName);
printf("\n Address : %s", pers->Address );
printf("\n Balance:%f \t Account open date :
%d / %d /%d",acct->Balance,acct->acctopendate.day,
acct->acctopendate.month,acct->acctopendate.year);

/* free the allocated personal and accounts record */


free(pers);
free(acct);
}
else
printf("\n No client matches that account number");

/* Returns value to OS */
return 0;
}

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use files in C in binary mode with structures

Deliverables of the exercise:


Personalinfo.c

3.13 File Handling - Employee details

Problem Description:

Write a C program to read the employee information and store it in a file using binary mode.
The file (emp.dat) should contain the following information Employee number, employee
name, years of service and birth date.

Next, it should then accept the mode of sorting from the user;
If user enters N it should sort by Employee number
If user enters B it should sort by birth date

The output should be written to another file got from command line arguments.

Education & Research Department Page 57


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

4 Assignments for Day 3

4.1 Storage class specifiers

Objective: To understand the concept behind storage class specifiers.

Background: C supports 4 different storage class specifiers (auto, static, register,


extern).The scope and life time of each storage class varies.

Step 1: Type the following program in vi editor

/*********************************************************************
* File name: scope.c
* Author: E&R Department, Infosys Technologies Limited
* Description: This file is to understand the concept of storage class
* specifiers in C.
*********************************************************************/
#include <stdio.h>

/*********************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*********************************************************************/
/*global declaration of variables */

int iNum = 20;


int fnIncrement(void); /* Proto typing of the sub function */

int main (int argc, char** argv)


{

{
/*declaration of local variables */
int iNum = 10;
register int iCount = 0;

Education & Research Department Page 58


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/* Use this statement in UNIX to clear the screen */


system("clear");
/* Display the result*/
printf( "Local Variable: %d\n",iNum);
printf("Register variable value: %d\n",++iCount);

} /*scope and lifetime of variable iNum and iCount ends here*/

printf("Global variable value: %d\n", iNum);


printf("Static variable value - first time: %d\n",fnIncrement());
printf("Static variable value-second time:%d\n",fnIncrement());
/* Return a code back to OS!*/
return 0;
}

/*********************************************************************
* end of scope.c
*********************************************************************/

/* Function fnIncrement( ) Definition */

int fnIncrement(void)
{
static int iNum;
return(++iNum);
}

/*********************************************************************
* end of function fnIncrement()
*********************************************************************/

Step 2: Compile and execute the program using “cc” and “scope.exe”

Compilation with –o option

Education & Research Department Page 59


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

In $ prompt type scope.exe, output appears

Summary of this exercise:


You have just learnt
• How to use storage classes
• How to use cc option

Deliverables of the exercise:


scope.c – the source code.
scope.exe – the executable file

Education & Research Department Page 60


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

4.2 Understanding Preprocessor directives

Objective: To understand the concept behind preprocessor directives.

Background: C supports preprocessor directives to expand the source code before


compilation. The directives are used for macro expansion, file Inclusion and conditional
compilation.

Step 1: Type the following program in vi editor

/************************************************************
* Filename: preproce.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: Uses #define preprocessor directive to define the macros with
arguments.
*************************************************************/

#include <stdio.h>

#define METHOD "ABS"


#define ABS(val) ((val) < 0 ? -(val) : (val))
#define MAX_LEN 8
#define NEGATIVE_NUM -10

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv)


{
char str[4] = METHOD;
int iArray[MAX_LEN];
int iCount;

printf("The orignal values in array:\n");

Education & Research Department Page 61


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

for (iCount=0; iCount<MAX_LEN; iCount++)


{
iArray[iCount] = (iCount + 1) * NEGATIVE_NUM;
printf("array[%d]: %d\n", iCount, iArray[iCount]);
}
printf("\nApplying the %s macro:\n", str);
for (iCount=0; iCount<MAX_LEN; iCount++)
{
printf("ABS(%d): %3d\n", iArray[iCount], ABS(iArray[iCount]));
}
/* Return a code back to OS!*/
return 0;
}
/*********************************************************************
* end of preproce.c
*********************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use #define preprocessor directive

Deliverables of the exercise:


• preproce.c – the source code

Education & Research Department Page 62


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

4.3 Understanding Conditional Compilation

Objective: To understand the concept of conditional compilation.

Background: The conditional compilation preprocessor directives are basically used for
compiling portion of the code in the given program. There are many preprocessor directives
available in C for conditional compilation like #ifdef, #ifndef, #endif, #if, #elif, and #else.

Step 1: Type the following program in vi editor

/************************************************************
* Filename: cond.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: Program is used to demonstrate the use of conditional
compilation
*************************************************************/

#include <stdio.h>

#define C_LANG ‘C’


#define B_LANG ‘B’
#define NO_ERROR 0

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv)


{
/* Conditional Compilation directives are used */

#if C_LANG == ‘C’ && B_LANG == ‘B’


/* Undefined C_Lang */
#undef C_LANG
#define C_LANG "I know the C language.\n"

Education & Research Department Page 63


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/* Undefined B_Lang */
#undef B_LANG
#define B_LANG "I know BASIC.\n"
printf("%s%s", C_LANG, B_LANG);

#elif C_LANG == ‘C’


#undef C_LANG
#define C_LANG "I only know C language.\n"
printf("%s", C_LANG);

#elif B_LANG == ‘B’


#undef B_LANG
#define B_LANG "I only know BASIC.\n"
printf("%s", B_LANG);
#else
printf("I don't know C or BASIC.\n");
#endif
/* Return a code back to OS!*/
return NO_ERROR;
}
/*********************************************************************
* end of cond.c
*********************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use conditional compilation preprocessor directives.

Deliverables of the exercise:


cond.c – the source code

Education & Research Department Page 64


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

5 Assignments for Day 4

5.1 Array operations using pointers

Problem Description:
Write a C program to accept 2 integer arrays and perform the following operations using
functions and pointers.
• Add two arrays and return the resultant array
• Check whether the two arrays are equal and return true/false based on the result
• Remove the duplicates from the array and return the reduced size

Hint:
Declare three functions with the following prototypes
int* add(int * ,int * );
int compare(int* ,int *);
int removeduplicates(int*,int);

Step 1: Declare two integer arrays


Step 2: Get the values for these two arrays from keyboard.
Step 3: Call the appropriate functions

5.2 Understanding function pointers

Objective: To understand the usage of function pointers

Step 1: Type the following program in vi editor

/************************************************************
* Filename: fnptr.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstate
the usage of function pointers.
*************************************************************/

#include <stdio.h>

/* Prototype Declaration of functions */

Education & Research Department Page 65


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

int fnSquare(int);
int fnCube(int);

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
int main (int argc, char**argv)
{
/* Declaration of function pointers pointing to function
whose argument is integer and returns an integer */
int (*fnPtr)(int);

/* Declaring 2 integer variables */


int iNum1, iNum2=2;

/* Assigning function starting address to fnPtr */


fnPtr = fnSquare;

/* calling function through fnPtr */


iNum1 = (*fnPtr)(iNum2);
/* printing the return value from fnSquare( ) */
printf("\nThe Square of %d is %d\n", iNum2,iNum1);

/* Assigning function starting address to fnPtr */


fnPtr = fnCube;

/* calling function through fnPtr */


iNum1 = (*fnPtr)(iNum2);

/* printing the return value from fnCube( ) */


printf("\nThe Cube of %d is %d\n", iNum2,iNum1);

/* Returns value to OS */
return 0;
}

/* Function Definition */
int fnSquare(int iNum)
{
return iNum*iNum;

Education & Research Department Page 66


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

int fnCube(int iNum)


{
return iNum*iNum*iNum;
}

/******************************************************************
* end of fnptr.c
******************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to use function pointers

Deliverables of the exercise:


fnptr.c – the source code

5.3 Passing Function as an Argument

Objective: To learn how to pass function as an argument to another function

Step 1: Type the following program in vi editor

/****************************************************************************
* Filename: fnarg.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This file is the demo program used to demonstate
How to pass function as an argument to another function
****************************************************************************/
#include <stdio.h>

/* Prototype Declaration of functions */


int fnSquare(int);
int fnCube(int);
int fnSum(int i, int (*fp)(int));

/************************************************************
* Function main
*

Education & Research Department Page 67


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

* DESCRIPTION: Entry point for the program


* PARAMETERS:
* int argc - no of cmd line parameters
* char **argv - cmd line parameters
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/

int main (int argc, char**argv)


{

/*Sum of cubes and squares*/


/*Declaration of Variables */
int iResult=0, iCount;
int iArr[3] = {1, 2, 3};

/*Calling the fnSum( ) function by passing fnSquare( )address as a


parameter in a for loop to calculate sum of the square of
numbers in an array iArr */

for (iCount=0; iCount<3; iCount++)


iResult += fnSum(iArr[iCount], &fnSquare);

/* Printing the Resultant Sum */


printf("\n The Result of Sum of Squares of 1,2,3 is %d\n", iResult);

/* Reinitializing the variable iResult to 0 */


iResult = 0;

/* Calling the fnSum() function by passing fnCube()address as


a parameter in a for loop to calculate sum of the Cubes of
numbers in an array iArr */

for (iCount=0; iCount<3; iCount++)


iResult += fnSum(iArr[iCount], &fnCube);

/* Printing the Resultant Sum */


printf("\n The Result of Sum of Cubes of 1,2,3 is %d\n",iResult);

/* Returns value to OS */
return 0;
}

/* Function Definition */
int fnSum(int iNum, int (*fp)(int))
{

Education & Research Department Page 68


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

return (*fp)(iNum);
}

int fnSquare(int iNum)


{
return iNum*iNum;
}

int fnCube(int iNum)


{
return iNum*iNum*iNum;
}

/******************************************************************
* end of fnptr.c
******************************************************************/

Step 2: Compile and execute the program using cc and a.out by default.

Summary of this exercise:


You have just learnt
• How to pass function as an argument to another function using function pointers

Deliverables of the exercise:


• fnarg.c – the source code

5.4 Array of function pointers

Problem Description: Write a C Program which declares an array of function pointers. The
function pointers should be such that they can point to a function accepting two integers and
returning an integer. Write four functions, add(), multiply(), divide() and subtract() which
accept two integers and return an integer. Initialize the array with the address of these four
functions and call the functions using the function pointers in the array.

Hint: Declare an array of function pointers having the same prototype as:
int (*fnptr[4])(int,int);
Assign the corresponding add, multiply, divide and subtract function’s addresses to the
elements of the function pointer array

Education & Research Department Page 69


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

5.5 Array of void pointers

Problem Description:
Write a C program to create an array of 4 void pointers.
1. The first element of this array is a pointer to an integer.
2. The second element of this array is a pointer to a function that accepts integer and
returns integer.
3. The third element of this array is a pointer to an array of 10 floating point values.
4. The last element of the array is a pointer to string. Print the content of each array
element.

Hint:
Declare an array of void pointers as void* vArr[4];
To assign different type of elements to this array, apply the following code snippet:
int iNum = 10;
float fNum = 10.5;
float fArr[ ]={1.5, 1.5, 1.5};
char *str = “Hello”;

To initialize:
vArr[0] = &iNum;
vArr[1] = &fNum;
vArr[2] = fArr;
vArr[3] = str;

While dereferencing convert to corresponding types like: *((int*)vArr[0])

5.6 Run-time errors in C (1)

Problem Description:
Type the given C code in vi editor and compile and run the program. Identify the runtime
error in the given C code and rectify the same

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/****************************************************************************
* Filename: memoryerror1.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
* Description: This program actually tries to concatenate eight different
* strings to a single string but produces an run time error
****************************************************************************/

Education & Research Department Page 70


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
************************************************************/
int main(char **argv,int argc)
{
/* create an array of eight strings */

char *str[8] = {"one", "two", "three", "four",


"five", "six", "seven", "eight"};

/* concat points to the concatenated string */


char *concat = 0;

int total_size = 0;
int i = 0;

/* find the total length of the final string (concatenated) */


for (i = 0; i < 8; i++)
total_size += strlen(str[i]);

/* allocate memory for the concatenated string */


concat = (char*) malloc(total_size);

/* concatenate strings one by one */


for (i = 0; i < 8; i++) {

strcat(concat, str[i]);
free(str[i]);
}

/* print the concatenated string and then free memory


allocated for it */

printf("%s\n", concat);
free(concat);

/* return success code to OS */


return 0;
}

Education & Research Department Page 71


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

5.7 Run-time errors in C (2)


Problem Description:
Type the given C code in vi editor and compile and run the program. Identify the runtime
error in the given C code and rectify the same.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/****************************************************************************
* Filename: memoryerror2.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This program actually tries to create an array of pointers
* each element points to an array but produces an run time
error
****************************************************************************/

/************************************************************
* Function createMemory
*
* DESCRIPTION: creates memory for input n integers
*
* PARAMETERS:
* input size n
* RETURNS
* a pointer to the block of integers
*************************************************************/
int *createMemory(int n) {

return (int *) malloc(n + 5);

/************************************************************
* Function freeMemory
*
* DESCRIPTION: frees the block pointed by ptr
*
* PARAMETERS:
* pointer to the block to be freed
*************************************************************/

Education & Research Department Page 72


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

void freeMemory(int *ptr) {

free(ptr + 5);

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
************************************************************/
int main(char **argv,int argc)
{

/* an array to hold sizes of the arrays to be created */


int num[10] = {1, 0, 2, 0, 3, 0, 4, 0, 5, 0};

/* an array of pointers should point to 10 different arrays */

int *ptr[10];

int i;

/* create an array and assign the pointer to the pointer array ptr */

for(i = 0; i < 10; i++) {


ptr[i] = createMemory(num[i]);
}

/* free each and every array allocated */

for(i = 0; i < 10; i++) {


freeMemory(ptr[i]);
}

/* return success code to OS */

return 0;
}

Education & Research Department Page 73


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

5.8 Run-time errors in C (3)


Problem Description:
Type the given C code in vi editor and compile and run the program. Identify the runtime
error in the given C code and rectify the same.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/****************************************************************************
* Filename: memoryerror3.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: This program actually tries to create an matrix of size
* 13X13 but produces an run time error
****************************************************************************/

/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
************************************************************/
int main(char **argv,int argc)
{
/* define the number of rows and columns of the matrix */
int size = 13;

/* create an array of 13 pionters(13 rows) */


int** table = (int**) malloc(size * sizeof(int*));

int i, j;

/* for each row in the matrix */


for(i = 1; i <= size; i++)
{
/* create space for columns for each row */
table[i] = (int*) malloc(size * sizeof(int));

for (j = 1; j <= size; j++)


{
table[i][j] = i * j;
}

Education & Research Department Page 74


© Infosys Technologies Limited
C Programmin Lab Guide Version 1.0

/* deallocating the matrix */

free(table);

for (i = 1; i <= size; i++)


{
free(table[i]);
}

/* return success code to OS */


return 0;
}

Education & Research Department Page 75


© Infosys Technologies Limited