Sunteți pe pagina 1din 22

C Lab Assignments

Page 1 of 22

SESSION 1
1.1 Execute the following program and rectify the errors. #include <stdio.h> main () { printf (Hello C World \n ); printf ( tHello \ t c \t World \n ) ; printf ( Logic Option s computer centre\n); printf ( Logic Options \vcomputer\vcentre\n); printf ( \ \ ); printf ( % % \n ); } Execute the following program and find out the result. #include <stdio.h> main ( ) { unsigned short int i = 65535; short int j=32767; printf (i value = % u\n, i); i = i +1; printf (after incrementing i value = %u \n, i); printf (j value = %d\n, j); j = j +1; printf ( j value using % %d modifier = %d \n, j); printf ( j value using % %u modifier = %d \n, j); } Study the following program. Experiment with different inputs. # include <stdio.h> main ( ) { int i; scanf (%o, & i); printf (the value in decimal is %d \n, i); printf (the value in hexadecimal is %x\n, i); } Study the given program which uses scanf and identify the problem # include <stdio.h> main ( ) {
Page 2 of 22

1.2

1.3

1.4

int i; float f; scanf (%d %d, & i ); scanf (%d %f, &f, &i ); scanf (%d, i ); } 1.5 Execute the following program and study the output. # include <stdio.h> main ( ) { float salary; printf ( Enter your salary : ); scanf(%f, &salary); printf(f\n, salary); printf(%6.2f\n, salary); printf(%2.2f\n, salary); printf(%6f\n, salary); } Experiment with the following program: # include <stdio.h> main ( ) { int i; printf( Enter a value between 65 and 91:); scanf (%d, &i); printf (Equivalent character = %c\n, i); printf (the data in the various formats are \n); printf (in decimal %d \n, i); printf (in octal % o \n, i); printf (in hexadecimal %x \n, i); } Find out the difference between the output of the two printf statements in the following program: # include <stdio.h> main ( ) { printf (%d \n, -1); printf (%u \n, -1); }
Page 3 of 22

1.6

1.7

SESSION 2
2.1 Study the following program and record your observations (pending) #include <stdio.h> main () { int i = 25 printf ( initial i value = %d \n, i); printf (%d %d %d \n, i++, i, i - -); printf (now i value = % d \n, i); printf (%d %d %d \n, i + 2, ++i, i); printf (now i value = %d \n, i); } The following program uses a # define constant to compute the interest for amount entered by the user. #include <stdio.h> define RATE 15 main ( ) { float amount; printf (Enter amount : ); scanf (%f, &amount); printf (\n\n Interest amount = %f \n, (amount * RATE)/100); } Compile the above program (2.2), using the following option in cc command and observe the final printf statement. $ cc E <source file> The following program is used to print the value of EOF defined in the header file stdio.h #include <stdio.h> main( ) { prinf (EOF = %d \n, EOF); } What will happen when you compile the above program (2.4) after deleting the include directive? How will you solve the problem without giving the include directive? Execute the following program and study its output. #include <stdio.h> main( )
Page 4 of 22

2.2

2.3

2.4

2.5 2.6

{ int i = 72 putchar (i++); putchar (i - =4); putchar (i + =7); putchar (i --); putchar (i + 4); putchar (\n); } 2.7 Explain the output of the following program. #include <stdio.h> main( ) { int i=10, j=17; float f=6.74; printf (%d \n, i+j /f ); printf (%f \n, i+j /f ); printf (%d \n, ( i+j )/f ); printf (%f \n, ( i+j ) /f); printf (%d \n, f /i+j); printf (%f \n, f /i+j ); } Write a program using getchar( ) which will accept two single digit numbers and display their sum. Write a program which accepts two integers and displays the quotient and remainder when the first is divided by the second.

2.8 2.9

Page 5 of 22

SESSION 3
3.1 Execute the following program and set it right to get the intended result. / * The following program prints the multiplication table for 5 */

#include <stdio.h> main( ) {


int i=0; while ( i ! = 11) printf ( 5 x %d = %d \n, i++, (5 * i++) ); } 3.2 The following program is used to count the number of characters, words and lines in a file redirected to it as input. $ a.out < filename Check the result with the Unix command wc (word count). #include <stdio.h> #define INSIDE 1 #define OUTSIDE 0 main ( ) { int ch, char_count=0, word_count=0, line_count=0, flag=OUTSIDE; while ( ( ch=getchar ( ) ) !=EOF) { char_count++; if (ch = = \n) line_count++; if (ch = = | | ch = = \n | | ch = = \t) flag=OUTSIDE; else if (flag = = OUTSIDE) { flag = INSIDE; word_count++; } } printf ( No. of characters = %d \n, char_count); printf ( No. of words = % d \n, word_count); printf ( No. of lines = % d \n, line_count); } 3.3 What will happen if the variable ch in the above program is declared as a character?
Page 6 of 22

