0% found this document useful (0 votes)
3 views

cse-module-4

The document is a comprehensive guide on C programming, covering fundamentals, control statements, arrays, functions, pointers, structures, and unions. It includes detailed explanations of key concepts, data types, variable declarations, and symbolic constants, along with notes, assignments, and test papers for practice. The content is structured with an index for easy navigation and includes various examples to illustrate programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

cse-module-4

The document is a comprehensive guide on C programming, covering fundamentals, control statements, arrays, functions, pointers, structures, and unions. It includes detailed explanations of key concepts, data types, variable declarations, and symbolic constants, along with notes, assignments, and test papers for practice. The content is structured with an index for easy navigation and includes various examples to illustrate programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Pearl Centre, S.B. Marg, Dadar (W), Mumbai  400 028. Tel.

4232 4232

CS : COMPUTER SCIENCE AND INFORMATION TECHNOLOGY


Programming in C

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.

Where ‘C’ stands


Programming languages are divided into high level and low level language
Programming language

High Level Low Level

Designed to give faster Designed to give faster


program development program execution
Example: FORTRAN Example: Assembly language,
BASIC Machine Language

‘C’ stands in between


? It is called ‘Middle Level Language’

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

Letters Digits Special character White spaces


A …..Z 0 …..9 , ; : ? etc. Blank spaces
a……z tab etc.

1. C supports A ..Z and a…z letters


2. C supports 0…9 digits
3. C supports 29 special characters
4. C supports white space like blank space or tab etc.
x Compiler ignores white spaces unless they are part of string
x It is also used to separate the words

Special Characters

, comma & ampersand


. period ^ caret
; semicolon * asterisk
: colon  minus sign
? question mark + plus sign
c apostrophe < opening angle bracket
cc quotation mark (or less than sign)
! exclamation mark > closing angle bracket
| vertical bar (or greater than sign)
/ slash ( left parenthesis
\ back slash ) right parenthesis
~ tilde [ left bracket
_ underscore ] right bracket
$ dollar sign { left brace
% per cent sign } right brace
# number sign

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

KEYWORDS AND IDENTIFIERS


C  word

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.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default go to sizeof volatile
do if static while

CONSTANTS
It refers to the fixed values that do not change during the execution of program

‘C’ constant

Primary constant Secondary constant


Ÿ

x Integer constant x Array


x Real x Pointer
x Character x Structure
x Union
x ENUM etc

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)

Fractional form Exponential form

(i) Fractional form


Rules for constructing Real constants in fractional form
(a) It must have at least one digit
(b) It must have decimal point
(c) It is either positive or negative
(d) By default it is positive.
(e) No comma or blank space is allowed.
Examples :
Valid Invalid
426.0 326
36.78 $ 4.76
(ii) Exponential form
Real number is represented as follows :
Mantissa e exponent
Mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer number with an optional plus or minus sign.
Example : 3.2e 5, 4.2e + 4
Rules for constructing Real constants in Exponential form
(a) Mantissa and Exponent should be separated by e.
(b) Mantissa is either positive or negative.
(c) By default positive.
(d) Exponent must have one digit either positive or negative. By default positive.
(e) Exponent can be written in either lowercase or uppercase.
(f) Embedded white space is not allowed.
(g) Exponent must be an integer.
(h) Range : 3.4e38 to 3.4e38
Example :
+3.2e  5
4.1e8
0.2e + 3
3.2e  5

GATE/CS/PM/SLP/Ch.1_Notes/Pg.4
Fundamentals and Input Output
Notes on C

Character constants

Character constants

Single character String constant Backslash character constant

(i) Single character :


x Single character enclosed within a pair of single quote marks.
x Example : ‘5’, ‘x’ etc.

(ii) String character


x String constants is a sequence of characters enclosed in double quotes.
x Characters may be letters, numbers, special characters and blank spaces.
x Example : “Hello!”, “1987” etc.

(iii) Backslash character constant.


‘C’ supports some special backslash character constants that are used in output
functions

Constant Meaning Constant Meaning


‘\a’ audible alert (bell) ‘\v’ vertical tab
‘\b’ back space ‘\’ ’ single quote
‘\f’ form feed ‘\”’ double quote
‘\n’ new line ‘\?’ question mark
‘\r’ carriage return ‘\\’ backslash
‘\t’ horizontal tab ‘\0’ null

These character combinations are known as "escape sequences".

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.

Rules for constructing variable names:


1. They must begin with a letter. Some systems permit underscore as the first
character.
2. ANSI standard recognizes a length of 31 characters. However, the length should not
be normally more than 8 characters, since only the first eight characters are treated
as significant by many compilers.
3. Uppercase and lowercase are significant. That is, the variable Total is not the same
as total or TOTAL.
4. The variable name should not be a keyword.
5. White space is not allowed.
Examples : Value, T_raise, XI etc.

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

Primary User Derived Empty


Data Types defined Data Types Data Type
Data Types
Primary Data Types

Integral Floating
Type point type

Integer Character

Signed Unsigned signed unsigned


x int x unsigned int char char
x short int x unsigned short int
x long int x unsigned long int float double long double

Type Size(bits) Range

char or signed char 8 128 to 127


unsigned char 8 0 to 255
int or signed int 16 32,768 to 32,767
unsigned int 16 0 to 65535
short int or 8 128 to 127
signed short int
unsigned short int 8 0 to 255
long int or 32 2,147,483,648 to 2,147, 483, 647
signed long int
unsigned long int 32 0 to4,294,967,295
float 32 3.4E -38 to 3.4E + 38
double 64 1.7E308 to 1.7E+308
long double 80 3.4E4932 to 1.1E+4932

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 ;

Assigning values to variables


Initial values can be assigned to variables within a type declaration. To do so, the
declaration must consist of a data type, followed by a variable name, an equal sign ( = )
and a constant of the appropriate type. A semicolon must appear at the end, as usual.

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.

Syntax : # define name text

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

Symbolic names are sometimes called constant identifiers


The following rules apply to a # define statement which define a symbolic constant.

1. Symbolic names have the same form as variable names


2. No blank space between the pound sign ‘#’ and the word define is permitted.
3. ‘#’ must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the
symbolic name and the constant.
5. # define statements must not end with a semicolon.
6. Symbolic names are NOT declared for data types. Its data type depends on the type
of constant.
7. #define statements may appear anywhere in the program but before it is referenced
in the program.

BASIC STRUCTURE OF C  PROGRAM

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.

OPERATORS and EXPRESSIONS

‘C’ supports a rich set of operators.


x An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations

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

Arithmetic Logical Increment and Bitwise


Operators Operators Decrement Operators
Operators

Relational Assignment Conditional Special


Operators Operators Operators Operators

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

Mixed mode Arithmetic:


x When one of the operands is real and the other is integer, the expression is called a
mixedmode arithmetic expression.
x If either operand is of the real type, then only the real operation is performed and the
result is always a real number.
e.g. : 15/10.0 = 1.5
where as 15/10 = 1

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)

x Relational operators are :


Operator Meaning
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

Syntax :

Arithmetic Expression 1 Relational operator Arithmetic expression 2

In this, arithmetic expression may contain simple constant, variables or combination


of them.
Examples :
4.5 < = 10 Ÿ True
4. 5 <  10 Ÿ False
10 < 7 + 5 Ÿ True
a+b==c+d Ÿ True (only if sum of (a + b) = sum of (c + d))

x Arithmetic operators having higher priority than relational operators.


? Arithmetic expressions are evaluated first and then compared.

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.

Example : a > b && x = = 10


An expression of this kind which combines two or more relational expression is termed as
a logical expression or compound relational expression.
Examples :
(1) if (age > SS && salary < 1000)
(2) if (number < 0 || number > 100)

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

x Advantages of shorthand operators :


1. What appears on the lefthand side need not be repeated and therefore it
becomes easier to write
2. The statement is more concise and easier to read.
3. The statement is more efficient.
Example :
value (5 * j  2 ) = value (5 * j  2) + delta ;
This can be written as, value (5 * j  2) + = delta

INCREMENT AND DECREMENT OPERATORS


x ‘C’ Supports Ÿ Increment operator o + + Ÿ adds 1
Ÿ Decrement operator o  Ÿ subtracts 1
x Both are unary operators. It takes the following form :
++ m or m ++ ;
Preorder Postorder
Operator  m or m  ; Operator
x ++ m & m ++ means
o The same thing when they form statement independently.
o It behave differently when they are used in expression on the RHS of an
assignment statement.
x Example :
(1) m = 5;
y = ++m ; Ÿ A prefix operator first adds 1 to the operand and then
the result is assigned to the variable on left
O/P :
y =m=6

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 ;

o In this case, exp 1 is calculated first


If exp 1 = true
then exp 2 is evaluated and it becomes the value of Exp.
o If exp 1 = false
then exp 3 is evaluated and it becomes the value of Exp. i.e. only one exp. is
evaluated at a time.

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


