You are on page 1of 59

REVIEW QUIZ

#1 Through the following function, swap (a, b), the values of 2 variables passed to it have to be swapped : swap (a, b) int a, b; { int temp; temp = a; a = b; b = temp; return (a); return (b); }
NIIT SEM Q/CPR/CR/SESSION 5/1/VER06/95

REVIEW QUIZ (Contd.)


The function is invoked from main () and the values of variables x an y are passed to it. a. Is the function syntactically correct? b. Is the function logically correct? c. Will the function interchange the values of the variables x and y? If not, give the correct code.

NIIT

SEM Q/CPR/CR/SESSION 5/2/VER06/95

REVIEW QUIZ (Contd.)


#2 Study the following C statements of 2 program files : /* Program A * / /* Program B */ main () int x = 0; { count (charac, str) char c, locate [20]; { count (&c, locate); int I = 0; printf (%d, x); while(str [i] != \0) } if (str [i+ + ] = = charac) x+ + ; } What declarations have to be included / modified in each of these programs ?
NIIT SEM Q/CPR/CR/SESSION 5/3/VER06/95

REVIEW QUIZ (Contd.)


#3 A program called find expects one value from the command line which is a string. How are these parameters accepted by the program? Give all parameter declarations and their values when the following command is entered at the $ prompt: Find The

NIIT

SEM Q/CPR/CR/SESSION 5/4/VER06/95

REVIEW QUIZ (Contd.)


#4 Given the following return statement of a function called ret_val (): return (float) rate * unit_sold; which of the following declaration (s) for the function ret_val() should be included in the main program? a. void ret_val (); b. int ret_val (); c. float ret_val (); d. No declaration is necessary

NIIT

SEM Q/CPR/CR/SESSION 5/5/VER06/95

REVIEW QUIZ (Contd.)


#5 Given that a char array has to be assigned the string: LOOKUP PAGE state whether true or false. The array may be declared to be either auto or extern or declared globally, but not static.

NIIT

SEM Q/CPR/CR/SESSION 5/6/VER06/95

REVIEW QUIZ (Contd.)


#6 What are the values of a and b after the fourth time the following function is invoked? find_type (c) char c; { static int a = 0, b; b = 0; if ((c > = A) && (c < = Z)) a+ + ; else if (( c > = a) && (c < = z)) b+ + ; } Assume that the values of c passed in the 4 function calls are : AbcD
NIIT SEM Q/CPR/CR/SESSION 5/7/VER06/95

SOLUTIONS TO REVIEW QUIZ


#1 a. Yes b. No, because a function cannot return 2 values. c. No, since it is a call by value, the values of x and y get copied to memory variables a and b respectively. The changes to these are not reflected in x and y. A call by reference should be made instead of a call by value. So, the correct code is :

NIIT

SEM Q/CPR/CR/SESSION 5/8/VER06/95

SOLUTIONS TO REVIEW QUIZ (Contd.)


swap (a, b) /* interchange *a and *b */ int *a, *b; { int temp; temp = *b; *b = *a; *a = temp; } #2 In program A: extern int x; /* within main () */ In program B: char *charac, str []; /* after count (charac, str) */
NIIT SEM Q/CPR/CR/SESSION 5/9/VER06/95

SOLUTIONS TO REVIEW QUIZ (Contd.)


#3 The declarations are : main (argc, argv) int argc; char *argv []; Value of argc will be 2. Value of argv [0] will be find. Value of argv [1] will be The. #4 c. #5 False #6 The variable a will be 2. The variable b will be O (b gets initialized each time the function is invoked).

NIIT

SEM Q/CPR/CR/SESSION 5/10/VER06/95

SPL SESSION
Objectives At the end of this session, you will be able to: Write C programs that invoke functions through : Call by reference Call by value Write C programs using void type functions and functions that return values of different data types Explain the structure of the function main () and write C programs which handle command line parameters

NIIT

SEM Q/CPR/CR/SESSION 5/11/VER06/95

SPL SESSION (Contd.)


Objectives (Contd.) State the features of the following data storage types : Auto Static Extern and use these in single and multiple C program files Use the following standard string comparison functions of c: strcmp () strcpy () strcat () strlen ()
NIIT SEM Q/CPR/CR/SESSION 5/12/VER06/95

SPL SESSION (Contd.)