3.4

Accept a character from the input stream and determine the case of the letter (upper / lower case). Also determine its position in the alphabet (d is the fourth alphabet). Take care to display an appropriate message if the character is not an alphabet. Accept a year from the user and check for leap year. Hint: A leap year is divisible by 4 and not divisible by 100,or is divisible by 400 Note: Try the above program using a nested if statement and an if statement with a compound condition.

3.5

3.6

Accept three positive integers from the user representing three sides of a triangle. Determine whether they form a valid triangle. Hint: In a triangle, the sum of any two sides must always be greater than the third side. Write a program using while loop to effectively solve the problem based on an idea given in the Scientific American in January 1984 (article entitle Hailstones). It states that any positive integer n will go to 1 if treated in the following fashion. If n is even, it is divided by 2. If odd, it is multiplied by 3 and then incremented by 1. This process continues using the generated number as the new value of n. It ceases only when n finally reaches 1. Note: No one has yet found an integer that does not go to 1 using this process, but no mathematician in the world has been able to prove that such a number does not exist.

3.7

3.8

Write a program to find the factorial of a given positive integer. Hint : n! = n (n-1)(n-2)..(1) Where0! = 1; 1! = 1

3.9.

The Russian peasant problem is a method of multiplying two numbers. Write the Numbers in two columns 13 Divide the first by 2 and multiply the second by 2 (ignoring remainders) 6 Repeat till first column is 1 Add all numbers in the second column if the 3 corresponding first column is odd. The answer in the example above is 1 13 * 12 + 48 + 96 = 156

12 + 24 48+ 96 + (Use

3.10 3.11

Write a program to count the number of occurrences of each vowel in an input stream if statement)

Write a program which accepts input from stdin and displays it on the stdout after replacing each tab by \ t, each backspace by \b , and each backslash by \ \. This makes tabs and backspaces visible in an unambiguous way. Hint : Use while loop
Page 7 of 22

3.12

n + n2
2!

n3
3!

n4
4!

Accept n as an integer and find the value for the first 10 terms 3.13 Use the ternary operator to find the absolute value of an integer.

Page 8 of 22

SESSION 4
4.1 4.2 4.3 Write a program containing a loop that counts from 1 to 1000. It should print the value of the variable (used in the iteration) for every 100 iterations. Write a program to find the value of a number x raised to the power y, where x and y are to be accepted from the user (use for loop). Write a program that examines all numbers from 1 to 999 displaying those numbers where the sum of the cubes of the individual digits equals the number of itself (Armstrong numbers). Example 4.4 4.5 4.6 : 371 = 33 + 73 + 13 563 = 53 + 63 + 33

Product a list of prime numbers from 1 to 999 Hint: A prime number is one that is divisible only by 1 and itself. Write a program to find the number of occurrences of each of the vowels in the input stream (use switch case) Write a program which would accept two integers and compute their Greatest Common Divisor (GCD) . The GCD of two numbers is the same as the GCD of one the numbers and the difference between the two numbers (use do. while loop). Example : GCD of 26, 65 is the same as the GCD of 26, 39 which is the same as the GCD of 26, 13 which is the same as the GCD of 13, 13 Thus GCD of 26, 65 is 13

4.7

Write a program which accepts a number n, finds and displays the sum of integers 1 to 2, then 1 to 3, then 1to 4 etc., until it displays sum of integers 1 to n. Example : If the input is 5, then the output will be 3, 6, 10, 15

4.8

Write a program to reverse an integer (use do. . . while loop) Example : If the input is 7931, then the output will be 1397 The reversed number should be stored in an integer Hint : n%10 can be used to extract the last digit.

4.9

Fibonocci numbers form an infinite series 1 1 2 3 5 8 13 Each number is the sum of the previous two numbers
Page 9 of 22

4.10 4.11 4.12

Write a program which will generate the series to n number of terms where n is accepted from the user. Write a program that converts newline, formfeed, tab and vertical tab characters into visible escape sequences like \n, \f, \t and \v (Use switch case) Write a Program to check if a given integer is a Palindrome (numbers which read the same from either side-example: 83938). Write a program which uses the method used in the following example to generate palindromic numbers. Take a number reverse it add the two reverse again add again 174 471 645 546 1191 1911 3102 2013 5115 a Palindrome

