You are on page 1of 20

Name: Section: Rollno:

ESC101: Fundamentals of Computing (Mid Semester Exam)

19 September, 2014

Total Number of Pages: 20 Total Points 110

Instructions Question Points Score


1. Read these instructions carefully. 1 4
2. Write you name, section and roll number on all 2 6
the pages of the answer book, including the
ROUGH pages. 3 20

3. Write the answers cleanly in the space provided. 4 14

S
Space is given for rough work in the answer book. 5 20
4. Do not exchange question books or change the 6 10
seat after obtaining question paper.
5. Using pens (blue/black ink) and not pencils. Do
not use red pens for answering.
6. Even if no answers are written, the answer book
N 7
8
Total:
20
16
110
IO
has to be returned back with name and roll num-
ber written.

Helpful hints
1. The questions are not arranged according to the
T

increasing order of difficulty. Do a quick first


round where you answer the easy ones and leave
the difficult ones for the subsequent rounds.
2. All blanks may NOT carry equal marks.
LU

3. Use the cheat sheet provided in the answer book


for any doubt related to C programming (Not all
topics in the cheat sheet are covered in class, Not
all topics covered in the class are provided in the
cheat sheet.)
SO

Page 1 of 20
Name: Section: Rollno:

Question 1. (4 points) There are 2 subparts of this question. (2 + 2)

(a) What does the following program print?


1 # include < stdio .h >
2 int x =1;
3 int main () {
4 x = 3;
5 {
6 int x ;
7 {
8 x = 2;
9 }
10 printf ( " % d " ,x ) ;
11 }
12 printf ( " % d \ n " ,x ) ;
13 return 0;
14 }

Solution: 2 3

(b) What does the following program print?


1 # include < stdio .h >
2 int x ;
3
4 void f () ;
5 void g () ;
6 void h () ;
7
8 int main () {
9 x = 2;
10 f () ;
11 g () ;
12 return 0;
13 }
14
15 void f () {
16 int x = 3;
17 h () ;
18 }
19
20 void g () {
21 x = 4;
22 h () ;
23 }
24
25 void h () {
26 printf ( " % d " ,x ) ;
27 }

Page 2 of 20
Name: Section: Rollno:

Solution: 2 4

Question 2. (6 points) The following program is executed with input formed by the last two digits of your roll
number, (For example, if Roll No. is 14XYZ, input is YZ). What will be the output of the program?
1 # include < stdio .h >
2 int main () {
3 int Roll_No , N , k , m , a , b , c , A [10];
4
5 scanf ("% d " , & Roll_No ) ; /* Last 2 digits of YOUR ROLL NO .*/
6 printf (" Last two digits of Roll No . : % d \ n " , Roll_No ) ;
7
8 N = ( Roll_No /10 + Roll_No %10) % 10;
9 if ( N < 5) {
10 N = 10;
11 }
12 printf (" Value of N : % d \ n " , N ) ;
13
14 a = 0;
15 for ( k = 1; k <= N ; k ++) { a = a + k ; }
16 printf (" Value of a : % d \ n " , a ) ;
17
18 b = 1; m = 1;
19 while ( m < N /2) {
20 b = b * m;
21 m ++;
22 }
23 printf (" Value of b : % d \ n " , b ) ;
24
25 m = 1; k = 0;
26 do {
27 if ( m % N == 0) {
28 A[k] = m;
29 k ++;
30 }
31 m ++;
32 } while ( k < 10) ;
33
34 c = A [2];
35 printf (" Value of c : % d \ n " , c ) ;
36
37 return 0;
38 }

Output of the above program for last 2 digits of your roll number is:

Page 3 of 20
Name: Section: Rollno:

Last two digits of Roll No. :

Value of N:

Value of a:

Value of b:

Value of c:

Solution: For 6 possible values of N at line # 12, values of a, b, and c will be as under
N 5 6 7 8 9 10
a 15 21 28 36 45 55
b 1 2 2 6 6 24
c 15 18 21 24 27 30
[Marks: 0+0+2+2+2, i.e. 2 marks each for correct values of a, b and c]