Objectives (contd.) Use the following string to numeric conversion function: atoi () atof () Use the following functions for formatting strings in memory: sscanf () sprintf ()

NIIT

SEM Q/CPR/CR/SESSION 5/13/VER06/95

PARAMETERS OF A FUNCTION
Data that the function must receive when called from another function A function may/may not have parameters Example main () { disp_head (); } disp_head () /* no parameters */ { printf (EMPLOYEE REPORT); } disp_head () does not have parameters
NIIT SEM Q/CPR/CR/SESSION 5/14/VER06/95

PARAMETERS OF A FUNCTION (Contd.)


Example The following function has two parameters, a and b: main () { : sum (x, y); } sum (a, b) /*2 parameters */ int a, b; { int value; value = a + b; }
NIIT SEM Q/CPR/CR/SESSION 5/15/VER06/95

PARAMETERS OF A FUNCTION (Contd.)


Parameters are of same data type as that of values received Declarations must be made outside opening brace for function Parameters may be passed : By value By reference

NIIT

SEM Q/CPR/CR/SESSION 5/16/VER06/95

INVOKING FUNCTIONS THROUGH CALL BY VALUE


Values of variables passed get copied into the memory locations of the parameters Example Contents of main () { num1 num2 operator : 2 3 * calc (num1, num2,operator : 2 3 * } val1 val2 oper calc (val1, val2, oper) int val1, val2; char oper; { : }
NIIT SEM Q/CPR/CR/SESSION 5/17/VER06/95

INVOKING FUNCTIONS THROUGH CALL BY REFERENCE


Addresses of variables passed get copied into the memory locations of the parameters Example Contents of num1 num2 operator main () 105 120 13 { 2 3 + : addresses passed calc ( &num1, 105 120 130 &num2 ,&oper); val1 val2 oper : }

NIIT

SEM Q/CPR/CR/SESSION 5/18/VER06/95

INVOKING FUNCTIONS THROUGH CALL BY REFERENCE (Contd.)


2 calc (val1, val2, oper) int *val1, *val2; val1 points to num1 char *oper; val2 points to num2 { : : printf (%d,*val1+ *val1); } + 3

NIIT

SEM Q/CPR/CR/SESSION 5/19/VER06/95

INVOKING FUNCTIONS THROUGH CALL BY REFERENCE (Contd.)


Arrays are inherently passed through call by reference Example main () { int str [10]; : stringfunc (str); } stringfunc (number_list) int number_list [ ]; /* no subscript*/ { : }
NIIT SEM Q/CPR/CR/SESSION 5/20/VER06/95

INVOKING FUNCTIONS THROUGH CALL BY REFERENCE (Contd.)


OR stringfunc (number_list) int number_list [ 10 ]; /* same size as num_array*/ { : } OR stringfunc (number_list) int *number_list: /* int type pointer because */ /* number_list is int type array */ { : }
NIIT SEM Q/CPR/CR/SESSION 5/21/VER06/95

RETURNING VALUES FROM FUNCTIONS


The return Statement Sends back one value to the caller Example sum (a, b) int a, b; { return a + b; /* value of a + b returned */ } Different values may be returned based on conditions

NIIT

SEM Q/CPR/CR/SESSION 5/22/VER06/95

RETURNING VALUES FROM FUNCTIONS


Example diff (a, b) int a, b; { if (a > b) return a - b; else if (b > a) return b - a; else return O; } Default return value is int type Also transfers control back to calling function
NIIT SEM Q/CPR/CR/SESSION 5/23/VER06/95

RETURNING VALUES FROM FUNCTIONS (Contd.)


Other data types may also be returned Example main () { float sum (); /* function declared float */ float x, y, value ; scanf (%f, &x, &y); fflush (stdin); value = sum (x, y); printf (Total is %f \n, value); }

NIIT

SEM Q/CPR/CR/SESSION 5/24/VER06/95

RETURNING VALUES FROM FUNCTIONS (Contd.)


float sum (a, b) float a, b; { return a+b; } /*function declared float */

Function must be declared as type of value it returns

NIIT

SEM Q/CPR/CR/SESSION 5/25/VER06/95

Void TYPE FUNCTIONS


Functions that simply return control to caller without returning a value Example main () { void sum (); /* sum () declared void */ float x, y; scanf (%f %f, &x, &y); sum (x, y); } void sum (a, b) float a, b; { printf (%f, a + b); return; /* sends control back */ }
NIIT SEM Q/CPR/CR/SESSION 5/26/VER06/95

THE main () FUNCTION


Standard type of parameters are used to receive arguments from command line main (argc, argv) int argc; char *argv [ ]; { : } argv 100 106 125 135 argv [0] 100 argv [1] 106 : : : Pointer to an Array
NIIT SEM Q/CPR/CR/SESSION 5/27/VER06/95

THE main () FUNCTION (Contd.)


Usage of Command Line Arguments Upper Abracadabra (entered on command line to execute a program called upper) argc =2 (2 words entered at command line)

argv [0] 100

u p

r /0

(first word on command line) argv [1] 106 A b r a c a d a b r a /0 (second word on command line, i.e. first argument) Pointer to an Array (char type)
NIIT SEM Q/CPR/CR/SESSION 5/28/VER06/95

DATA STORAGE TYPES


Storage Created Initialized Can be Type accessed auto Each time Can be initia- Only in the (default) the function lized at time function in is invoked of declarawhich tion or later declared static The first time Initialized at Only in the the function time of decl- function in is invoked aration so which that the value declared is not reset; static arrays can also be initialized
NIIT SEM Q/CPR/CR/SESSION 5/29/VER06/95

DATA STORAGE TYPES (Contd.)


Storage Created Initialized Type extern Created at Initialized the time where declwhere decl- ared global ared as global since membut not where ory is reserdeclared ext- ved then ern Can be accessed In any function in same /different program file

NIIT

SEM Q/CPR/CR/SESSION 5/30/VER06/95

STANDARD STRING-HANDLING FUNCTIONS


STRCMP () Compares 2 strings (its parameters) character by character (ASCII comparison) Returns any of the following integer values : Return value Meaning Example < 0 ASCII value of y= strcmp (ABC, character of first abc); string is less than returns-32 (ASCII that of correspon- difference ding character of between A and a) second string

NIIT

SEM Q/CPR/CR/SESSION 5/31/VER06/95

STANDARD STRING-HANDLING FUNCTIONS (Contd.)


Return value Meaning Example 0 Strings are identi- y = strcmp (ABC, cal ABC); returns 0 >0 ASCII value of y = strcmp (abc, character of first ABC); string is greater returns 32 (ASCII than that of corre- difference sponding charac- between a and A ter of second string

NIIT

SEM Q/CPR/CR/SESSION 5/32/VER06/95

STANDARD STRING-HANDLING FUNCTIONS


strcpy () Copies second string to the first string names as the parameter Example strcpy (str1, ABC); copies string ABC to array str1 strcpy (str1, str2); copies contents of array str2 to array str1

Current contents of first array are lost

NIIT

SEM Q/CPR/CR/SESSION 5/33/VER06/95

STANDARD STRING-HANDLING FUNCTIONS (Contd.)


strcat () appends second string passed to it to end of first string passed to it Example strcat (str1, ABC); adds string ABC to current contents of str1 strcat (str1, str2); adds contents of array str2 to current contents of str1

NIIT

SEM Q/CPR/CR/SESSION 5/34/VER06/95

STANDARD STRING-HANDLING FUNCTIONS (Contd.)


strlen () Returns length of string passed to it Length does not include NULL character Example If str1 contains 1234 y = strlen (str1); then y = 4

NIIT

SEM Q/CPR/CR/SESSION 5/35/VER06/95

STANDARD STRING - TO NUMERIC CONVERSION FUNCTIONS


atoi () Returns int type value of string passed to it; returns 0 if string does not begin with digit Example If str1 contains string 1234 y = atoi (str1); then y = 1234 If str1 contains string ABC y = atoi (str1); then y = 0

NIIT

SEM Q/CPR/CR/SESSION 5/36/VER06/95

STANDARD STRING - TO NUMERIC


atof () Returns double type value of string passed to it; returns O if string does not begin with digit for decimal point Example If str1 contains string 1234 y = atof (str1); then y = 1234.000000 Following declaration must be included in program: double atof (); since it returns a non-integer value

CONVERSION FUNCTIONS (Contd.)

NIIT

SEM Q/CPR/CR/SESSION 5/37/VER06/95

FORMATTING DATA IN MEMORY


sprintf () formats data and can control the width of the destination string Syntax sprintf (string, format-specification, data, ); where: string is a pointer to destination string in memory which will contain formatted data as per formatspecification formatis specification of how data is to be specification formatted data, is list of data to be formatted

NIIT

SEM Q/CPR/CR/SESSION 5/38/VER06/95

FORMATTING DATA IN MEMORY (Contd.)


Example sprintf (str, %02s-%02s-%02s, 28, 8, 89); printf (str contains : %s\ n, str); Output str contains : 28-08-89

NIIT

SEM Q/CPR/CR/SESSION 5/39/VER06/95

FORMATTING DATA IN MEMORY (Contd.)


sscanf() assigns different parts of a string to different variables Syntax sscanf (string, format-specification, variable, ); where : string is a pointer to source string in memory which contains data to be assigned to the list of variables according to format-specification formatis the specification of how data is specification to be formatted variable, is the list of variables to which the data would be assigned after formatting
NIIT SEM Q/CPR/CR/SESSION 5/40/VER06/95

FORMATTING DATA IN MEMORY (Contd.)


Example sscanf (str, %2d%2s%s%d, &day, suffix, mnth, & year); printf (The day is: %d, suffix is: %s, month is: %s, year is: %d\n, day, suffix, mnth, year); Example If the data in str is 28th August 1989: The day is : 28, suffix is:th, month is : August, year is: 1989

NIIT

SEM Q/CPR/CR/SESSION 5/41/VER06/95

SPL EXERCISE
#1 Given below is a C program called remdigit.c and a listing of errors in the program indicated by the compiler. Go through the error listing and correct the program. Since the C compiler does not always give very meaningful error messages, go through the program carefully. 1 /* search for the number of digits in an input string and 2 copy all characters except digits into another string*/ 3 4 main () 5 { 6 char inp , out [];
NIIT SEM Q/CPR/CR/SESSION 5/42/VER06/95

SPL EXERCISE (Contd.)


7 8 9 10 11 12 13 14 15 16 17 18 19
NIIT

int numb = I = j = 0;

printf (Enter string :); gets (inp); fflush (stdin);


while (inp [i] != \0) { if (inp [i] > = 0 && inp [i] < = 9) number+ + ; else out [j+ + ] = inp [i];

SEM Q/CPR/CR/SESSION 5/43/VER06/95

SPL EXERCISE (Contd.)


20 } 21 22 printf (Number of digits in string were : %c numb); 23 printf (String without digits is %s, out); 24 25 Error listing : remdigit.c, line 7: i undefined remdigit.c, line 7: j undefined remdigit.c, line 9: Enter undefined
NIIT SEM Q/CPR/CR/SESSION 5/44/VER06/95

SPL EXERCISE (Contd.)


Error listing (Contd.): remdigit.c, line 9: syntax error

remdigit.c, line 11: stdin undefined


remdigit.c, line 13: illegal indirection remdigit.c, line 15: illegal indirection

remdigit.c, line 15: illegal indirection


remdigit.c, line 16: number undefined remdigit.c, line 18: illegal indirection

remdigit.c, line 22: syntax error


remdigit.c, line 25: syntax error

NIIT

SEM Q/CPR/CR/SESSION 5/45/VER06/95

SOLUTION TO SPL EXERCISE


#1 /* search for the number of digits in an input string and copy copy all characters except except digits into another string */ # include < stdio.h> main () char inp [80] , out [80]; int I, j, number; number = i = j = O; printf (Enter string :); gets (inp); fflush (stdin);

NIIT

SEM Q/CPR/CR/SESSION 5/46/VER06/95

SOLUTION TO SPL EXERCISE (Contd.)


while (inp [i] != \O) { if (inp [i] > = O && inp [i] < = 9 number+ + ; else out [j+ + ] = inp [i]; i+ + ; } printf (Number of digits in string were : %d, number); printf (String without digits is %s, out); }

NIIT

SEM Q/CPR/CR/SESSION 5/47/VER06/95

SPL EXERCISE
#2 Write a program to display all the positions at which a character occurs in a string. Both the character to be located and the string to be searched should be passed to a function called nextpos (findchar, searchstr). Each time the function locates the character, it should pass back the position. After searching the entire string, the function should return the value -1.

NIIT

SEM Q/CPR/CR/SESSION 5/48/VER06/95

SOLUTION TO SPL EXERCISE


#2 #include < stdio.h> main () { int occur = O; char str [100], whichchar; printf (Enter a string of upto 99 characters \ n); scanf (%99s, str); fflush (stdin); printf (Enter character to be located : ); scanf (%c, &whichchar); fflush (stdin);

NIIT

SEM Q/CPR/CR/SESSION 5/49/VER06/95

SOLUTION TO SPL EXERCISE (Contd.)


while ((occur = nextpos (whichchar, str + occur )) != -1 { printf (The character %c occurs in the string at position %d \ n, whichchar, occur); } } nextpos (findchar, searchstr) char findchar, *searchstr; { static int i=0;

NIIT

SEM Q/CPR/CR/SESSION 5/50/VER06/95

SOLUTION TO SPL EXERCISE (Contd.)


while (searchstr [i] != \0 { if (searchstr [i+ + ] = = findchar) return i;
}

return -1;

NIIT

SEM Q/CPR/CR/SESSION 5/51/VER06/95

CLASSROOM EXERCISE
#1 Alcatel Automatics is a company known for its marketing success. This success has been largely due to its superb data analysis programs. The Product Manager wants some modifications to the existing programs. When running the program, he should be able to specify any of the following with the run command itself : %s for displaying the product sales by each salesman as a percentage of the total salesman sales %p for displaying the product sales by each salesman as a percentage of the total product sales
NIIT SEM Q/CPR/CR/SESSION 5/52/VER06/95

CLASSROOM EXERCISE (Contd.)


%i for displaying the product sales as an index of total sales of all products

He should also be shown some help message to assist him in case he forgets what to specify with the command and should then be able to give the command again.
Since the calculations done in this program are to be used in some other data analysis programs also, it has been decided that the calculations will be coded in separate functions which are stored together in one file called func. C, separate from the main () function.
NIIT SEM Q/CPR/CR/SESSION 5/53/VER06/95

CLASSROOM EXERCISE (Contd.)


The functions available in this file are : inddat () this displays the data as an index of total sales proddat () this displays the data as a percentage of total product sales calcprodtot () this calculates the productwise totals calcsaltot () this calculates the salesman-wise totals (The code of the file func.c is provided in your Learner Guide). Write the code for the function main (). In case the %s option is chosen, print the message Module not ready yet.
NIIT SEM Q/CPR/CR/SESSION 5/54/VER06/95

CLASSROOM EXERCISE (Contd.)


as the function to display product sales as a percentage of the total salesman sales has not been coded in func.c as yet. Hints for Classroom Exercise a. Check first argument. If invalid, display message. b. Input data into 2-d array. Array is declared global so that is available to all other functions. c. Declare array as extern in other functions. d. Depending on first argument, call appropriate function. e. exit () function terminates program execution.

NIIT

SEM Q/CPR/CR/SESSION 5/55/VER06/95

SOLUTION TO CLASSROOM EXERCISE


#1 # include < stdio.h> main (argc, argv) int argc; char *argv [ ]; { extern float salesdat [4] [4], prodtot [4], salestot [4]; extern int ind, row, col; /* check parameter count and first argument*/

NIIT

SEM Q/CPR/CR/SESSION 5/56/VER06/95

SOLUTION TO CLASSROOM EXERCISE (Contd.)


if ((argc != 2) && (strcmp (argv [1], %I) != 0) && (strcmp (argv [1], %p) != 0) && (strcmp (argv [1], %s) != 0)) { printf ( Usage : sales [%s] [%p] [%i]\n); exit (); } if (argv [1] [1] = = s) } printf (\nModule not ready yet.); exit ();
}

NIIT

SEM Q/CPR/CR/SESSION 5/57/VER06/95

SOLUTION TO CLASSROOM EXERCISE (Contd.)


/* input sales data into 2-d array */ for (row = O; row < 4; row+ +) { printf (Enter sales figures for salesman %d :\n, row + 1); for (col = O; col < 4; row+ +) { scanf (%f, &salesdat [row] [col]);

fflush (stdin);
} }
NIIT SEM Q/CPR/CR/SESSION 5/58/VER06/95

SOLUTION TO CLASSROOM EXERCISE (Contd.)


/* execute appropriate function depending on first argument */ if (strcmp (argv [1], %p) = = O) proddat (); else if (strcmp (argv [1], %i) = = O)

inddat ();

NIIT

SEM Q/CPR/CR/SESSION 5/59/VER06/95

You might also like