The sizeof is a compile time operator and, when used with an operand, it returns the
number of bytes the operand occupies. The operand may be a variable, a constant or a
data type qualifier.
Examples :
m = sizeof (sum) ;
n = sizeof (long int) ;

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.

EXPRESSIONS AND ITS COMPONENTS


x An expression represents a single data item, such as a number or a character. The
expression may consist of a single entity, such as a constant, a variable, an array
element or a reference to a function.

x It may also consist of some combination of such entities interconnected by one or


more operators.
The use of expressions involving operators is particularly common in C, as in most
other programming languages.

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

Algebraic expression C  Expression


aubc a*bc
(m + n) ( x + y) (m + n) * ( x + y)
ab
a*b/c
c
3x2 + 2x + 1 3 * x * x + 2 * x +1
x
+c x/y+c
y

PRECEDENCE OF ARITHMETIC OPERATORS

Arithmetic Operators

High priority Low priority


* / % +

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.

Example to study operator precedence

# include < stdio.h >


main ( )
{ float a, b, c, x, y, z ;
a=9;
b = 12;
c = 3;
x=ab/3+c*21;
y = a  b / (3 + c) * (2  1) ;
z = a  (b / (3 + c) * 2)  1 ;
printf ("x = % f \n", x) ;
printf ("y = % f \n", y) ;
printf ("z = %f \n", z) ;
}

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

AUTOMATIC TYPE CONVERSION

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

Character Test Functions


We can use different functions to test a given character is an alphabet or digit or any
other special character.
Various functions are :
Functions Test
isalnum ( C ) is C an alphanumeric character ?
isalpha ( C ) is C an alphabetic char ?
isdigit ( C ) is C a digit ?
islower ( C ) is C a lower case letter ?
isupper ( C ) is C an upper case letter ?
isprint ( C ) is C a printable character ?
ispunct ( C ) is C a punctuation mark ?
isspace ( C ) is C a white space character ?
All these functions are included in ctype . h

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.

Syntax : puts (string) ;

write a program to study gets ( ) and puts ( ) function


# include < stdio.h >
main ( )
{
char cricket [40] ;
puts (“Enter Name”) ;
gets (cricket) ; / * sends bare address of an array * /

GATE/CS/PM/SLP/Ch.1_Notes/Pg.21
Vidyalankar : GATE – CS

puts (“Cricket is a funny game”) ;


puts (cricket) ;
}
Output :
Enter Name
Sachin Tendulkar
Cricket is a funny game
Sachin Tendulkar

FORMATTED INPUT
Formatted input refers to an input data that has been arranged in a particular format.
General syntax :

scanf ( “ control string” , arg1, arg2 ……..argn) ;


³
it specifies the field Both are Specify the address
format in which the separated of location where
data is to be entered by comma the data is stored

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 :

scanf (“ % 2d % 5d “, & num 1, & num 2) ;

Control string Arguments

GATE/CS/PM/SLP/Ch.1_Notes/Pg.22
Fundamentals and Input Output
Notes on C

Suppose, we entered two values 50 and 31426 then :


50
50 31426 But I/P : 31 426

Ÿ
Ÿ

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

data type int char float string

GATE/CS/PM/SLP/Ch.1_Notes/Pg.23
Vidyalankar : GATE – CS

Points to Remember while using scanf


1. All functions arguments, except the control string, must be pointer to variable.
2. Format specifications contained in the control string should match the arguments
in order.
3. I/P data items must be separated by spaces and must match the variables
receiving the input in the same order.
4. The reading will be terminated, when scanf encounters an ‘invalid mismatch’ of
data or a character that is not valid for the value being read.
5. When searching for a value, scanf ignores line boundaries and simply looks for
the next appropriate character.
6. Any unread data items in a line will be considered as a part of the data input line
to the next scanf call.
7. When the field width specifier w is used, it should be large enough to contain the
i/p data size.
FORMATTED OUTPUT
It is highly desirable that the outputs are produced in such a way that they are understandable
and are in an easytouse form. The printf statement provides certain features that can be
effectively exploited to control the alignment and spacing of printouts on the terminals.

x Syntax
³ printf ( “control string”, arg1, arg2, ……argn) ;

Control string consists of three types of items :