Page 4 of 20
Name: Section: Rollno:

Question 3. (20 points) What does the following program print?


1 # include < stdio .h >
2 int foo ( int ) ;
3 int bar ( int ) ;
4
5 int main () {
6 printf ("% d \ n " , foo ( bar ( foo (2) * foo (4) ) ) ) ;
7 return 0;
8 }
9
10 int is_prime ( int n )
11 { /* checks if n is a prime >= 3 */
12 int j ;
13 for ( j =3; j * j <= n ; j = j +2) {
14 if ( n % j == 0) break ;
15 }
16 return ( j * j > n ) ;
17 }
18
19 int foo ( int n ) {
20 int i = 3 , a = 1;
21 if ( n ==1)
22 return 2;
23
24 do {
25 a = a + is_prime ( i ) ;
26 if ( a == n ) break ;
27 i = i + 2;
28 } while (1) ;
29
30 printf ("% d \ n " , i ) ;
31 return i ;
32 }
33
34 int bar ( int n ) {
35 int s =0;
36 while ( n ) {
37 s = s *10 + n %10;
38 n = n /10;
39 }
40
41 printf ("% d \ n " , s ) ;
42 return s ;
43 }

Page 5 of 20
Name: Section: Rollno:

Solution: 3
7
12
37
37

Page 6 of 20
Name: Section: Rollno:

Question 4. (14 points) You have two arrays containing numbers in sorted (non-decreasing) order. You want
to combine the two separate arrays into one sorted array. For example: if array A={1,4,6,9} and array
B={2,3,7}, the combined array C={1,2,3,4,6,7,9}
We have given the partial implementation of the combine function that takes two sorted arrays A (of length
n) and B (of length m), and combine these into array C. Fill in the blanks to complete the function.
(Partial Implementation is on the next page.)

Page 7 of 20
Name: Section: Rollno:

1 /* n is the size of array A , m is the size of array B */


2 void combine ( int A [] , int n , int B [] , int m , int C [])
3 {
4 /* a_index is the index to traverse in array A , b_index
5 * for B . c_index is for C to fill the array . Start
6 * with the first element in each of A , B and C . */
7 int a_index =0 , b_index =0 , c_index =0;
8
9 /* Make sure , we do not overflow */
10 while (( < n ) && ( < m)) {
11 /* Compare the elements at the current poition .
12 * Pick the smaller one , and put into C . Then move to the
13 * next element in the smaller element ‘ s array */
14 if ( A [ a_index ] <= B [ b_index ])
15 {
16 C [ c_index ] = ;
17 c_index ++;
18 ;
19 }
20 else
21 {
22 C [ c_index ] = ;
23 ;
24 b_index ++;
25 }
26 }
27
28 /* At this point , we must have traversed one array
29 * completely . Traverse the other array completely and
30 * copy the elements to C */
31 if ( b_index < m ) {
32 while ( ) {
33 = B [ b_index ];
34 ;
35 ;
36 }
37 }
38 else if ( a_index < n ) {
39 while ( ) {
40 = A [ a_index ];
41 ;
42 ;
43 }
44 }
45 return ;
46 }

Page 8 of 20
Name: Section: Rollno:

Solution:

1 # include < stdio .h >


