C Programming LabGuide FP2005 Ver1.0
C Programming LabGuide FP2005 Ver1.0
Lab Guide
Page i
Table Of Contents
1 BACKGROUND........................................................................................................1
Page ii
4.3 UNDERSTANDING CONDITIONAL COMPILATION ................................................................... 63
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.
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
At the prompt, type vi and a filename with extension .c. Example: vi hello.c
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
*************************************************************/
/************************************************************
* End of hello.c
*************************************************************/
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.
Step 6: An executable file a.out is created. At the prompt type the name of the executable
file to run the program
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
Background: C has the built-in header file ctype.h, which provides all the character handling
functions.
/************************************************************
* 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
*************************************************************/
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);
/*********************************************************************
* end of case.c
*********************************************************************/
Step 2: Compile and execute the program using cc and a.out by default.
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
Use exit(0) built-in function to exit from the program and include <stdlib> header file
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
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
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
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
Problem Description:
Write a C program to count the number of characters, words and lines in the given text.
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
/************************************************************
* Filename: ptraccess.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* Description: Demo program to understand the concept of pointers
*************************************************************/
#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
*************************************************************/
/* Initialization of variables */
ch = ‘A’;
iNum = 7;
fNum = 123.45;
/*********************************************************************
* end of ptraccess.c
*********************************************************************/
Step 2: Compile and execute the program using cc and a.out by default
/************************************************************
* 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
*
* 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*/
printf("\n");
/*********************************************************************
* end of ptr_string.c
*********************************************************************/
Step 2: Compile and execute the program using cc and a.out by default
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
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
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.
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.
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.
If the character is found, return a character pointer which points to that matched position
character else return NULL
/****************************************************************************
* 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>
struct date
{
int day;
int month;
int year;
};
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
****************************************************************************/
DATE d = {10,2,1974};
struct employee e ={100,"Venkat"};
e.birthdate = d;
e.yearsofservice =10;
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.
/****************************************************************************
* 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>
#define SIZE 2
/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
Trainee trainee_batch[SIZE];
Trainee tmp;
int i;
int index1,index2;
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);
}
/* Returns value to OS */
return 0;
}
/******************************************************************
* end of arrayOfStructure.c
******************************************************************/
Step 2: Compile and execute the program using cc and a.out by default
/****************************************************************************
* 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
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>
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
*************************************************************/
/************************************************************
* 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);
/************************************************************
* 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)
{
/************************************************************
* 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;
}
}
/************************************************************
* 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;
return ptr;
}
/************************************************************
* Function findprev
*
/************************************************************
* 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
*************************************************************/
NODE* prev;
NODE* ptr;
NODE* nn;
prev = findprev(x);
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)
{
/************************************************************
* Function removefirst
*
* DESCRIPTION: removes the first element of the linked list
*************************************************************/
void removefirst()
{
if(!head)
return;
else
{
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
* RETURNS
* an integer value indicating the choice entered by the user
*************************************************************/
int menu()
{
int 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;
while((choice=menu()) != 12)
{
switch(choice)
{
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);
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:
/******************************************************************
end of linkedlist.c
*******************************************************************/
Step 2: Compile and execute the program using cc and a.out by default.
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)
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
/****************************************************************************
* 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 iCount;
printf("\n Total number of arugments is : %d ", argc);
printf("\n The command line arguments are ");
printf("\n");
/* Returns value to OS */
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.
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.
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.
/****************************************************************************
* 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>
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;
};
/************************************************************
* Function main
*
* DESCRIPTION: Entry point for the program
* RETURNS: 0 on success, Non-Zero value on error
*************************************************************/
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);
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.
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
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.
/****************************************************************************
* Filename: stacklist.c
* Date: 30-Mar-2005
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<conio.h>
/* declare the node which contains the data and address of next node */
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;
//allocate a node
ptr = (NODE*) malloc(sizeof(NODE));
/************************************************************
* 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
*************************************************************/
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
*
/************************************************************
* 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
/****************************************************************************
* 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 */
/* initialize both front and rear pointers to NULL to indicate empty queue */
/************************************************************
* 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()
{
/* 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;
}
/************************************************************
* 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)
{
createQueue();
printf("\n created Queue using linked list");
printf("\n printing the contents of the Queue");
printf("\n");
addElement(-111);
/* Returns value to OS */
return EXIT_SUCCESS;
}
Step 2: Compile and execute the program using cc and a.out by default.
/****************************************************************************
* 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>
/************************************************************
* 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)
{
char buff[MAX_LEN];
int linenumber = 1;
/* read the file line by line and print with line numbers onto the
console */
/************************************************************
* 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[])
{
FILE *fptr;
printWithLineNumbers(fptr);
fclose(fptr);
return 0;
}
}
Step 2: Compile and execute the program using cc and a.out by default.
Objective: To understand how to use files in C in text mode and how to get filenames from
Command line arguments
/****************************************************************************
* 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
*************************************************************/
Step 2: Compile and execute the program using cc and a.out by default.
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.
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.
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
/****************************************************************************
* Filename: personalinfo.c
* Date: 30-Mar-2005
* Author: E&R, Infosys
*
* 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>
/* 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;
};
/*
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()
{
FILE *fp;
int choice=1;
struct Personal a;
char FirstName[25];
char LastName[25];
char Address[150];
int accno;
fp=fopen("personal.dat","wb");
while(choice)
{
printf("\n Enter personal details");
printf("\n enter accountno : ");
scanf("%d",&accno);
a.accno=accno;
strcpy(a.Address,Address);
strcpy(a.FirstName,FirstName);
strcpy(a.LastName,LastName);
fwrite(&a,sizeof(struct Personal),1,fp);
fflush(stdin);
printf("\n continue/quit[1/0] :" );
scanf("%d",&choice);
}
/************************************************************
* 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)
{
FILE *fp;
fp=fopen("accounts.dat","rb");
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;
}
}
/************************************************************
* 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*/
/************************************************************
* Function createAccountFile
*
* DESCRIPTION: creates the accounts file
* reads the accounts record from the user
* and stores it in binary mode
*************************************************************/
void createAccountFile()
{
/************************************************************
* Function printPersonalFile
*
* DESCRIPTION: prints the contents of the personal file
*
*************************************************************/
void printPersonalFile()
{
FILE *fp;
fp=fopen("personal.dat","rb");
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 );
}
}
}
/************************************************************
* 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;
printPersonalFile();
printAccountFile();
/* get the personal and accounts record for the given account number */
pers = GetPersonalInformation(account);
acct = GetAccountInformation(account);
/* Returns value to OS */
return 0;
}
Step 2: Compile and execute the program using cc and a.out by default.
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.
/*********************************************************************
* 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 */
{
/*declaration of local variables */
int iNum = 10;
register int iCount = 0;
/*********************************************************************
* end of scope.c
*********************************************************************/
int fnIncrement(void)
{
static int iNum;
return(++iNum);
}
/*********************************************************************
* end of function fnIncrement()
*********************************************************************/
Step 2: Compile and execute the program using “cc” and “scope.exe”
/************************************************************
* 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>
/************************************************************
* 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
*************************************************************/
Step 2: Compile and execute the program using cc and a.out by default.
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.
/************************************************************
* 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>
/************************************************************
* 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
*************************************************************/
/* Undefined B_Lang */
#undef B_LANG
#define B_LANG "I know BASIC.\n"
printf("%s%s", C_LANG, B_LANG);
Step 2: Compile and execute the program using cc and a.out by default.
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);
/************************************************************
* 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>
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);
/* Returns value to OS */
return 0;
}
/* Function Definition */
int fnSquare(int iNum)
{
return iNum*iNum;
/******************************************************************
* end of fnptr.c
******************************************************************/
Step 2: Compile and execute the program using cc and a.out by default.
/****************************************************************************
* 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>
/************************************************************
* Function main
*
/* Returns value to OS */
return 0;
}
/* Function Definition */
int fnSum(int iNum, int (*fp)(int))
{
return (*fp)(iNum);
}
/******************************************************************
* end of fnptr.c
******************************************************************/
Step 2: Compile and execute the program using cc and a.out by default.
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
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;
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
****************************************************************************/
/************************************************************
* 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 */
int total_size = 0;
int i = 0;
strcat(concat, str[i]);
free(str[i]);
}
printf("%s\n", concat);
free(concat);
#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) {
/************************************************************
* Function freeMemory
*
* DESCRIPTION: frees the block pointed by ptr
*
* PARAMETERS:
* pointer to the block to be freed
*************************************************************/
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)
{
int *ptr[10];
int i;
/* create an array and assign the pointer to the pointer array ptr */
return 0;
}
#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;
int i, j;
free(table);