C questionare

Embed Size (px)

Citation preview

  • 7/30/2019 C questionare

    1/22

    C

    Lab Assignments

    Page 1 of 22

  • 7/30/2019 C questionare

    2/22

    SESSION 1

    1.1 Execute the following program and rectify the errors.#include 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 );

    }

    1.2 Execute the following program and find out the result.#include 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);

    }

    1.3 Study the following program. Experiment with different inputs.# include main ( ){

    int i;scanf (%o, & i);printf (the value in decimal is %d \n, i);printf (the value in hexadecimal is %x\n, i);

    }

    1.4 Study the given program which uses scanf and identify the problem# include main ( ){

    Page 2 of 22

  • 7/30/2019 C questionare

    3/22

    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 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);

    }

    1.6 Experiment with the following program:# include 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);

    }

    1.7 Find out the difference between the output of the two printf statements in the followingprogram:

    # include main ( ){

    printf (%d \n, -1);printf (%u \n, -1);

    }

    Page 3 of 22

  • 7/30/2019 C questionare

    4/22

    SESSION 2

    2.1 Study the following program and record your observations (pending)#include main (){

    int i = 25printf ( 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);

    }

    2.2 The following program uses a # define constant to compute the interest for amountentered by the user.#include define RATE 15main ( ){

    float amount;printf (Enter amount : );scanf (%f, &amount);printf (\n\n Interest amount = %f \n, (amount * RATE)/100);

    }

    2.3 Compile the above program (2.2), using the following option in cc command and observethe final printf statement.

    $ cc E

    2.4 The following program is used to print the value of EOF defined in the header file stdio.h#include main( )

    {prinf (EOF = %d \n, EOF);

    }

    2.5 What will happen when you compile the above program (2.4) after deleting the includedirective? How will you solve the problem without giving the include directive?

    2.6 Execute the following program and study its output.#include main( )

    Page 4 of 22

  • 7/30/2019 C questionare

    5/22

    {int i = 72putchar (i++);

    putchar (i - =4);putchar (i + =7);putchar (i --);putchar (i + 4);putchar (\n);

    }

    2.7 Explain the output of the following program.#include 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 );

    }

    2.8 Write a program using getchar( ) which will accept two single digit numbers and display

    their sum.

    2.9 Write a program which accepts two integers and displays the quotient and remainderwhen the first is divided by the second.

    Page 5 of 22

  • 7/30/2019 C questionare

    6/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 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 fileredirected to it as input.

    $ a.out < filename

    Check the result with the Unix command wc (word count).

    #include #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

  • 7/30/2019 C questionare

    7/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 anappropriate message if the character is not an alphabet.

    3.5 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 acompound condition.

    3.6 Accept three positive integers from the user representing three sides of a triangle. Determinewhether they form a valid triangle.

    Hint: In a triangle, the sum of any two sides must always be greater than the third side.

    3.7 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 positiveinteger 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. Thisprocess continues using the generated number as the new value of n. It ceases only when nfinally reaches 1.

    Note: No one has yet found an integer that does not go to 1 using this process, but nomathematician in the world has been able to prove that such a number does not exist.

    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 12 + Divide the first by 2 and multiply the second by 2

    (ignoring remainders) 6 24 Repeat till first column is 1 Add all numbers in the second column if the 3 48+

    corresponding first column is odd. The answer in the example above is 1 96 +

    13 * 12 + 48 + 96 = 156

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

    3.11 Write a program which accepts input from stdin and displays it on the stdout after replacing eachtab by \ t, each backspace by \b , and each backslash by \ \. This makes tabs and backspacesvisible in an unambiguous way.Hint : Use while loop

    Page 7 of 22

  • 7/30/2019 C questionare

    8/22

    3.12 n + n2 + n3 + n4 .2! 3! 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

  • 7/30/2019 C questionare

    9/22

    SESSION 4

    4.1 Write a program containing a loop that counts from 1 to 1000. It should print the value of thevariable (used in the iteration) for every 100 iterations.

    4.2 Write a program to find the value of a number x raised to the power y, where x and y are to beaccepted from the user (use for loop).

    4.3 Write a program that examines all numbers from 1 to 999 displaying those numbers where thesum of the cubes of the individual digits equals the number of itself (Armstrong numbers).

    Example : 371 = 33 + 73 + 13

    563 = 53 + 63 + 33

    4.4 Product a list of prime numbers from 1 to 999Hint: A prime number is one that is divisible only by 1 and itself.

    4.5 Write a program to find the number of occurrences of each of the vowels in the input stream (useswitch case)

    4.6 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 differencebetween 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 theGCD of 26, 13 which is the same as theGCD 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 1to 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 integerHint : n%10 can be used to extract the last digit.

    4.9 Fibonocci numbers form an infinite series

    1 1 2 3 5 8 13Each number is the sum of the previous two numbers

    Page 9 of 22

  • 7/30/2019 C questionare

    10/22

    Write a program which will generate the series to n number of terms where n is accepted fromthe user.

    4.10 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)4.11 Write a Program to check if a given integer is a Palindrome (numbers which read the same from

    either side-example: 83938).

    4.12 Write a program which uses the method used in the following example to generate palindromicnumbers.

    Take a number 174

    reverse it 471

    add the two 645reverse again 546

    add again 1191

    1911

    3102

    2013

    5115 a Palindrome

    4.13 Twin primes are defined as two consecutive odd numbers that are prime. Print allTwin primes between 1 and 1000.

    4.14 Print ASCII values from 32 to 127 in octal, hexadecimal, decimal and character formats.

    Page 10 of 22

  • 7/30/2019 C questionare

    11/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 themaximum 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

    5.2 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)

    5.3 Write a program to accept the marks of ten students. The average of the mark secured by astudent in two subjects is calculated and stored in an integer array. The maximum mark in eachsubject is 100. Introduce necessary validation when accepting the marks for each of the 10students.

    Use the same information for the following problems (5,4,5.5 & 5.6)

    5.4 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!)

    5.5 Sort the marks in ascending / descending order as per users wish. If the array already sortedbefore the loop is completed, then stop and display the sorted and the number of passes taken.

    5.6 Print the maximum and minimum marks in the class.

    5.7 Find out the frequency of alphabets from an input stream (ignore cases). Option your program(use redirection).

    5.8 Convert a decimal number to any given base.

    5.9 Accept two sorted arrays and merge sort them into another array. The third array should be largeenough 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 ofthe numbers in the remaining array into the third array.

    Page 11 of 22

  • 7/30/2019 C questionare

    12/22

    SESSION 6

    6.1 Write a function to check if the year passed as a parameter is a leap year or not. The functionshould return a Boolean value (either True or False).

    6.2 Write a function absolute (int i ) which returns the absolute value of an integer that is passed as aparameter.

    6.3 Write a function fact (int n), whch returns the factorial of the parameter n. Use this function tofind:

    nc = n! .r ( n r)! r!

    6.4 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 inFahrenheit, the function should calculate and return the Celsius equivalent. Similarly, a Celsiustemperature should be converted to Fahrenheit.

    Hint : * Celsius = (5.0 / 9.0 * (Fahrenheit 32.0)* Fahrenheit ((9.0 / 5.0 ) * Celsius + 32.0 )

    6.5 Write a function to determine whether the three parameters passed to it form a valid triangle.(Refer problem 3.6 ) [return true or false ]

    6.6 Write a function to check whether a given integer is a palindrome (Refer problem 4.12)

    6.7 Write a function which returns the GCD of two numbers. Find the LCM wherem x n .

    LCM = GCD (m, n)

    (Refer problem 4.6)

    6.8 Use the above function to find LCM and GCD of three numbers.

    6.9 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

  • 7/30/2019 C questionare

    13/22

    SESSION 7

    7.1 Execute the following program and note down your observations.#include 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++;

    }

    7.2 Execute the following program and note down your observations.#include

    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/30/2019 C questionare

    14/22

    7.3 Write a program that reads in a line of text of a character basis and then writes out the charactersin reverse order (Use recursion).

    7.4 Write a function to find the GCD between two integers. (Use recursion)7.5 Reverse a given number using recursion.

    7.6 Find the binary form of a decimal number using a recursive function.

    Page 14 of 22

  • 7/30/2019 C questionare

    15/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 - ursescaStrings - tringssaProgramming - rogrammingpa

    Note : The program can be extended to get a line from the user and then changing topiglatin.

    8.2 Write a function lower (char str [ ] ) which converts the characters in the string str fromuppercase to lowercase.

    8.3 Write a function reverse (char str [ ]) which reverses the string str .

    8.4 Write a function capitalize (char str [ ] ) which converts the first character of every word touppercase, rest to lowercase.

    8.5 Write a function right (char str2[ ] , char str1[ ], int n) which copies the right most n charactersfrom the string str1 to string str2.

    8.6 Write a function mid (char str2 [ ], char str1 [ ], int n) which copies the leftmost n characters fromthe string str1 to the string str2.

    8.7 Write a function mid (char str2 [ ], char str1 [ ], int n, int p) which copies n characters of thestring str1 from the position p into the string str2.

    8.8 Combine all the above three functions (Q. 8.5 8.7) into one function by passing an extraparameter r right; l left; m mid.

    8.9 Write a function squeeze (char str2 [ ], char str [ ]) which deletes each character in the string str2that matches any character in the string str1.

    8.10 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.

    8.11 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.

    8.12 Accept a line. If a word is a, and if the following word begins with a vowel, then change a toan.

    8.13 Write a function which will delete a pattern from a string.

    8.14 Write a program to search for a patter in a given string and replace it with another pattern.

    Page 15 of 22

  • 7/30/2019 C questionare

    16/22

    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 aNULL in that pointer variable.

    9.2 Write a program to get a string and a character from the user. It should search for the firstoccurrence of the character in the string and from there it should print the rest of the charactersusing a char pointer.

    9.3 Write a program to implement your own version of realloc using malloc and free.

    9.4 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 thearray. Then the print the strings using these pointers.

    9.5 Write a program to search and replace in a string using pointers and functions provided by the Clibrary.

    9.6 Find the word frequency of the words the, and, of, a and have in a given text.

    9.7 Find the length of a given string using pointers.Hint: Increment the pointer till it points to NULL and then use pointer arithmetic.

    Page 16 of 22

  • 7/30/2019 C questionare

    17/22

    SESSION 10

    10.1 Write a pointer version for the following string functions.

    a. strcat b. strcpy c. strncpy d. strcmpe. strncmp f. atoi g. itoa

    10.2 Write a program to print the command line arguments in the reverse order.

    10.3 Write a program to receive two integer values and an operator as command line arguments to docalculation. The result of this calculation has to be displayed on the screen.

    $ a.out 2 + 35$

    10.4 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 operandsthere will be n- 1 operators for that.

    $ a.out 5 - 5 + 25 5 - 2 +2

    $

    10.5 Write a program to convert the day of the year to the day of a month and vice versa.1993 60 < - > Mar 11992 61 < - > Mar 1Hint : Use two-dimensional array to store the maximum number of days in eachmonth depending on the leap / non leap year.

    10.6 Declare a char pointer array of 100 elements. Accept input from a file (redirected by givinga.out

  • 7/30/2019 C questionare

    18/22

    SESSION 11

    11.1 Write a program that will compare two files character by character. The file names can beaccepted as command line parameters. Stop on the occurrence of the first difference and reportits position and the line number.

    11.2 Write a program to number lines of a file and create a new output file.

    11.3 Write a program to implement your own version of fgets ( ) and fputs( ).

    11.4 Write a program that will concatenate files. The program will be invoked in the followingmanner.$ a.out target_file source1 source2 source3source n

    11.5 Write a program that will receive a file name and a string from the command line and delete alloccurrences of the string from the file and place the result in a separate file.

    Note: Introduce an option for interactive replacement

    11.6 Write a program to find the longest line in a given file. (filename given as a command lineparameter).

    11.7 Write a program to check whether the word following a . starts with a capital letter in a giventext file.

    Page 18 of 22

  • 7/30/2019 C questionare

    19/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 Write your own version of the Unix command uniq which eliminates consecutive redundant lineswithin a file.

    12.3 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).

    12.4 Modify the above programs to accept I as an option to fold upper and lowercase together so thatcase distinctions are not made during pattern searching.

    12.5 Add f option to the above program to get patterns from a file specified as a next parameter in thecommand line.

    $ a.out f pattern_file input_file

    12.6 Write a program to implement a simple version of the #define preprocessor directive.

    12.7 Write a program to implement the Unix tail and head commands.

    12.8 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 usingatemporary file. Accept filename as a command line parameter.

    Page 19 of 22

  • 7/30/2019 C questionare

    20/22

    SESSION 14

    Create a structure library to contain the following;

    Book codeBook NameAuthor NameSubject

    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 afterinitialization.

    C001, THE SPIRIT OF C, MULLISH COOPER, C

    14.2 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.

    14.3 Write a program to accept book details and store them in a file.

    14.4 Write a query program to query program to query on subject. The information must be readfrom the file you have crated above.

    14.5 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 ];

    14.6 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;

    };

    14.7 Write a function to find the difference between two dates passed as parameters.

    14.8 Write a program with functions to accept data in an array of structures and write it onto a file.

    14.9 Using the data file created in the above problem, determine the number of records stored in thefile and allocate memory for exactly that many and display the data. (call to fread should be onlyonce)

    Page 20 of 22

  • 7/30/2019 C questionare

    21/22

    SESSION 15

    Use the library file created and the structure defined in the session 14 (for 15.1 to 15.6)15.1 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.

    15.2 Write a program to create a link list sorted on subject and print book code and book name for aspecific subject.

    15.3 Modify your data addition program (written in the previous session) to check for duplicationsusing link list.

    15.4 Write a program to print the library details in the ascending order (alphabetical ) of book name

    15.5 Write a program to print a file in reverse order (last line should be displayed first and so on) usinglink list.

    Write a program to accept data from a file into an o rdered linked list. Write functions which will add anddelete 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 thecontents page by page assuming 22 lines per page. Options must be provided to see the first, last,previous and next page.

    15.7 Write a program to find the frequency of words in a text file accepted as a command lineparameter.

    15.8 Use Linked list to stimulate a stack.

    Page 21 of 22

  • 7/30/2019 C questionare

    22/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) = BImplement the functions defined in ctype.h as macros in your program1. tolower ( c )2. toupper ( c )3. isprint ( c )4. isxdigit ( c )

    Write macros for the following situations :average (x, y ) to calculate averagebetween x and yfeet_to_meters (x) to convert x feet to metersmeters_to_feet (x) to

    convert x meters to feetfind the absolute valueHint : Meters = feet * 0.3048

    Write a program to find the twos complement form of an integer16.1 Find out if the fifth bit of an nteger is set. If not, set it to 1.

    Page 22 of 22