2
3 void merge ( int A [] , int n , int B [] , int m , int C [])
4 {
5 int a_index , b_index , c_index ;
6 a_index =0;
7 b_index =0;
8 c_index =0;
9 while (( a_index < n ) && ( b_index < m ) )
10 {
11 if ( A [ a_index ] <= B [ b_index ])
12 {
13 C [ c_index ]= A [ a_index ];
14 c_index ++;
15 a_index ++;
16 }
17 else
18 {
19 C [ c_index ]= B [ b_index ];
20 c_index ++;
21 b_index ++;
22 }
23 }
24 if ( b_index < m )
25 {
26 while ( b_index < m )
27 {
28 C [ c_index ]= B [ b_index ];
29 c_index ++;
30 b_index ++;
31 }
32 }
33 if ( a_index < n )
34 {
35 while ( a_index < n )
36 {
37 C [ c_index ]= A [ a_index ];
38 c_index ++;
39 a_index ++;
40 }
41 }
42 return ;
43 }
44
45 int main ()
46 {
47 int A []={1 ,4 ,9};
48 int B []={2 ,3 ,6 ,8};
49 int C [7];
50 merge (A ,3 ,B ,4 , C ) ;

Page 9 of 20
Name: Section: Rollno:

51 int i =0;
52 for ( i =0; i <7; i ++)
53 printf ( " % d " ,C [ i ]) ;
54 printf ( " \ n " ) ;
55 }

Question 5. (20 points) What does the following program print?


1 # include < stdio .h >
2
3 long factorial ( int ) ;
4 void foo ( int [] , int ) ;
5 float bar ( int [] , int ) ;
6
7 int main ()
8 {
9 int n = 5;
10 int a [6];
11 foo (a , n ) ;
12 printf ( " %.2 f \ n " , bar (a , n ) ) ;
13 return 0;
14 }
15
16 void foo ( int a [] , int n ) {
17 int i , j ;
18 int b [6];
19 for ( i = 0 ; i < n ; i ++ ) {
20 for ( j = 0 ; j <= ( n - i - 2 ) ; j ++ )
21 printf ( " " ) ; /* print a SINGLE SPACE */
22
23 for ( j = 0 ; j <= i ; j ++ ) {
24 b [ j ]= factorial ( i ) /( factorial ( j ) * factorial (i - j ) ) ;
25 printf ( " % d " ,b [ j ]) ; /* print INT followed by a SPACE */
26 }
27 printf ( " \ n " ) ;
28
29 a [ i ]=( int ) bar (b , i +1) ;
30 }
31 }
32
33 float bar ( int a [] , int n ) {
34 if ( n %2 == 0)
35 return ( a [ n /2] + a [ n /2 -1]) /2.0;
36
37 return ( float ) a [ n /2] ;
38 }
39
40 /* compute factorial of n >= 0 */
41 long factorial ( int n )
42 {
43 int c ;

Page 10 of 20
Name: Section: Rollno:

44 long result = 1;
45
46 for ( c = 1 ; c <= n ; c ++ )
47 result = result * c ;
48
49 return result ;
50 }

Solution:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
2.00

Page 11 of 20
Name: Section: Rollno:

Question 6. (10 points) What is the output of following program for the given inputs:
1 # include < stdio .h >
2 # include < ctype .h >
3
4 int main () {
5 char base [] = " A Quick Brown Fox Jumps Over The Lazy Dog " ;
6 int arr [26];
7
8 int i , k , j =0;
9 for ( i = 0; i < 26; i ++) {
10 arr [ i ] = 0; /* Initialize array */
11 }
12
13 while ( base [ j ] != ’ \0 ’) { /* till end of base string */
14 if (( base [ j ] >= ’a ’ && base [ j ] <= ’z ’)
15 | | ( base [ j ] >= ’A ’ && base [ j ] <= ’Z ’) ) {
16 base [ j ] = tolower ( base [ j ]) ; /* convert to lower case */
17 int tmp = arr [ base [ j ] - ’a ’ ];
18 arr [ base [ j ] - ’a ’] = tmp + 1;
19 }
20 j ++;
21 }
22
23 int num ;
24 scanf ( " % d " ,& num ) ; /* the number of characters to read */
25 for ( k = 0; k < num ; k ++) {
26 char ch ;
27 scanf ( " % c " ,& ch ) ; /* input the character */
28 ch = tolower ( ch ) ; /* convert to lower case */
29 printf ( " % d " , arr [ ch - ’a ’ ]) ; /* print something ... */
30 }
31
32 return 0;
33 }

INPUT INPUT
4abcd 5uoiea

OUTPUT OUTPUT