1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of
each item.
3. Escape sequence characters such as \n , \t and \b.
x The control string indicates how many arguments follow and
what their types are.
x The arguments arg1, arg2 …argn are the variables whose
values are formatted and printed according to the specification of
the control string.
x A simple format specification has the following form :
% w. p typespecifier
where, w o an integer number that specifies the total number of columns for the
output value
p o an integer number that specifies the number of digits to the right of the
decimal point or the number of characters to be printed from a string.

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

Output of Integer numbers


x The format specification for printing an integer number is

%w d
field width For integer

x The number is written rightjustified in the given field width.


x Example :

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.

Output of Real Numbers

x The output of a real number may be displayed in decimal notation using


³ the following format specification:
% w. pf

where : w o indicates the minimum number of positions that are to


be used for the display of the value.
p o indicates the number of digits to be displayed after the
decimal point.
(Precision)

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

(1) printf (“ % 7.4f cc, y) 9 8 x 7 6 5 4


(2) printf (“%7.2fcc, y) 9 8 x 7 7
(3) printf (“%-7.2fcc,y) 9 8 x 7 7
(4) printf (“% fcc, y) 9 8 x 7 6 5 4
(5) printf (“% 10.2 ecc, y) 9 x 8 8 e + 0 1

Output of a single character


x A single character can be displayed in a desired position using the format,
%wc

x The character will be displayed right  justified in the field of w columns


x Left justified by placing minus sign () before w. The default value of w = 1

Printing of Strings :

³ The format specification for outputting strings is similar to that of real


numbers.
% w. p. s
For string

width It instructs that, only


the first p characters of
the string are to be
displayed(Right justified)

Example : Hello 123


1) % s H e A A o 1 2 3

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

Mixed data output :

It is permitted to mix data types in one printf statement.


³ printf (“ % d %f % s % c cc, a, b, c, d ) ;

scanf format codes

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)

printf format code

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

LMR (LAST MINUTE REVISION)

x C was an offspring of BCPL and discovered by Dennis Ritchie in 1972.


x C was developed along with Unix Operating system, so strongly associated with
Unix.
x C is rich with built in functions and operations and combines the capabilities of
an assembly language with the features of the high-level language.
x C program written for one machine can easily be run on another machine with
little or no-modification. Also one can add our own function to its library.
x While space separate the words and compiler ignore them unless they are part
of string.
x Keywords have fixed meaning which cannot be changed whereas identifiers are
the name of variables, function and arrays.
x Constants refer to the fixed value that do not change during the execution of
program.
x Allowable range for integer constant is -32768 to + 32767, for exponential form
is -3.4e 38 to 3.4e 38.
x A variable may take different values at different times during execution and they
are not keywords.
x Symbolic constant are unique constants in a program which may appear
repeatedly in a number of places in the program.
x # define statements may appear anywhere in the program but before it is
referenced in the program and must not end with a semicolon.
x Compiler directives such as define and include are special instructions to the
compiler to help it compile a program.
x C is a free – form language and therefore a proper form of indentation of various
sections would improve legibility of the program.
x Operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
x An arithmetic expression is a combination of variables, constants and operators
arranged as per the syntax of the language.
x ‘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.
x sizeof operator is used to allocate memory space dynamically to variables during
execution of a program.

GATE/CS/PM/SLP/Ch.1_Notes/Pg.28
Fundamentals and Input Output
Notes on C

x ‘C’ has a distinction of supporting special operators known as bitwise operators


for manipulation of data at bit level.
x The comma operator can be used to link the related expressions together.
x Ternary operator pair “ ? : ” is available in C to construct a conditional
expression.
x Assignment operator is used to assign the result of an expression to a variable.
x The logical operators are used to evaluate logical expression.
x 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 becomes part of the source code when it is compiled.
x Reading a single character can be done by using the function getchar.
x putchar function is use for writing characters one at a time to the terminal.
x getchar and putchar function does not require any arguments, though a pair of
empty parentheses must follow those words.
x gets function receives a string from the input device and terminate when Enter
key is pressed.
x puts outputs the string on monitor.
x Formatted input refers to an input data that has been arranged in a particular
format.
x It is possible to use one scanf statement to input a data line containing mixed
mode data.

‰‰‰‰‰‰

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

Q7 to Q18 carry two marks each