4.13 4.14

Twin primes are defined as two consecutive odd numbers that are prime. Print all Twin primes between 1 and 1000. Print ASCII values from 32 to 127 in octal, hexadecimal, decimal and character formats.

Page 10 of 22

SESSION 5
5.1 Initialize an integer, array of size 12 with the following values, (each initialized to the maximum no. of days in a month). Accept month and year as integer from the user and display the maximum day in that month. Note : Care has to be taken in case of leap year (Feb will be 29 days) 31 28 31 30 31 30 31 31 30 31 30 31 Accept five integers from the user in an integer array. Print them in the reverse order of storing (5th integer will be displayed first, 4th as second and so on) Write a program to accept the marks of ten students. The average of the mark secured by a student in two subjects is calculated and stored in an integer array. The maximum mark in each subject is 100. Introduce necessary validation when accepting the marks for each of the 10 students. Use the same information for the following problems (5,4,5.5 & 5.6) Find the number of persons whose average lies in the range. < 40 >= 40 to < 60 >= 60 to < 80 >= 80 to < 100 == 100 > 100 (invalid mark!) Sort the marks in ascending / descending order as per users wish. If the array already sorted before the loop is completed, then stop and display the sorted and the number of passes taken. Print the maximum and minimum marks in the class. Find out the frequency of alphabets from an input stream (ignore cases). Option your program (use redirection). Convert a decimal number to any given base. Accept two sorted arrays and merge sort them into another array. The third array should be large enough to accommodate the first two arrays. Hint : Compare each element from the two arrays and store the smaller in the third. Increment its array subscript. Continue till one of the arrays is exhausted. Store the rest of the numbers in the remaining array into the third array.

5.2 5.3

5.4

5.5 5.6 5.7 5.8 5.9

Page 11 of 22