Note: “ctype.h” contains declaration of function tolower that converts given uppercase letter to lowercase.

Page 12 of 20
Name: Section: Rollno:

Solution: 2111 24122

Page 13 of 20
Name: Section: Rollno:

Question 7. (20 points) What is the output of following program for the given inputs:
1 # include < stdio .h >
2
3 const int true =1;
4 const int false =0;
5
6 int main () {
7 int a [11];
8 int b [11];
9 int n ;
10
11 int i =0;
12 int inc = true ;
13 int dec = false ;
14 int tog =0;
15
16 a [0] = 0;
17 b [0] = inc ;
18
19 scanf ( " % d " , & n ) ; /* Assume n <= 10 */
20 for ( i =1; i <= n ; i ++) {
21 scanf ( " % d " ,& a [ i ]) ;
22 }
23
24 for ( i =1; i <= n ; i ++) {
25 if ( inc && a [ i ] < a [i -1] ) {
26 tog ++;
27 dec = inc ;
28 inc = false ;
29 }
30 else if ( dec && a [ i ] > a [i -1]) {
31 tog ++;
32 inc = dec ;
33 dec = false ;
34 }
35 b [ i ]= inc ;
36 printf ( " % d % d \ n " , inc , dec ) ;
37 }
38
39 printf ( " % d \ n " , tog ) ;
40 for ( i =0; i < n ; i ++) {
41 printf ( " % d " ,b [ i ] ) ;
42 }
43
44 return 0;
45 }

Page 14 of 20
Name: Section: Rollno:

INPUT INPUT
6 4
1 3 5 1 10 2 -1 1 -1 1
OUTPUT OUTPUT

Solution:
10 01
10 10
10 01
01 10
10 4
01 1010
3
111101

Page 15 of 20
Name: Section: Rollno:

Question 8. (16 points) ( NOTE: This question has a very lengthy description and cryptic program. My advice
is to attempt it after you have looked at all other questions.)
A wrap around array or cyclic array of size S is one in which indices beyond the range [0,...,S-1] are also
acceptable. Indices S, S+1, S+2, ... point to the same elements as 0, 1, 2, .... and similarly negative indices
are also valid, where indices -1, -2, -3 .... point to S-1, S-2, S-3,... and so on.
Consider a cyclic array of characters of size S = 8. Associated with this array are two special numbers, called
as leap forward number (denoted as F) and leap backward number (denotes as B). Whenever leap forward()
function is called, all elements in the array leap forward by a step of size F, i.e., for all i, element at index i
goes to its new index i+F. Similarly, whenever leap backward() function is called, all elements in the array
leap backward by step of size B (element at index i goes to index i-B).
The program given below first accepts two positive integers F and B from the user. Then program accepts
a sequence of S characters from user. The string of characters must be stored in the same order. Whenever
user enters a vowel, leap forward() function is called. Similarly, whenever the user enters a consonant,
leap backward() function is called. After the user has entered all the characters, the starting point of the
array and the array itself is printed.
Fill in the blanks in the program given below. Read the comments carefully as they may contain helpful
instructions.
1 # include < stdio .h >
2
3 const int S =8; /* max elements */
4 int start = 0; /* store the position of first character in the array . */
5
6 void leap_forward ( char Arr [] , int size , int step ) {
7 int i , j ; char tmp ;
8 for ( i =0; i < step ; i ++) { /* leap one step at a time */
9 tmp = Arr [( start + size ) % S ];
10 for ( j = start + size -1; j >= start ; j - -)
11 Arr [( j +1) % S ] = Arr [ j % S ];
12 Arr [ ] = tmp ;
13 start = ;
14 }
15 }
16
17 void leap_backward ( char Arr [] , int size , int step ) {
18 int i , j ; char tmp ;
19 for ( i =0; i < step ; i ++) { /* leap one step at a time */
20 /* we make sure we use MOD (%) operator with
21 * * positive arguments only * to avoid any surprises
22 * due to different compilers . */
23 tmp = Arr [( start +S -1) % S ];
24 for ( j = start ; j < ; j ++)
25 Arr [( j +S -1) % S ] = Arr [ j % S ];
26 Arr [ ] = tmp ;
27 start = ( )%S;
28 }
29 }
30
31 /* Continued on next page ... */
32