7. Trace the output :
main ( )
{
int i = 32, j = 0u20, k, l, m;

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

18. Consider a following declaration


int i = 7;
float f = 8.5;
then which of the following statement is correct?
(i) (i + f) % 4 (ii) ((int)(i +f)) % 4
(iii) ((float)(f + i)) % 4 (iv) ((int)f) % 2
(A) Only (ii) (B) (i) and (iii)
(C) (ii) and (iv) (D) All of the above

‰‰‰‰‰‰

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

1. The rule for implicit type conversion in ‘C’ is :


(A) int < unsigned < float < double
(B) unsigned < int < float < double
(C) int < unsigned < double < float
(D) unsigned < int < double < float

2. Which of the following statements is/are correct ?


(A) enum variables can be assigned new values
(B) enum variables can be compared
(C) enumeration feature does not increase the power of C
(D) all of the above.

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

4. The difference between rand( ) and srand( ) is _______


(A) There is no difference between rand( ) and srand(u) both do same function.
(B) The return type of rand( ) function is int and that of srand( ) is void.
(C) The srand( ) function is used to initialize the random number generator
whereas rand( ) function returns a random positive integer.
(D) Both (B) and (C)

5. A _________ is the value of a variable or an expression which is displayed


continuously as the program executes.
(A) breakpoint value
(B) watch value
(C) step value
(D) error value

GATE/CS/PM/SLP/Ch.1_Test/Pg.33
Vidyalankar : GATE – CS

Q6 to 13 Carry two marks each


6. Consider a following declaration
main ( )
{
int i, n;
float p;
scanf(“%d %d %f”, &i, &n, &p);
printf(“%f”, p*(pow((1 + i), n)));
}
Select the correct statement :
(A) The above program is used for finding the Fibbonacci series with
n numbers and n power.
(B) The above program is use for finding compound interest.
(C) The above program is use for finding (a  (a  1)1  (a  2)2  .....)
(D) The above program is also use for (1 i1  i2  i3  .....  in )n

7. Consider the following declaration :


# include “goto.c”
# include <goto.c>
From which of the following statement is correct ?
(A) Both declaration are same and valid
(B) Both declaration are not same and not valid
(C) Both declaration are not same but both are valid
(D) Only second declaration is valid and both are same
8. Trace the final value of s and i
void main ( )
{
int c = 1, s = 0, i = 1;
while(c <= 5)
{
s = s + i;
i = i + 2;
c += 1;
}
printf(“%d %d”, s, i);
}
(A) 36 13 (B) 25 11
(C) 64 17 (D) 81 21
9. Match the following :
1. Integrity a. enhances the accuracy and clarity of program.
2. Efficiency b. execution speed and proper memory utilization
3. Modularity c. clarity and accuracy of a program are usually enhanced by it.
d. refers to the accuracy of the calculations.
(A) 1  a, 2  c, 3  d (B) 1  b, 2  d, 3  c
(C) 1  c, 2  d, 3  b (D) 1  d, 2  b, 3  a

GATE/CS/PM/SLP/Ch.1_Test/Pg.34
Fundamentals and Input Output
Test Paper on C

10. Trace the output :


main ( )
{
float a = 4.9, b = 8.6; int c;
c = floor (a) * a  (b);
printf(“%d”, c);
}
(A) 28.2 (B) 28
(C) 33.1 (D) 33

11. Consider the following declaration :


main ( )
{
int a, b, c;
c += (a > 0 && a <= 10) ? ++a : a | b;
}
Which of the following statements is false?
(A) If (a > 0 && a <= 10) is true then ++a with right to left associativity is
evaluated.
(B) If (a > 0 && a <= 10) is false then a | b with left to right associativity is
evaluated.
(C) ++, \, and += operators are always right to left associative.
(D) The value of C is increased by the value of conditional expression.
12. Select the correct statement :
(i) The sign # of compiler directives must appear in the first column of the line
(ii) C is free form of language
(iii) All statements, variables, constants are always written in lowercase in a C
program.
(A) Only (i)
(B) Only (iii)
(C) (i) and (ii)
(D) (i), (ii) and (iii)
13. Consider the following declaration :
int i = 8, j = 5;
float x = 0.005, y = 0.01;
char c = ‘c’, d = ‘d’;
f = 2 * ((i/5) + (4 *(j  3)) % (i + j  2));
Then, the data type of f is ________ and value is _______
(A) float, 13
(B) int, 18
(C) float, 18
(D) int, 13

GATE/CS/PM/SLP/Ch.1_Test/Pg.35
Vidyalankar : GATE – CS

Q14(a) & (b) carry two marks each

Linked Answer Question


14(a). main ( )
{
int a = 6, b = 10, x;
x = a & b;
printf(“%d”, x);
}
Find the value of x.
(A) 2 (B) 7
(C) 10 (D) 5

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

You might also like