SESSION 6
6.1 6.2 6.3 Write a function to check if the year passed as a parameter is a leap year or not. The function should return a Boolean value (either True or False). Write a function absolute (int i ) which returns the absolute value of an integer that is passed as a parameter. Write a function fact (int n), whch returns the factorial of the parameter n. Use this function to find: nc = n! . r ( n r)! r! Write a function which takes two parameters, the first being temperature and second being a character to indicate whether the temperature is in Fahrenheit or Celsius. If the temperature is in Fahrenheit, the function should calculate and return the Celsius equivalent. Similarly, a Celsius temperature should be converted to Fahrenheit. Hint 6.5 6.6 6.7 : * * Celsius = (5.0 / 9.0 * (Fahrenheit 32.0) Fahrenheit ((9.0 / 5.0 ) * Celsius + 32.0 )

6.4

Write a function to determine whether the three parameters passed to it form a valid triangle. (Refer problem 3.6 ) [return true or false ] Write a function to check whether a given integer is a palindrome (Refer problem 4.12) Write a function which returns the GCD of two numbers. Find the LCM where m x n . LCM = GCD (m, n) (Refer problem 4.6)

6.8 6.9

Use the above function to find LCM and GCD of three numbers. Write a function which takes an integer as a parameter and returns 1 if the number is prime, else 0 (Use GCD)

Page 12 of 22

SESSION 7
7.1 Execute the following program and note down your observations. #include <stdio.h> void fun(int, int); int i=5, j=10; main( ) { int i, j; for ( i = 0, j = 0; i < 5; i++) { j++ printf (from main( ) the value of i = %d \t j = %d \n, i, j ); fun( i , j ); printf (after fun( ) the value of i = %d \t j = %d \n, i, j); } } void fun (int i , int j) { printf( from fun( ) the value of i = %d \t the value of j = %d \n, i, j); i++; j++; } Execute the following program and note down your observations. #include <stdio.h> void fun(int, int); main( ) { static int j = 10 ; int i = 0 ; for (i = 0; i < 5; i++, j++) { printf (main before fun i = %d \ t j = %d \n, i , j); fun (i, j); printf (main after fun i = %d \ t j = %d \n, i , j); } } void fun ( int k, int j) { static int i = 50; i++ j++ printf (from fun( ) i = %d \ t j = %d \ t k = % d \n, i , j , k ); }
Page 13 of 22

7.2

7.3 7.4 7.5 7.6

Write a program that reads in a line of text of a character basis and then writes out the characters in reverse order (Use recursion). Write a function to find the GCD between two integers. (Use recursion) Reverse a given number using recursion. Find the binary form of a decimal number using a recursive function.

Page 14 of 22

SESSION 8
8.1 Write a piglatin word generator program. A piglatin word is formed from a word by transposing the first letter to the end of the word and then adding the letter a. Curses ursesca Strings tringssa Programming rogrammingpa Note : The program can be extended to get a line from the user and then changing to piglatin. Write a function lower (char str [ ] ) which converts the characters in the string str from uppercase to lowercase. Write a function reverse (char str [ ]) which reverses the string str . Write a function capitalize (char str [ ] ) which converts the first character of every word to uppercase, rest to lowercase. Write a function right (char str2[ ] , char str1[ ], int n) which copies the right most n characters from the string str1 to string str2. Write a function mid (char str2 [ ], char str1 [ ], int n) which copies the leftmost n characters from the string str1 to the string str2. Write a function mid (char str2 [ ], char str1 [ ], int n, int p) which copies n characters of the string str1 from the position p into the string str2. Combine all the above three functions (Q. 8.5 8.7) into one function by passing an extra parameter r right; l left; m mid. Write a function squeeze (char str2 [ ], char str [ ]) which deletes each character in the string str2 that matches any character in the string str1. Write a function atoi (char str [ ]) which converts the string str into its equivalent number (integer). This converted integer value has to be returned to the caller. Write a function atof (char str [ ]) which converts the string str into its equivalent float integer. This converted float value has to be returned to the caller. Accept a line. If a word is a, and if the following word begins with a vowel, then change a to an. Write a function which will delete a pattern from a string. Write a program to search for a patter in a given string and replace it with another pattern.
Page 15 of 22

8.2 8.3 8.4 8.5 8.6

8.7 8.8 8.9 8.10 8.11 8.12 8.13 8.14

SESSION 9
9.1 Accept 10 integer values into an array. Write a program which accepts a number and stores the corresponding cells address in a pointer variable if the number is found in the array, else stores a NULL in that pointer variable. Write a program to get a string and a character from the user. It should search for the first occurrence of the character in the string and from there it should print the rest of the characters using a char pointer. Write a program to implement your own version of realloc using malloc and free. Declare an array of 10 char pointers. Accept a line upto 10 word. Store the address of every cell having the start of a word into the array. Then the print the strings using these pointers. Write a program to search and replace in a string using pointers and functions provided by the C library. Find the word frequency of the words the, and, of, a and have in a given text. Find the length of a given string using pointers. Hint: Increment the pointer till it points to NULL and then use pointer arithmetic.

9.2

9.3 9.4

9.5 9.6 9.7

Page 16 of 22

SESSION 10
10.1 Write a pointer version for the following string functions. a. strcat b. strcpy c. strncpy d. strcmp e. strncmp f. atoi g. itoa Write a program to print the command line arguments in the reverse order. Write a program to receive two integer values and an operator as command line arguments to do calculation. The result of this calculation has to be displayed on the screen. $ a.out 2 + 3 5 $ Extend the above program to evaluate the command line arguments using the reverse polish notation (rpn). A rpn is nothing but operands followed by the operators. If there are n operands there will be n- 1 operators for that. $ a.out 5 - 5 + 2 5 5 -2 + 2 $ Write a program to convert the day of the year to the day of a month and vice versa. 1993 60 < - > Mar 1 1992 61 < - > Mar 1 Hint : Use two-dimensional array to store the maximum number of days in each month depending on the leap / non leap year. Declare a char pointer array of 100 elements. Accept input from a file (redirected by giving a.out<filename) after allocating memory for it. Store the address returned by malloc in the array. Now display the contents of the file. If the file has 90 lines, determine how much memory has been saved when compared to having two dimensional array to do the same exercise. Write generalized functions for reading and printing a matrix. (The matrix could be of any dimension). Also write a function to add two matrices and store the result in a third matrix. Write a program with a function which will find both the smallest and largest integers in a given integer array. Decide on the number of parameters and their types yourself. Write a program to solve simultaneous equations of two unknows.

10.2 10.3

10.4

10.5

10.6

10.7 10.8 10.9

Page 17 of 22

SESSION 11
11.1 Write a program that will compare two files character by character. The file names can be accepted as command line parameters. Stop on the occurrence of the first difference and report its position and the line number. Write a program to number lines of a file and create a new output file. Write a program to implement your own version of fgets ( ) and fputs( ). Write a program that will concatenate files. The program will be invoked in the following manner. $ a.out target_file source1 source2 source3source n Write a program that will receive a file name and a string from the command line and delete all occurrences of the string from the file and place the result in a separate file. Note: Introduce an option for interactive replacement Write a program to find the longest line in a given file. (filename given as a command line parameter). Write a program to check whether the word following a . starts with a capital letter in a given text file.

11.2 11.3 11.4

11.5

11.6 11.7

Page 18 of 22

SESSION 12 & 13
Note : for the following programs possible errors have to be trapped and proper messages have to be displayed on the screen. 12.1 Write a program to implement your own version of Unix command cp. Note : introduce on option-I to ensure that accidental overwriting does not take place. 12.2 12.3 12.4 12.5 Write your own version of the Unix command uniq which eliminates consecutive redundant lines within a file. Write your own version of the Unix command grep, which is used to find a pattern in a file (pattern and file name should be accepted as command line parameters). Modify the above programs to accept I as an option to fold upper and lowercase together so that case distinctions are not made during pattern searching. Add f option to the above program to get patterns from a file specified as a next parameter in the command line. $ a.out f pattern_file input_file 12.6 12.7 12.8 Write a program to implement a simple version of the #define preprocessor directive. Write a program to implement the Unix tail and head commands. Write a program to display the login id, name and home directory from the password file. Hint : The password file is in / etc directory. 12.9 Write a program which converts lowercase letters to uppercase in the same file without using a temporary file. Accept filename as a command line parameter.

Page 19 of 22

SESSION 14
Create a structure library to contain the following; Book code Book Name Author Name Subject Use this structure for the following problems(14.1 - 14.4 ) 14.1 Initialize the above structure with the following value and the display the contents after initialization. C001, THE SPIRIT OF C, MULLISH COOPER, C 14.2 14.3 14.4 14.5 Get information about ten books from the user and store it in an array of structures. Write a query program to query on book name. Write a program to accept book details and store them in a file. Write a query program to query program to query on subject. The information must be read from the file you have crated above. Write a program to count the number of occurrences of each vowel in the input stream. Hint : Use the following structure. struct vowel_count { char vowel; int count; } occur [5 ]; Write a function to validate the date passed as a parameter. Hint: Use the following structure: struct date_tag { unsigned int yy; unsigned int mm; unsigned int dd; }; Write a function to find the difference between two dates passed as parameters. Write a program with functions to accept data in an array of structures and write it onto a file. Using the data file created in the above problem, determine the number of records stored in the file and allocate memory for exactly that many and display the data. (call to fread should be only once)

14.6

14.7 14.8 14.9

Page 20 of 22

SESSION 15
Use the library file created and the structure defined in the session 14 (for 15.1 to 15.6) 15.1 15.2 15.3 15.4 15.5 Write a program to read the contents of the file into a link list and display the information. Also write functions to delete and insert data. Write a program to create a link list sorted on subject and print book code and book name for a specific subject. Modify your data addition program (written in the previous session) to check for duplications using link list. Write a program to print the library details in the ascending order (alphabetical ) of book name Write a program to print a file in reverse order (last line should be displayed first and so on) using link list.

Write a program to accept data from a file into an o rdered linked list. Write functions which will add and delete record from the list and finally write the data back into the file. 15.6 Read a text file into a structure having two way links (previous node, next node) to display the contents page by page assuming 22 lines per page. Options must be provided to see the first, last, previous and next page. 15.7 15.8 Write a program to find the frequency of words in a text file accepted as a command line parameter. Use Linked list to stimulate a stack.

Page 21 of 22

SESSION 16
Write a program that will encode and decode the contents of a text file by replacing each character with its ones complement. Hint: Ones complement of a complement is the original character Count the number of 0s and 1s in an unsigned integer. Write a program to crypt / decrypt a file by accepting a password from the user.. Hint : A ^ (A ^ B) = B Implement the functions defined in ctype.h as macros in your program 1. tolower ( c ) 2. toupper ( c ) 3. isprint ( c ) 4. isxdigit ( c ) Write macros for the following situations :average (x, y ) to calculate average between x and yfeet_to_meters (x) to convert x feet to metersmeters_to_feet (x) to convert x meters to feetfind the absolute value Hint : Meters = feet * 0.3048 Write a program to find the twos complement form of an integer 16.1 Find out if the fifth bit of an nteger is set. If not, set it to 1.

Page 22 of 22

S-ar putea să vă placă și