Page 16 of 20
Name: Section: Rollno:

33

34 isVowel ( ) {
35 return ch == ’a ’ || ch == ’e ’ || ch == ’i ’ || ch == ’o ’ || ch == ’u ’;
36 }
37
38 int main () {
39 char A [ S ] , ch ; /* S characters to be stored in array */
40 int F , B , i ;
41 int count =0; /* count of chracters read so far */
42 /* Values of F and B from user .
43 * Assume : ( i ) F and B are positive .
44 * ( ii ) 0 ≤ F ≤ S, 0 ≤ B ≤ S
45 * Make sure we * EAT AWAY * the newline */
46 scanf ( " % d % d \ n " , &F , & B ) ;
47 while ( count < S ) { /* Read characters . */
48 scanf ( " % c " , & ch ) ; /* Assume no whitespace between characters */
49 A [( start + count ) % S ] = ch ; /* Store the character in the array */
50 count ++; /* one more character read . */
51
52 /* Leap forward for vowel , backward for consonant */
53 if ( ) { leap_forward (A , count , F ) ; }
54 else { leap_backward (A , count , B ) ; }
55 }
56
57 /* Now print the start , and the string from start */
58 printf ( " start = % d \ n " , start ) ;
59 for ( i = start ; i < ; i ++) {
60 putchar ( A [ ]) ;
61 }
62 return 0;
63 }

Solution:
1 # include < stdio .h >
2 const int S =8;
3 int start = 0; // store the position of first character in the array .
4
5 void leap_forward ( char Arr [] , int size , int step ) {
6 int i , j ; char tmp ;
7 for ( i =0; i < step ; i ++) {
8 tmp = Arr [( start + size ) % S ];
9 for ( j = start + size -1; j >= start ; j - -)
10 Arr [( j +1) % S ] = Arr [ j % S ];
11 Arr [( start + size +1) % S ] = tmp ;
12 start = ( start +1) % S ;
13 }
14 }
15
16 void leap_backward ( char Arr [] , int size , int step ) {

Page 17 of 20
Name: Section: Rollno:

17 int i , j ; char tmp ;


18 for ( i =0; i < step ; i ++) {
19 tmp = Arr [( start -1+ S ) % S ];
20 for ( j = start ; j < start + size ; j ++)
21 Arr [( j -1+ S ) % S ] = Arr [ j % S ];
22 Arr [( start -2+ S ) % S ] = tmp ;
23 start = ( start -1+ S ) % S ;
24 }
25 }
26
27 int isVowel ( char ch ) {
28 return ch == ’a ’ || ch == ’e ’ || ch == ’i ’ || ch == ’o ’ || ch == ’u ’;
29 }
30
31 int main () {
32 char A [ S ] , ch ;
33 int F , B , i ;
34 int count =0; // maintain count of chracters entered so far by user
35 /* Values of F and B from user ; assume F and B are positive .
36 * Make sure we * EAT AWAY * the newline */
37 scanf ( " % d % d \ n " , &F , & B ) ;
38 while ( count < S ) { // Read characters .
39 scanf ( " % c " , & ch ) ; // Assume no whitespace between characters
40 A [( start + count ) % S ] = ch ; // Store the character in the array
41 count ++;
42
43 /* Leap forward for vowel , backward for consonant */
44 if ( isVowel ( ch ) ) { leap_forward (A , count , F ) ; }
45 else { leap_backward (A , count , B ) ; }
46 }
47
48 /* Now print the start , and the string from start */
49 printf ( " start = % d \ n " , start ) ;
50 for ( i = start ; i < start + S ; i ++) { putchar ( A [ i % S ]) ; }
51 return 0;
52 }

