CS19002 Programming and Data Structures Laboratory, Section 5 |
Spring 2007 |
Exercise 1 | Exercise 2 | Exercise 3 | Exercise 4 | Exercise 5 | |
Solution 1 | Solution 2 | Solution 3 | Solution 4 | Solution 5 | |
Show all | Hide all |
Click on the links above
Exercise 1
Write a C program that counts the total number of characters in a file, the name of which is read from the user.
Solution 1
#include <stdio.h> int main () { char fname[100], c; FILE *fp; unsigned int size = 0; printf("Enter a file name: "); scanf("%s", fname); fp = (FILE *)fopen(fname,"r"); if (fp != NULL) { while (!feof(fp)) { fscanf(fp,"%c",&c); ++size; } } printf("Size of the file = %u bytes\n", size); }Exercise 2
Write a C program that converts a text file to upper case and stores the converted text in another file. The input and output file names should be supplied as command line parameters. The output file name may be omitted. In that case, the output is written to a file with the name obtained by appending .uc to the input file name.
Example
$ ./a.out infile.txt outfile.txt $ ./a.out infile.txtSolution 2
#include <stdio.h> int main ( int argc, char *argv[] ) { FILE *ifp, *ofp; char c, fname[100]; if (argc == 1) { fprintf(stderr, "Too few arguments\n"); exit(1); } ifp = (FILE *)fopen(argv[1],"r"); if (argc >= 3) { ofp = (FILE *)fopen(argv[2],"w"); } else { sprintf(fname,"%s.uc", argv[1]); ofp = (FILE *)fopen(fname,"w"); } if ((ifp != NULL) && (ofp != NULL)) { while (!feof(ifp)) { fscanf(ifp,"%c",&c); if ((c >= 'a') && (c <= 'z')) c += 'A' - 'a'; fprintf(ofp,"%c",c); } fclose(ifp); fclose(ofp); } exit(0); }Exercise 3
Write a function that accepts a positive integer n as input, and creates and returns a linked list of n random integers in the range 0 to 999.
Solution 3
typedef struct _node { int data; struct _node *next; } node; node *randList ( unsigned int n ) { node *p = NULL, *head; int i; if (n == 0) return NULL; head = p = (node *)malloc(sizeof(node)); p -> data = rand() % 1000; for (i=1; i<n; ++i) { p -> next = (node *)malloc(sizeof(node)); p -> next -> data = rand() % 1000; p = p -> next; } p -> next = NULL; return head; }Exercise 4
Write a function that, upon input a linked list, prints the items stored in the list from beginning to end.
Solution 4
typedef struct _node { int data; struct _node *next; } node; void printList ( node *p ) { while (p != NULL) { printf("%d ", p -> data); p = p -> next; } }Exercise 5
Write a recursive function that, upon input a linked list, prints the items stored in the list in the reverse order, that is, from end to beginning.
Solution 5
typedef struct _node { int data; struct _node *next; } node; void printListRev ( node *p ) { if (p == NULL) return; printListRev(p -> next); printf("%d ", p -> data); }