cse-module-4
cse-module-4
4232 4232
Index
Sr. Pg.
Contents SubTopics
No. No.
1. Fundamentals and Input Output
C
Introduction to C Programming 1
C Fundamentals 2
Notes Operators and Expressions 9
Data Input / Output 19
LMR (Last Minute Revision) 28
Assignment1 Questions 30
Test Paper1 Questions 33
2. Control Statements
if Statement 37
switch Statement 40
goto Statement 41
Notes while Statement 42
dowhile Statement 43
for Statement 43
LMR (Last Minute Revision) 47
Assignment2 Questions 48
Test Paper2 Questions 54
3. Arrays in C
Need of an Array 59
One Dimensional Array 60
Two Dimensional Array 62
Three Dimensional Array 64
Notes
Introduction to string 65
String functions 67
Table of strings 69
LMR (Last Minute Revision) 71
Assignment3 Questions 72
Test Paper3 Questions 78
Sr. Pg.
Contents Topics
Sub
No. No.
4. Functions
Introduction 82
Need For Userdefined Functions 82
CFunction 83
Return values and their types 84
Calling a function 84
Category of functions 85
Notes
Nesting of functions 85
Recursion 86
Function with Arrays 87
Function Prototyping 88
Scope and Lifetime of Variables in functions 89
LMR (Last Minute Revision) 95
Assignment4 Questions 96
Test Paper4 Questions 102
5. Pointers, Structures and Union
Introduction 107
Accessing the address of a variable 108
Declaring and Initializing pointers 109
Accessing a variables through its pointer 110
Pointer expressions 111
Pointer increment and scale factor 112
Pointers and Arrays 112
Pointers and Character Strings 113
Pointers to functions 114
Notes Introduction to Structures 115
Structure Initialization 118
Comparison of Structure variables 120
Arrays of Structures 120
Arrays within Structures 121
Structures within structure 121
Structures and functions 123
Union 124
Size of Structures 125
LMR (Last Minute Revision) 126
Assignment5 Questions 127
Test Paper5 Questions 133
Sr. Pg.
Contents Topics
Sub
No. No.
ID Problems Questions 139
Practice Problems Questions 144
SOLUTIONS
Answer Key Assignment 170
Model Solutions Assignment 172
Answer Key Test Paper 185
Model Solutions Test Paper 187
Answer Key ID Problems 199
Model Solutions ID Problems 200
Answer Key Practice Problems 202
Model Solutions Practice Problems 203
Fundamentals and Input Output
Topic 1 : C
INTRODUCTION TO C PROGRAMMING
‘C’ seems a strange name for a programming language. But this strange sounding
language is one of the most popular computer languages today. C was an offspring of the
‘Basic Combined Programming Language’ (BCPL) called B. B Language was modified by
Dennis Ritchie and was implemented at Bell Laboratories in 1972. The new language
was named C. Since it was developed along with the UNIX operating system, it is
strongly associated with Unix.
Importance of C
1. It is robust language whose rich set of built-in functions and operators can be used to
write any complex programs.
2. The ‘C’ compiler combines the capabilities of an Assembly language with the features
of the highlevel language and therefore well suited for writing both system software
and business packages.
3. Programs written in C are efficient and fast due to variety of data types and powerful
operators.
4. It is a highly portable means ‘C’ program written for one machine can easily be run on
another machine with little or nomodification.
5. ‘C’ language can extend itself i.e. we can add our own function to its library.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.1
Vidyalankar : GATE – CS
C FUNDAMENTALS
CHARACTER SET
x The characters that can be used to form words, numbers and expressions depend
upon the computer on which the program is run.
x The characters in ‘C’ are grouped into :
Ccharacter set
Special Characters
White Spaces
Blank space
Horizontal tab
Carriage return
New line
Form feed
GATE/CS/PM/SLP/Ch.1_Notes/Pg.2
Fundamentals and Input Output
Notes on C
Keyword Identifier
x Every C word is classified as either a keyword or an identifier
x All keywords have fixed meaning and their meanings cannot be changed.
x Keywords serves as basic building blocks for programming statement.
Example : void, for, if etc.
IDENTIFIER
x It refers to the names of variables, functions and arrays
x These are user defined and consists of letter / digit, with a letter as first character. It
accepts both lowercase and uppercase letters.
Example : max10, m1023 etc.
CONSTANTS
It refers to the fixed values that do not change during the execution of program
‘C’ constant
Integer constants
It refers to the sequence of digits. There are three types of integers, namely decimal,
octal and hexadecimal. Rules for constructing integer constants are:
(a) At least one digit must be present
(b) No decimal point
(c) It is either +ve or ve
(d) If no sign mention, then it is considered as positive.
(e) No comma or blanks are allowed within constant.
(f) Allowable range for integer constant is 32768 to +32767
GATE/CS/PM/SLP/Ch.1_Notes/Pg.3
Vidyalankar : GATE – CS
Examples :
Valid Invalid
+ 123 IS 7500
0 $ 15
78 20,000
12
654321
Real constant
It is also called as floating point constant. Real numbers are represented into two forms.
Real constants (floating point)
GATE/CS/PM/SLP/Ch.1_Notes/Pg.4
Fundamentals and Input Output
Notes on C
Character constants
Character constants
VARIABLES
x A variable is a data name that may be used to store a data value.
x Unlike constants that remain unchanged during the execution of a program, a
variable may take different values at different times during execution.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.5
Vidyalankar : GATE – CS
DATA TYPES
‘C’ language is rich in its ‘data types’. Storage representations and machine instructions
to handle constants differ from machine to machine.
The variety of data types are available to allow the programmer to select the type
appropriate to the needs of application as well as the machine. ANSI C supports four
classes of data types.
Data Types
Integral Floating
Type point type
Integer Character
GATE/CS/PM/SLP/Ch.1_Notes/Pg.6
Fundamentals and Input Output
Notes on C
Declaration of Variables
After designing suitable variable names, we must declare them to the compiler. A
declaration associates a group of variables with a specific data type. Declaration does
two things:
(1) It tells the compiler what the variable name is.
(2) It specifies what type of data the variable will hold.
Syntax :
data type v1, v2, …..vn;
where v1, v2, …….vn are the names of variables. Variables are separated by
commas.
Declaration sentences must end with a semicolon.
Example :
int count ;
int number, total ;
double ratio ;
Example : initial_value = 0 ;
Final_value = 100 ;
The process of giving initial values to variables is called initialization. C permits the
initialization of more than one variables in one statement using multiple assignment
operators.
Example : p = q = s = 0 ;
x = y = z = MAX ;
External and static variables are initialized to zero default.
SYMBOLIC CONSTANTS
A symbolic constant is a name that substitutes for a sequence of characters. The
characters may represent a numeric constant, a character constant or a string constant.
Thus, a symbolic constant allows a name to appear in place of a numeric constant, a
character constant or a string. When a program is compiled, each occurrence of a
symbolic constant is replaced by its corresponding character sequence. Symbolic
constants are usually defined at the beginning of a program.
where name represents a symbolic name, typically written in uppercase letters and text
represents the sequence of characters associated with the symbolic name.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.7
Vidyalankar : GATE – CS
Example :
# define PI 3.1415
# define MAX 200
Documentation Section
Link Section
Definition Section
Global Declaration
Main ( ) function section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2 User
: defined
: functions
Function n
1. Every C program requires a main ( ) function (use of more than one main ( ) is
illegal). The place main is where the program execution begins.
2. The execution of a function begins at the opening brace of the function and ends at
the corresponding closing brace.
3. C programs are written in lowercase letters. However, uppercase letters are used for
symbolic names and output strings.
4. All the words in a program line must be separated from each other by at least one
space, or a tab, or a punctuation mark.
5. Every program statement in a C program must end with a semicolon.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.8
Fundamentals and Input Output
Notes on C
6. All variables must be declared for their types before they are used in the program.
7. We must make sure to include header files using # include directive when the
program refers to special names and functions that it does not define.
8. Compiler directives such as define and include are special instructions to the
compiler to help it compile a program. They do not end with a semicolon.
9. The sign # of compiler directives must appear in the first column of the line.
10. When braces are used to group statement, make sure that the opening brace has a
corresponding closing brace.
11. C is a free form language and therefore a proper form of indentation of various
sections would improve legibility of the program.
12. A comment can be inserted almost anywhere a space can appear. Use of
appropriate comments in proper places increases readability and understandability of
the program and helps users in debugging and testing. Remember to match the
symbols /* and */ appropriately.
x Operators are used in programs to manipulate data and variable. They usually form a
part of the mathematical or logical expression.
x The data items that operators act upon are called operands. Some operators require
two operands, while other act upon only one operand.
COperators
GATE/CS/PM/SLP/Ch.1_Notes/Pg.9
Vidyalankar : GATE – CS
ARITHMETIC OPERATORS
x C provides all the basic arithmetic operators.
They are as follows:
Operator Meaning
+ Addition or Unary plus
Subtraction or unary minus
* Multiplication
/ Integer Division
% Modulo Division
x Examples:
ab a+b
a ub a/b a & b are variables and are known as operands
a % b a u b
Integer Arithmetic :
x When both the operands in a single arithmetic expression such as a + b are integers,
the expression is called an integer expression and the operation is called integer
arithmetic.
x It always gives integer values.
x Examples :
Let a = 14, b = 4
a b = 10
a + b = 18
a * b = 56
a / b = 3 (14/4 It truncates fractional part)
a % b = 2 (14 % 4 It gives remainder)
During integer division
o If both the operands are of the same sign, the result is truncated towards zero.
e.g. 6/7 = 0 or 6 / 7 = 0
o If one of them is negative, the direction of truncation is implementation dependent.
e.g. : 6/7 = 0 or 1 (machine dependent)
During modulo division
o The sign of the result is always the sign of the first operand
e.g. 14 % 3 = 2
14 % 3 = 2
14 % 3 = 2
Real Arithmetic
x An arithmetic operation with real operands is called Real arithmetic.
x A Real operand may assume values either in decimal or exponential notation.
x If x, y, z are floats, then we will have
x = 6.0/7.0 = 0.857143
y = 1.0/3.0 = 0.333
z = 2.0/3.0 = 0.66667
x The % operator cannot be used with Real operands
GATE/CS/PM/SLP/Ch.1_Notes/Pg.10
Fundamentals and Input Output
Notes on C
RELATIONAL OPERATORS
x These operators are generally used for comparisons. Expression containing
relational operators is termed as relational expression
x The value / Result of the Relational expression is either one if the specified relation is
true or zero if the specified relation is false.
e.g. 10 < 20 True (1)
20 < 10 False (0)
Syntax :
GATE/CS/PM/SLP/Ch.1_Notes/Pg.11
Vidyalankar : GATE – CS
LOGICAL OPERATORS
x The logical operators are used to evaluate logical expression.
Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Each of the logical operators falls into its own precedence group. Logical and has a
higher precedence than logical or. Both precedence groups are lower than the group
containing the equality operators. The associativity is left to right. C also includes the
unary operator ! that negates the value of a logical expression, i.e., it causes an
expression that is originally true to become false, and vice versa. This operator is referred
to as the logical negation (or logical not) operator.
ASSIGNMENT OPERATORS
x Assignment operator is used to assign the result of an expression to a variable. We
usually
_
use ‘ _ ’
x We can also use shorthand assignment operator.
Syntax: Vop = exp; equivalent to V = Vop(exp) ;
where, V o variable
op o operator
exp o expression
x Assignment operator = and the equality operator = = are distinctly different. The
assignment operator is used to assign a value to an identifier, whereas the equality
operator is used to determine if two expressions have the same value.
x If the two operands in an assignment expression are of different data types. Then
the value of the expression on the right (i.e., the right hand operand) will
automatically be converted to the type of the identifier on the left. The entire
assignment expression will then be of this same data type.
Under some circumstances, this automatic type conversion can result in an alteration
of the data being assigned.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.12
Fundamentals and Input Output
Notes on C
For Example :
x A floating point value may be truncated if assigned to an integer identifier.
x A doubleprecision value may be rounded if assigned to a floating point (single
precision) identifier.
Assignment operators have a lower precedence than any of the other operators that
have been discussed so far. Therefore unary operations, arithmetic operations,
relational operations, equality operations and logical operations are all carried out
before assignment operations.
Examples :
Statement with simple statement with
assignment operator shorthand operators
a=a+1 a+=1
a =a1 a=1
a = a*(n + 1) a* = n + 1
a = a / (n + 1) a/=n+1
a=a%b a%=b
GATE/CS/PM/SLP/Ch.1_Notes/Pg.13
Vidyalankar : GATE – CS
(2) m = 5;
y = m ++ ; A postfix operator first assigns the value to the variable
on left and then increment its value by 1.
O/P :
y =5
m=6
CONDITIONAL OPERATOR
x A ternary operator pair “ ? : ” is available in C to construct a conditional
expression
x Syntax :
Exp = exp1 ? exp 2 : exp 3 ;
x Example :
a = 10 ;
b = 15 ;
x = (a > b) ? a : b ;
n
Exp (a > b) is evaluated first, in this case (10 > 15) is false.
?x=b i.e. x = 15 is the result.
BITWISE OPERATORS
x ‘C’ has a distinction of supporting special operators known as bitwise operators
for manipulation of data at bit level.
x These operators are used for testing the bits, or shifting them right or left.
Bitwise operators may not be applied for float or double.
x
Operator Meaning
& Bitwise AND
| Bitwise OR
/ Bitwise ExOR
<< Shift Left
>> Shift right
One’s complement
GATE/CS/PM/SLP/Ch.1_Notes/Pg.14
Fundamentals and Input Output
Notes on C
SPECIAL OPERATORS
x C supports some special operators such as comma, sizeof operators.
x The comma operator can be used to link the related expressions together. A
commalinked list of expressions are evaluated left to right and the value of
rightmost expression is the value of the combined expression.
Example : value = (x = 10, y = 5, x +y) ;
It first assigns the value 10 to x, then assign 5 to y, and finally assigns
15( i.e. 10 + 5) to value. Since, comma operator has the lowest operator
precedence of all operators, the parentheses are necessary.
Use of comma operator:
(1) In for loops :
for (n = 1, m = 10; n < = m; n++, m++)
(2) In while loops :
while ( c = getchar ( ), c! = c10’)
The sizeof operator is normally used to determine the lengths of arrays and structures
when their sizes are not known to the programmer. It is also used to allocate memory
space dynamically to variables during execution of a program.
x Expression can also represent logical conditions that are either true or false.
However, in C the conditions true and False are represented by the integer values 1
and 0, respectively. Hence, logical type expressions represent numerical quantities.
Arithmetic Expressions
An arithmetic expression is a combination of variables, constants and operators
arranged as per the syntax of the language.
x Evaluation of expressions
Expressions are evaluated using an assignment statement of the form :
Variable = expression ;
GATE/CS/PM/SLP/Ch.1_Notes/Pg.15
Vidyalankar : GATE – CS
Arithmetic Operators
The basic evaluation procedure includes two left to right passes through expression.
During first pass : High priority operators are applied as they are encountered
During second pass : Low priority operators are applied as they are encountered.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.16
Fundamentals and Input Output
Notes on C
Note :
For solving such kind of problem, apply all basic rules of operators and
expression.
O/P :
x =10.000
y = 7.000
z = 4.000
‘C’ permits mixing of constants and variables of different types in an expression, but
during evaluation it adheres to very strict rules of type conversions.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.17
Vidyalankar : GATE – CS
Summary of C operators
Operators Description Associativity Ranks
() function call
Left to Right 1
[] Array element reference
+ Unary plus
unary minus
++ increment
decrement
! logical not
~ one’s complement Right to left 2
* pointer reference
& address
size of size of an object
(type) Type cast
* multiplication
3
/ Division Left to right
% Modulus
+ Addition
Left to Right 4
Subtraction
<< Left shift
Left to Right 5
>> Right shift
< less than
Left to Right 6
<= less than or equal to
> Greater than
>= Greater than or equal to
== Equality
Left to Right 7
!= Inequality
& Bitwise AND Left to Right 8
^ Bitwise XOR Left to Right 9
| Bitwise OR Left to Right 10
&& Logical AND Left to Right 11
|| Logical OR Left to Right 12
?: Conditional Expn Right to Left 13
=
*=/=%=
Assignment
+==&= Right to left 14
operators
^= |=
<<=>>=
Comma (,)
Left to Right 15
Operator
GATE/CS/PM/SLP/Ch.1_Notes/Pg.18
Fundamentals and Input Output
Notes on C
DATA INPUT/OUTPUT
Unlike other high level language, C does not have any built in input /output statements
as part of its syntax. All input / output operations are carried out through function calls
such as printf and scanf. There exist several functions that have more or less become
standard for input and output Operations in C. These functions are collectively known as
the standard I /O Library.
The file name stdio.h is an abbreviation for standard input output header file. The
instruction # include < stdio. h > tells the compiler ‘to search for a file named stdio. h and
place its contents at this point in the program. The contents of the header file become
part of the source code when it is compiled.
READING A CHARACTER
x The simplest of all input / output operations is reading a character from the standard
input unit (usually the key board) and writing it to the standard output unit (usually the
screen)
x Reading a single character can be done by using the function getchar.
Syntax :
Variable name = getchar ( ) ;
where ¸ variable name is a valid C name that has been declared as char type.
x When this statement is encountered, the computer waits until a key is pressed and
then assigns this character as a value to getchar function.
x Since getchar is used on the R. H. S. of an assignment statement, the character
value of getchar is in turn assigned to the variable name on the left.
For example :
char name ;
name = getchar ( ) ;
The getchar( ) function accepts any character keyed in. This includes RETURN and
TAB. This means that when we enter single character input, the newline character is
waiting in the input queue after getchar( ) returns.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.19
Vidyalankar : GATE – CS
Example :
isalpha (character)
True false
if argument otherwise
is character
WRITING A CHARACTER
Like getchar, there is an analogous function putchar for writing characters one at a time
to the terminal.
Syntax :
putchar (Variablename);
where variable name is a type char variable containing a character. This statement
displays the character contained in the variablename at the terminal.
Example :
ans = ‘y’ ;
putchar (ans) ;
getchar function
³ x Single character can be entered into the computer using the C library
function getchar. The getchar function is a part of the standard C
language I/O Library. It returns a single character from a standard
input device.
x The function does not require any arguments, though a pair of empty
parentheses must follow the word getchar.
A reference to the getchar function is written as
Character var = getchar ( ) ;
x If an end of file conditions is encountered when reading a
character with the getchar function, the value of the symbolic
constant EOF will automatically be returned.
x The detection of EOF in this manner offers a convenient way to
detect an endoffile, whenever and wherever it may occur.
x The getchar function can also be used to read multi character
strings, by reading one character at a time within a multipass loop.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.20
Fundamentals and Input Output
Notes on C
putchar function
³ x Single characters can be displayed using the C library function
putchar. This function is complementary to the character input
function getchar.
x The putchar function, like getchar, is a part of the standard C
language I/O library. It transmits a single character to a standard
output device.
x The character being transmitted will normally be represented as a
character type variable. It must be expressed as an argument to the
function, enclosed in parenthesis, following the word putchar. It is
written as :
putchar (char variable) ;
where, charvariable is valid Ccharacter variable.
x The putchar function can be used to output a string constant by
storing the string within a one dimensional, character type array.
Each character can then be written separately within a loop.
gets ( )
It receives a string from the input device. We can do the same by scanf function but it
has some limitation. Let’s consider following example :
main ( )
{ char name [50] ; O / P {Expected }
printf (“ /n Enter Name” ) ; Enter Name
scanf (“ % s”, name) ; Jonty Rhodes
printf (“ % s”, name) ; Actual O/p after execution
} Jonty
Due to the blank space, it never stored in an array. scanf assumes that it is end of string
once a blank space is encountered. So to avoid this problem we use gets ( ). It accepts
the string from keyboard and terminate when Enter key is pressed. Therefore, space and
tab is acceptable.
Syntax : gets (string) ;
puts ( )
It works exactly opposite to gets ( ). i.e. it outputs the string on monitor.
GATE/CS/PM/SLP/Ch.1_Notes/Pg.21
Vidyalankar : GATE – CS
FORMATTED INPUT
Formatted input refers to an input data that has been arranged in a particular format.
General syntax :
x Control string contains field specification which direct the interpretation of input
data. It may include :
o Field (or format) specifications, consisting of the conversion character %, a data type
character, and an optional number specifying the field width.
o Blanks, tabs or newlines.
Blanks, tables and newlines are ignored. The data type character indicates the type
of data that is to be assigned to the variable associated with the corresponding
argument.
The field width specifier is optional.
(a) Integer numbers :
The field specification for reading an integer number is :
%wd
indicates that a int. data type
conversion Integer number that
specification follows specifies the field width
Example :
GATE/CS/PM/SLP/Ch.1_Notes/Pg.22
Fundamentals and Input Output
Notes on C
assign to assign to Not assign in
Num1 Num2 this statement
num 1 num 2
50 is not assigned in this scanf statement. 50 will be assigned to the first variable
in the next scanf call.
x To avoid this types of errors we can write a scanf statement without w.
scanf (“ % d % d ”, & num1, & num2) ;
x An I/P field may be skipped by specifying * in the place of field width.
Example :
scanf (“ %d %d *d %d”, & a, &b) ;
We will assign the data : 50 100 150
It is as follows : 50 to a
100 is skipped
150 to b
(b) Real numbers :
x field width is not required in Real number.
x scanf reads real numbers using the simple specification %f
x Example :
scanf (“ %f %f %f”, &x, &y, &z) ;
with i/p data : 475.89 43.21E 1 678
x y = 4.321 z
x If the number to be read is of double type, the specification should be % A f
instead of simple %f
x An input field may be skipped by specifying * in the place of field width.
(c) Character string :
x Single character can be read by getchar function, the same can be done by
scanf function.
x In addition, a scanf function can input strings containing more than one character.
x We can use
% ws or % wc
Example. : scanf (“ %ws”, & name) ;
scanf (“ %wc”, & name) ;
(d) Reading Mixed data type :
x It is possible to use one scanf statement to input a data line containing mixed
more data.
Example :
int char float string
scanf (“ %d %c %f %s”, &count, &code, &ratio, &name ) ;
GATE/CS/PM/SLP/Ch.1_Notes/Pg.23
Vidyalankar : GATE – CS
x Syntax
³ printf ( “control string”, arg1, arg2, ……argn) ;
x Examples :
printf (“programming in C”) ;
printf ( “ ” ) ;
printf (“ \n” ) ;
printf (“ % d”, x) ;
printf (“a = %f \n b = %f”, a, b) ;
printf (“sum = %d”, 1234) ;
printf (“\n \n ”) ;
GATE/CS/PM/SLP/Ch.1_Notes/Pg.24
Fundamentals and Input Output
Notes on C
%w d
field width For integer
Format output
(1) printf (“ % d”, 3846)
3 8 4 6
(2) printf (“%6d”, 3846) 3 8 4 6 By default right justified.
(3) printf (“%2d”, 3846) 3 8 4 6
(4) printf (“%-6d”, 3846) 3 8 4 6 Left justified.
(5) printf (“%06d”, 3846) 0 0 3 8 4 6
x The long integer may be printed by specifying A d in the place of d in the format
specification.
x The value, when displayed, is rounded to p decimal places and printed rightjustified
in the field of w columns.
x Leading blanks and trailing zeros will appear as necessary. The default precision is 6
decimal places. The negative numbers will be printed with the minus sign.
x We can also display a real number in exponential notation by using the specification.
% w. pe
The field width w should satisfy the condition
w t p +7
GATE/CS/PM/SLP/Ch.1_Notes/Pg.25
Vidyalankar : GATE – CS
Example : y = 98.7654
Format output
Printing of Strings :
2) % 10s H e A o 1 2 3
3) % .5s H e A o
4) % 10.5s H e A A o
5) % 10.5s H e o
GATE/CS/PM/SLP/Ch.1_Notes/Pg.26
Fundamentals and Input Output
Notes on C
Code Meaning
%c Read a single character
%d Read a decimal integer
%e Read a floating pt. value
%f Read a floating pt. value
%g Read a floating pt. value
%h Read a short integer
%i Read a decimal, hexadecimal or octal integer
%o Read an octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
% [..] Read a string of word (s)
Code Meaning
%c print a single character
%d print a decimal integer
%e print a floating pt. value in exponent form
%f print a floating pt. value without exponent
%g print a floating pt. value either etype
or f type depending on value
%i print a signed decimal integer
%o print an octal integer, without leading zero
%s print a string
%u print an unsigned decimal integer
%x print a hexadecimal integer, without leading 0’s
GATE/CS/PM/SLP/Ch.1_Notes/Pg.27
Vidyalankar : GATE – CS
GATE/CS/PM/SLP/Ch.1_Notes/Pg.28
Fundamentals and Input Output
Notes on C
GATE/CS/PM/SLP/Ch.1_Notes/Pg.29
Vidyalankar : GATE – CS
ASSIGNMENT 1
Duration : 45 Min. Max. Marks : 30
Q 1 to Q 6 carry one mark each
1. We want to round off x, a float to an int value. What is the correct way to do so?
(A) y = (int)(x + 0.5) (B) y = int(x + 0.5)
(C) y = (int) x + 0.5 (D) y = (int)((int) x + 0.5)
2. By default any real number in ‘C’ is treated as
(A) a float
(B) a long double
(C) a double
(D) depends upon the memory model that you are using
3. Trace the output :
main ( )
{
printf(“%c”, “abcdefgh”[4]);
}
(A) Error (B) d
(C) e (D) abcd
4. Trace the output :
main ( )
{
printf(“\n %x”, 1 >> 4);
}
(A) ffff (B) 0fff
(C) 000 (D) fff0
5 The declarations
typedef float ht[100];
ht men, women;
defines _____
(A) men and women as 100 element floating point arrays
(B) men and women as floating point variables
(C) ht, men and women as floating point variables
(D) None of these
6. If a variable can take any integral values from 0 to n, where n is a constant
integer, then the variable can be represented as a bit field whose width is the
integral part of __________
(A) log2(n) + 1 (B) log2(n + 1) +1
(C) log2(n 1) + 1 (D) None of the above
GATE/CS/PM/SLP/Ch.1_Assign/Pg.30
Fundamentals and Input Output
Assignment on C
k=i|j;
l=i&j
m = k ^ l;
printf(“%d %d %d %d %d”, i, j, k, l, m);
}
(A) 32 32 32 32 0 (B) 00000
(C) 0 32 32 32 32 (D) 32 32 32 32 32
8. Trace the output :
main ( )
{
unsigned int a = 0xffffffff ;
a = ~ a;
printf(“%x”, a);
}
(A) ffff (B) 0
(C) 00ff (D) None of these
9. If y is of integer type, then the expression
3 * ( y 8) / 9 and (y 8) / 9 * 3
yield the same value if
(A) y is an even number
(B) y is an odd number
(C) (y 8) is an integral multiple of 9
(D) (y 8) is an integral multiple of 3
10. If y is of integer type, then the expressions
3 * (y 8) / 9 and (y 8) /9 * 3
(A) must yield the same value
(B) must yield different values
(C) may or may not yield the same value
(D) None of the above
11. Trace the output :
int x, y = 2, z, a;
x = (y*= 2) + (z = a = y);
printf(“%d”, x);
(A) prints 7 (B) prints 6
(C) prints 8 (D) is syntactically wrong
12. What is the result of execution of the following ‘C’ program fragment?
int i = 107, x = 5;
printf((x > 7) ? “%d” : “%c”, i);
(A) an execution error (B) a syntax error
(C) printing k (D) None of the above
13. Consider the following program fragment:
main ( )
{
int a, b, c;
b = 2;
a = 2 * (b++);
GATE/CS/PM/SLP/Ch.1_Assign/Pg.31
Vidyalankar : GATE – CS
c = 2 * (++b);
}
Which of the following is correct?
(A) a = 4, c = 6 (B) b = 3, c = 6
(C) a = 3, c = 8 (D) a = 4, c = 8
14. Trace the output:
main ( )
{
int y = 128;
const int x = y;
printf(“%d”, x);
}
(A) 128 (B) Garbage value
(C) Error (D) 0
15. Match the following :
(a) \a (i) tab
(b) \v (ii) apostrophe
(c) \” (iii) carriage return
(iv) bell
(v) quotation mark
(A) a ii, b iv, c iii (B) a iv, b i, c v
(C) a i, b iv, c v (D) a v, b i, c iii
16. What will be the values of a, b, and c after execution?
int a, b, c;
b = 10;
c = 15;
a = ++b + c++;
(A) a = 25, b = 10, c = 15 (B) a = 27, b = 10, c = 15
(C) a = 26, b = 11, c = 16 (D) a = 27, b = 11, c = 16
17. Consider a following declaration:
i = 3.3, j = 3.9, k = 3.9;
printf(“%d %d %d”, i, j, k) ;
The select the correct the statement?
(A) 3 4 4 (B) 3 3 3
(C) 3 3.9 3.9 (D) None of these
GATE/CS/PM/SLP/Ch.1_Assign/Pg.32
Fundamentals and Input Output
Test Paper on C
TEST PAPER 1
Duration : 30 Min. Max. Marks : 25
Q 1 to 5 Carry one mark each
3. main ( )
{
int i;
for (i = ‘64’; i <= ‘127’; i++)
{
printf(“%d”, i);
}
}
In the above declaration, the value of first and last i is __________
(A) A and ~
(B) ? and DEL
(C) A and DEL
(D) None of these
GATE/CS/PM/SLP/Ch.1_Test/Pg.33
Vidyalankar : GATE – CS
GATE/CS/PM/SLP/Ch.1_Test/Pg.34
Fundamentals and Input Output
Test Paper on C
GATE/CS/PM/SLP/Ch.1_Test/Pg.35
Vidyalankar : GATE – CS
14(b). main ( )
{
int z;
float p;
p = 6.8;
z = (++x)*floor(p) u 3.5;
printf(“%d”, z);
}
Find the value of z.
(A) 73 (B) 73.5
(C) 63 (D) 66.5
GATE/CS/PM/SLP/Ch.1_Test/Pg.36