Page 18 of 20
C Reference Card (ANSI) Constants Flow of Control
suffix: long, unsigned, float 65536L, -1U, 3.0F statement terminator ;
Program Structure/Functions exponential form 4.2e1 block delimiters { }
type fnc(type 1 , . . . ); function prototype prefix: octal, hexadecimal 0, 0x or 0X exit from switch, while, do, for break;
type name; variable declaration Example. 031 is 25, 0x31 is 49 decimal next iteration of while, do, for continue;
int main(void) { main routine character constant (char, octal, hex) 'a', '\ooo', '\xhh' go to goto label;
declarations local variable declarations newline, cr, tab, backspace \n, \r, \t, \b label label: statement
statements special characters \\, \?, \', \" return value from function return expr
} string constant (ends with '\0') "abc. . . de" Flow Constructions
type fnc(arg 1 , . . . ) { function definition if statement if (expr 1 ) statement 1
declarations local variable declarations Pointers, Arrays & Structures else if (expr 2 ) statement 2
statements declare pointer to type type *name; else statement 3
return value; declare function returning pointer to type type *f(); while statement while (expr )
} declare pointer to function returning type type (*pf)(); statement
/* */ comments generic pointer type void * for statement for (expr 1 ; expr 2 ; expr 3 )
int main(int argc, char *argv[]) main with args null pointer constant NULL statement
exit(arg); terminate execution do statement do statement
object pointed to by pointer *pointer
while(expr );
address of object name &name
C Preprocessor array name[dim] switch statement switch (expr ) {
case const 1 : statement 1 break;
include library file #include <filename> multi-dim array name[dim 1 ][dim 2 ]. . . case const 2 : statement 2 break;
include user file #include "filename" Structures default: statement
replacement text #define name text struct tag { structure template }
replacement macro #define name(var ) text declarations declaration of members
Example. #define max(A,B) ((A)>(B) ? (A) : (B)) }; ANSI Standard Libraries
undefine #undef name create structure struct tag name <assert.h> <ctype.h> <errno.h> <float.h> <limits.h>
quoted string in replace # member of structure from template name.member <locale.h> <math.h> <setjmp.h> <signal.h> <stdarg.h>
Example. #define msg(A) printf("%s = %d", #A, (A)) member of pointed-to structure pointer -> member <stddef.h> <stdio.h> <stdlib.h> <string.h> <time.h>
concatenate args and rescan ## Example. (*p).x and p->x are the same
conditional execution #if, #else, #elif, #endif single object, multiple possible types union
Character Class Tests <ctype.h>
is name defined, not defined? #ifdef, #ifndef bit field with b bits unsigned member : b; alphanumeric? isalnum(c)
name defined? defined(name) alphabetic? isalpha(c)
line continuation char \ Operators (grouped by precedence) control character? iscntrl(c)
Data Types/Declarations struct member operator name.member decimal digit? isdigit(c)
struct member through pointer pointer ->member printing character (not incl space)? isgraph(c)
character (1 byte) char lower case letter? islower(c)
integer int increment, decrement ++, --
printing character (incl space)? isprint(c)
real number (single, double precision) float, double plus, minus, logical not, bitwise not +, -, !, ~
printing char except space, letter, digit? ispunct(c)
short (16 bit integer) short indirection via pointer, address of object *pointer , &name
space, formfeed, newline, cr, tab, vtab? isspace(c)
long (32 bit integer) long cast expression to type (type) expr
upper case letter? isupper(c)
double long (64 bit integer) long long size of an object sizeof
hexadecimal digit? isxdigit(c)
positive or negative signed multiply, divide, modulus (remainder) *, /, % convert to lower case tolower(c)
non-negative modulo 2m unsigned add, subtract +, - convert to upper case toupper(c)
pointer to int, float,. . . int*, float*,. . .
left, right shift [bit ops] <<, >> String Operations <string.h>
enumeration constant enum tag {name 1 =value 1 ,. . . };
constant (read-only) value type const name; relational comparisons >, >=, <, <= s is a string; cs, ct are constant strings
declare external variable extern equality comparisons ==, != length of s strlen(s)
internal to source file static and [bit op] & copy ct to s strcpy(s,ct)
local persistent between calls static concatenate ct after s strcat(s,ct)
no value void exclusive or [bit op] ^
compare cs to ct strcmp(cs,ct)
structure struct tag {. . . }; or (inclusive) [bit op] | only first n chars strncmp(cs,ct,n)
create new name for data type typedef type name; logical and && pointer to first c in cs strchr(cs,c)
size of an object (type is size_t) sizeof object pointer to last c in cs strrchr(cs,c)
logical or ||
size of a data type (type is size_t) sizeof(type) copy n chars from ct to s memcpy(s,ct,n)
conditional expression expr 1 ? expr 2 : expr 3
Initialization copy n chars from ct to s (may overlap) memmove(s,ct,n)
assignment operators +=, -=, *=, . . . compare n chars of cs with ct memcmp(cs,ct,n)
initialize variable type name=value; expression evaluation separator , pointer to first c in first n chars of cs memchr(cs,c,n)
initialize array type name[]={value 1 ,. . . }; Unary operators, conditional expression and assignment oper- put c into first n chars of s memset(s,c,n)
initialize char string char name[]="string"; ators group right to left; all others group left to right.
c 2007 Joseph H. Silverman Permissions on back. v2.2
°
C Reference Card (ANSI) Standard Utility Functions <stdlib.h> Mathematical Functions <math.h>
absolute value of int n abs(n) Arguments and returned values are double
Input/Output <stdio.h> absolute value of long n labs(n) trig functions sin(x), cos(x), tan(x)
Standard I/O quotient and remainder of ints n,d div(n,d) inverse trig functions asin(x), acos(x), atan(x)
standard input stream stdin returns structure with div_t.quot and div_t.rem arctan(y/x) atan2(y,x)
standard output stream stdout quotient and remainder of longs n,d ldiv(n,d) hyperbolic trig functions sinh(x), cosh(x), tanh(x)
standard error stream stderr returns structure with ldiv_t.quot and ldiv_t.rem exponentials & logs exp(x), log(x), log10(x)
end of file (type is int) EOF pseudo-random integer [0,RAND_MAX] rand() exponentials & logs (2 power) ldexp(x,n), frexp(x,&e)
get a character getchar() set random seed to n srand(n) division & remainder modf(x,ip), fmod(x,y)
print a character putchar(chr ) terminate program execution exit(status) powers pow(x,y), sqrt(x)
print formatted data printf("format",arg 1 ,. . . ) pass string s to system for execution system(s) rounding ceil(x), floor(x), fabs(x)
print to string s sprintf(s,"format",arg 1 ,. . . ) Conversions
convert string s to double atof(s) Integer Type Limits <limits.h>
read formatted data scanf("format",&name 1 ,. . . )
read from string s sscanf(s,"format",&name 1 ,. . . ) convert string s to integer atoi(s) The numbers given in parentheses are typical values for the
print string s puts(s) convert string s to long atol(s) constants on a 32-bit Unix system, followed by minimum re-
File I/O convert prefix of s to double strtod(s,&endp) quired values (if significantly different).
declare file pointer FILE *fp; convert prefix of s (base b) to long strtol(s,&endp,b) CHAR_BIT bits in char (8)
pointer to named file fopen("name","mode") same, but unsigned long strtoul(s,&endp,b) CHAR_MAX max value of char (SCHAR_MAX or UCHAR_MAX)
modes: r (read), w (write), a (append), b (binary) Storage Allocation CHAR_MIN min value of char (SCHAR MIN or 0)
get a character getc(fp) allocate storage malloc(size), calloc(nobj,size) SCHAR_MAX max signed char (+127)
write a character putc(chr ,fp) change size of storage newptr = realloc(ptr,size); SCHAR_MIN min signed char (−128)
write to file fprintf(fp,"format",arg 1 ,. . . ) deallocate storage free(ptr); SHRT_MAX max value of short (+32,767)
read from file fscanf(fp,"format",arg 1 ,. . . ) Array Functions SHRT_MIN min value of short (−32,768)
read and store n elts to *ptr fread(*ptr,eltsize,n,fp) search array for key bsearch(key,array,n,size,cmpf) INT_MAX max value of int (+2,147,483,647) (+32,767)
write n elts from *ptr to file fwrite(*ptr,eltsize,n,fp) sort array ascending order qsort(array,n,size,cmpf) INT_MIN min value of int (−2,147,483,648) (−32,767)
close file fclose(fp) LONG_MAX max value of long (+2,147,483,647)
Time and Date Functions <time.h> LONG_MIN min value of long (−2,147,483,648)
non-zero if error ferror(fp)
non-zero if already reached EOF feof(fp) processor time used by program clock() UCHAR_MAX max unsigned char (255)
read line to string s (< max chars) fgets(s,max,fp) Example. clock()/CLOCKS_PER_SEC is time in seconds USHRT_MAX max unsigned short (65,535)
write string s fputs(s,fp) current calendar time time() UINT_MAX max unsigned int (4,294,967,295) (65,535)
Codes for Formatted I/O: "%-+ 0w.pmc" time2 -time1 in seconds (double) difftime(time2 ,time1 ) ULONG_MAX max unsigned long (4,294,967,295)
- left justify arithmetic types representing times clock_t,time_t
structure type for calendar time comps struct tm Float Type Limits <float.h>
+ print with sign
space print space if no sign tm_sec seconds after minute The numbers given in parentheses are typical values for the
0 pad with leading zeros tm_min minutes after hour constants on a 32-bit Unix system.
w min field width tm_hour hours since midnight FLT_RADIX radix of exponent rep (2)
p precision tm_mday day of month FLT_ROUNDS floating point rounding mode
m conversion character: tm_mon months since January FLT_DIG decimal digits of precision (6)
h short, l long, L long double tm_year years since 1900 FLT_EPSILON smallest x so 1.0f + x 6= 1.0f (1.1E − 7)
c conversion character: tm_wday days since Sunday FLT_MANT_DIG number of digits in mantissa
d,i integer u unsigned tm_yday days since January 1 FLT_MAX maximum float number (3.4E38)
c single char s char string tm_isdst Daylight Savings Time flag FLT_MAX_EXP maximum exponent
f double (printf) e,E exponential convert local time to calendar time mktime(tp) FLT_MIN minimum float number (1.2E − 38)
f float (scanf) lf double (scanf) convert time in tp to string asctime(tp) FLT_MIN_EXP minimum exponent
o octal x,X hexadecimal convert calendar time in tp to local time ctime(tp) DBL_DIG decimal digits of precision (15)
p pointer n number of chars written convert calendar time to GMT gmtime(tp) DBL_EPSILON smallest x so 1.0 + x 6= 1.0 (2.2E − 16)
g,G same as f or e,E depending on exponent convert calendar time to local time localtime(tp) DBL_MANT_DIG number of digits in mantissa
format date and time info strftime(s,smax,"format",tp) DBL_MAX max double number (1.8E308)
Variable Argument Lists <stdarg.h> tp is a pointer to a structure of type tm DBL_MAX_EXP maximum exponent
declaration of pointer to arguments va_list ap; DBL_MIN min double number (2.2E − 308)
initialization of argument pointer va_start(ap,lastarg); DBL_MIN_EXP minimum exponent
lastarg is last named parameter of the function
access next unnamed arg, update pointer va_arg(ap,type)
call before exiting function va_end(ap); c 2007 Joseph H. Silverman
January 2007 v2.2. Copyright °
Permission is granted to make and distribute copies of this card pro-
vided the copyright notice and this permission notice are preserved on
all copies.
Send comments and corrections to J.H. Silverman, Math. Dept., Brown
Univ., Providence, RI 02912 USA. hjhs@math.brown.edui

You might also like