Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

15jan2019 C-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 139

PROGRAMMING IN C – For 6th Sem B.Tech.

@ NIST
National Institute of Science & Technology

.
SECTION L3-B 15.JAN.2019 [ TUE ] [1]
BACKGROUND
National Institute of Science & Technology

C is a structured programming language.


C is derived from ALGOL.
C is often called “Middle Level” programming language.

In 1967, Martin Richards developed a language called Basic Combined


Programming Language, or BCPL.

Ken Thompson followed in 1970 with a similar language called B.


In 1972 Dennis M. Ritchie developed C which took many concepts from

ALGOL, BCPL and B and added the concept of data types.

C is the 1972 version of the language which was documented and


popularized in 1978 by Brian Kernighan and Dennis Ritchie now known
as the K&R standard.

[2]
1983 ANSI (American National Standards Institute) began the
National Institute of Science & Technology

definition of a standard for C approved in 1989 .


This release is called C90.

The year after, the American standard was accepted internationally


and published by ISO (ISO 9899:1990).

In 1995 minor changes were made and version known as C95.


Significant update was done in 1999, the changes incorporated and
now known as C99.

In 2011, the C standard was again changed (ISO 9899:2011). This


version is called C11. It is currently the definition of "the C language".

[3]
Why C?
National Institute of Science & Technology

• C is the common
• Originated at AT&T Bell Labs,
denominator of many of
Dennis Ritchie – implemented
today‟s languages 1972
• C‟s strong points • Development language for
– very efficient UNIX operating system
– weakly typed language
– Small structured language with
many operators
– Small set of keywords (ONLY
32!)
– Has no input/output statements!
It uses function calls.

[4]
Creating C Programs
National Institute of Science & Technology

There are four fundamental stages, or processes, in the


creation of any C program:

•Editing
•Compiling
•Linking
•Executing

[5]
National Institute of Science & Technology

Editing is the process of creating and modifying C source code.

The compiler converts your source code into machine language and
detects and reports errors in the compilation process.

The output from the compiler is known as object code and it is stored in
files called object files,
cc myprog.c

The linker combines the object modules generated by the compiler from
source code files, adds required code modules from the standard library
supplied as part of C, and welds everything into an executable whole.

[6]
National Institute of Science & Technology

The execution stage is where you run your program, having completed
all the previous processes successfully.

When the compiler has successfully translated the program the compiler
version or the executable program code is stored in a file called a.out,
or if the –o option is used the executable program code is put in the file
listed after the –o specified in the compilation command.e.g.

cc myprog.c –o objectfile

The above command puts the compiled program into the file called
objectfile( name given by the user)

To run the executable the command is ./a.out

[7]
The two methods of compilation and execution is
National Institute of Science & Technology

given below.

cc myprog.c
./a.out

cc myprog.c –o objectfile
./objectfile

[8]
National Institute of Science & Technology

.
.

[9]
National Institute of Science & Technology

Figure: Basic Structure of a C Program

[10]
National Institute of Science & Technology

.
.

[11]
The C Character Set
A to Z
National Institute of Science & Technology

a to z
0 to 9
Special Character
+ - * / = % & #
! ? ^ “ ‘ ~ \ |
< > ( ) { } [ ]
: ; . , _ @ $
blank space (Handled Specially)

Combination of characters
\n \t \b etc used instead of controller characters.

[12]
Identifiers: Name given to various programming element like
National Institute of Science & Technology

Variables, Functions, Array etc.


Rules for Identifiers:
Upper and lower case letters
Digits (0 to 9)
_(under score)
case sensitive
digit can not be the first character
can start with a „_‟ (under score)

An Identifier can be arbitrarily long (meaning vs length)


Some compiler recognize only first 8 some upto 31

[13]
Valid Identifiers:
X y12 sum_1 _temp
National Institute of Science & Technology

Names area Tax_Rate TABLE

InValid Identifiers:
4th “x” order-on order flag

Check for validity


$tax recORd1 name_and_address 123-45-67
Name and Adresss file-3 A123_45_678

[14]
Key Words:
certain reserved words that have standard predefine meaning in C
National Institute of Science & Technology

programming.
can not be used as an Identifier ( But uppercase names are allowed)

auto extern sizeof break float static


case for struct char goto switch
const if typedef continue int union
default long unsigned do void register
double return volatile else short while
enum signed

[15]
Data Types in C Language
National Institute of Science & Technology

The type , or data type of a variable determines a set of values that a


variable might take and a set of operations that can be applied to those
values. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.

Data type:
Primitive /basic data type: char, int, float, double
Derived data type: array, function, pointer
User defined data types: structure, union, enum
Valueless: void.

[16]
New Data Types of C99
National Institute of Science & Technology

There are some new data types introduced in C99. They


are
_Bool,
_Complex
_Imaginary

C has four type qualifiers, also known as type modifiers


which precede the basic data types.
Short
Long (to increase the size of int or double )
Signed
Unsigned.

[17]
National Institute of Science & Technology

.
.

[18]
Name Range Storage Size
National Institute of Science & Technology

byte –27 (-128) to 27–1 (127) 8-bit signed

short –215 (-32768) to 215–1 (32767) 16-bit signed

int –231 (-2147483648) to 231–1 (2147483647) 32-bit signed

long –263 to 263–1 64-bit signed


(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308

[19]
Floating-Point
. Types
C provides representations of real numbers and those
National Institute of Science & Technology

representations are finite.

Following table gives you details about standard floating-point


types with storage sizes and value ranges and their precision:

Type Storage size Value range Precision


Float
(single precission 4 byte 1.2E-38 to 3.4E+38 6 decimal places
floating point number)
Double
(double precission 8 byte 2.3E-308 to 1.7E+308 15 decimal places
floating point number)
long double
3.4E-4932 to
(long double precission 12byte 19 decimal places
.
floating point number)
1.1E+4932

[20]
AN EXAMPLE …
National Institute of Science & Technology

#include <limits.h> // For limits on integer types


#include <float.h> // For limits on floating-point types

printf("Variables of type short store values from %d to %d\n", SHRT_MIN,


SHRT_MAX);

printf("Variables of type unsigned short store values from 0 to %u\n",


USHRT_MAX);

printf("Variables of type int store values from %d to %d\n", INT_MIN,


INT_MAX);

printf("Variables of type unsigned int store values from 0 to %u\n",


UINT_MAX);

[21]
National Institute of Science & Technology

Character Data Type

We will discuss about ASCII


Character in C is stored as one byte integer
So a character can be interpreted as a number also.
Can be signed or unsigned
Don‟t have to bother: to use character between (0 - 127)
Characters are represented in single quotes

[22]
ASCII may refer to any of the following:
Short for American Standard Code for Information
National Institute of Science & Technology

Interexchange, ASCII is a standard that assigns letters,


numbers, and other characters in the 256 slots available in
the 8-bit code.

The ASCII table is divided into three different sections.


Non-printable, system codes between 0 and 31.

Lower ASCII, between 32 and 127. This table originates from the older,
American systems, which worked on 7-bit character tables.

Higher ASCII, between 128 and 255. This portion is programmable;


characters are based on the language of your operating system or
program you are using.

[23]
. Decimal Binary character
National Institute of Science & Technology

48 110000 0
57 111001 9
97 1100001 a
122 1111010 z
65 1000001 A
90 1011010 Z

Example
. : ASCII VALUES

[24]
The
. void Type
National Institute of Science & Technology

The void type specifies that no value is available. It is used in three kinds of situations:

S.N. Types and Description


1 Function returns as void :There are various functions in C which do not return
value or you can say they return void. A function with no return value has the
return type as void.
2 Function arguments as void :There are various functions in C which do not accept
any parameter. A function with no parameter can accept as a void.
3 Pointers to void :A pointer of type void * represents the address of an object, but
not its type.

[25]
Tokens in C
A C program consists of various tokens and a token is either a
National Institute of Science & Technology

keyword, identifier, a constant, a string literal, or a symbol.

For example, the following C statement consists of five tokens:


printf("Hello, World! \n");

The individual tokens are:


printf
(
"Hello, World! \n"
)
;

[26]
Keywords
National Institute of Science & Technology

Keywords are standard identifiers that have standard predefined


meaning in C. Keywords are all lowercase.

Points to remember

1. Keywords can be used only for their intended purpose.


2. Keywords can't be used as programmer defined identifier.
3. The keywords can't be used as names for variables.

[27]
auto else long switch
National Institute of Science & Technology

break enum register typedef


case extern return union
char float short unsigned

const for signed void


continue goto sizeof volatile

default if static while


do int struct double

Key Words : 32

[28]
Whitespace in C
National Institute of Science & Technology

A line containing only whitespace, possibly with a


comment, is known as a blank line, and a C compiler
totally ignores it.

Whitespace is the term used in C to describe blanks,


tabs, newline characters and comments..

[29]
Variable and Its Declaration
A variable is an Identifier for a memory location In which
National Institute of Science & Technology

the data can be stored and retrieve.


Variable are Associated with a Data Type
Once Assigned, Data type can not be changed. But value
in the variable can be changed.
Name of the variable should explain its feature and its
use.

[30]
Variable Declaration
DataType VarableList;
National Institute of Science & Technology

Examples:
int a, test, check;
float takeFirst, takeSecond;

Can also be written as:


int a;
int test;
int check;
float takeFirst;
float takeSecond;
[31]
Example:
National Institute of Science & Technology

main()
{
int x, z, k;
k = x + z;
printf(“ Value of k is %d”,k);
}

Need to assign value before using a variable


Better to assign the values at the time of declaration

[32]
Variable Initialization
National Institute of Science & Technology

Assigning values to the variables at the time of declaration


is called Initialization

Example:

int x=23,y=2;
float k;
k = x+y;

Not Compulsory but Recommended.

[33]
Operators in C
National Institute of Science & Technology

What is Operator?
An operator is a symbol that specifies the arithmetic,
logical or relational operation to be performed. C
language supports following type of operators.

[34]
National Institute of Science & Technology

.
.

[35]
Arithmetic Operators in C
National Institute of Science & Technology

Operators which performs arithmetic operation on operands


are called arithmetic operators.

 Unary Operators:
Operate on one operand
 Binary Operators:
Operate on two operands
 Ternary Operators:
Operates on three operands

[36]
Unary Arithmetic Operator
National Institute of Science & Technology

+ Identity Operator or unary plus


- Negation Operator or unary minus
++ Increment Operators
-- Decrement operators

[37]
Binary Arithmetic Operator
National Institute of Science & Technology

+ Addition Operator A+B


- Subtraction Operator A-B
* Multiplication Operator A*B
/ Division Operator A/B
% Modulus Operator A%B

 All operators except % can work on both integers and


floating point numbers or mixed numbers
 If the operation results in a value more than the range of
the data type then the MSBs are dropped (True for unsigned
data type)
 For signed data type it is implementation dependent
[38]
Arithmetic Operators
National Institute of Science & Technology

• If the data type of both the operands are same than operation will be
performed in the same data type and result will be in the same data
type.

• But the minimum data type should be integer (char and short are
converted into integer before actual operation)

• If they are different than the data type of one operand will be changed to
match the other (called automatic type conversion) and the operation is
performed

• The data type of the least comprehensive variable changes to the data
type of the most comprehensive variable. Type Promotion

[39]
Automatic Type Conversion
National Institute of Science & Technology

char c; int j; float f; double d, r;


Long Double
r = ( c * j) + (f / j) – (f + d)
Double
Float int float double
Long
Int float double
Short

Char double

[40]
Multiple Assignment Operators ( =)
National Institute of Science & Technology

x = y = z = 5; associativity is from right to left


z = 5 is an expression
value of the expression is 5 which is assigned to y
Value of the expression y = 5 is 5 which is assigned
to x ;

Equivalent to
z = 5;
y = z;
x = y;

[41]
Type Conversion During Assignment
National Institute of Science & Technology

Variable = Expression;
What if data type of the variable is not equal to the data type
of the expression;
An internal Automatic (Implicit) Type conversion
is done.
If the Lvalue is of higher data type than it can easily
accommodate the value of the expression.
But What if the case is reverse
In that case we are going to loose the higher order bit or
some information

[42]
Data Loss During Conversion
National Institute of Science & Technology

Target Type Expression Type Possible Info Loss


Char Short int (16 bits) Higher order 8 bits
Char Int (32 bit) Higher order 24 bits
Int (32 bits) Long int(32 bits) None
Int Float Fractional part +
possibly more
Float Double Precision and
rounded
Double Long Double Precision and
rounded

[43]
More on precedence for arithmetic operators
1 Unary operators has the highest precedence
National Institute of Science & Technology

2 *, /, % are at the same level of precedence


3 +, - are at the same level of precedence
• For operators at the same “level”, left-to-right ordering is
applied (left associativity)
2 + 3 – 1 = (2 + 3) – 1 = 4
2 – 3 + 1 = (2 – 3) + 1 = 0
2 * 3 / 4 = (2 * 3) / 4 = 6 / 4
2 / 3 * 4 = (2 / 3) * 4 = 0 * 4
• Parenthesis can be used to change the precedence
(does not hamper speed)

[44]
Increment (++) & Decrement (--) Operators
National Institute of Science & Technology

used to increment or decrement the value of the variable by


one;
Two Basic Rules
1. operand must be a variable (can not be constants or
expression)
2. ++ or -- can precede or succeed the operand
Known as pre increment and post increment
int I = 5;
I ++; or ++ I (is same as I = I + 1; but executed faster)
Similarly I --; or -- I ; (Is same as I = I -1;)

[45]
Assignment Operators ( =)
National Institute of Science & Technology

variable_name = expression;
Lvalue = Rvalue

I = 6;
X = m * 23 + k;
Lvalue should be a memory location which can store a
value; a variable
where Rvalue can be a variable or a constant or an
expression.
A + B = 5 +2;
Assignment operator has got the least precedence

[46]
Compound Assignment Operators ( =)
National Institute of Science & Technology

x = x+5;

x += 5;

Similarly
-=, *= , /=, %= etc are different compound
assignment statements

[47]
Comparison Operators
National Institute of Science & Technology

Equality Operator
== equal to operator (checks for equality)
!= not equal to operator (checks for in equality)

Don’t get confused with == and =

Relational Operators
> Greater than operator
< Less than operator
<= Less than equal to operator
>= Greater than equal to operator

[48]
Table of Relational Operators
National Institute of Science & Technology

Operator Meaning
A == B is A equal to B ?
A < B is A less than B ?
A <= B is A less than or equal to B ?
A > B is A Greater than B ?
A >= B is A Greater than or equal to B ?
A != B is A not equal to B ?

All these operators take two operand and compare them. And return 1 for
true and 0 for false
[49]
Boolean Expressions
National Institute of Science & Technology

Expression Value Expression Value

25 < 25 false 25 != 25 false

25 <= 25 ?? 25 > 25 false

25 >= 25 true 25 = 25
??

-5 < 7 true -305 <= 97 true

If A>B is FALSE than what is the value of A<B


[50]
Playing with Conditionals
National Institute of Science & Technology

int x=0, y=10, w=20, z, T=1, F=0;


Find Out the value of Z after each statement
z = (x == 0);
z = (x = 0);
z = (x == 1);
z = (x = 15);
z = (x != 2);
z = (x < 10);
z = (x <= 50);

[51]
• Logical Operators
National Institute of Science & Technology

–! Logical Negation (Unary)


– && Logical AND Operator
– || Logical OR Operator
! - Negation operator
!(T) F
!(F) T
|| - Logical OR Operator && - Logical AND Operator
F || F F F && F F
F || T T F && T F
T || F T T && F F
T || T T T && T T [52]
Certain Rules
National Institute of Science & Technology

While evaluating the logical value of a expression a non


zero value is treated as TRUE and Zero is treated as
FALSE.
Logical operators are evaluated until an expression is
known to be true or false
X=0
Example Y=2
int x=5, y=2, z; Z=0
Z = (x=0) && (++Y);

What is the value of X, Y, Z after the statements get


executed.
[53]
Certain Rules (cont..)
National Institute of Science & Technology

If logical AND operation is being performed, the


evaluation is stopped when it finds the first FALSE
operand.

If Logical OR is being performed the evaluation


stops if it finds the first TRUE expression.

[54]
Declaration of a variable in C hints the compiler about the type
and size of the variable in compile time. Similarly,
National Institute of Science & Technology

declaration of a function hints about type and size of function


parameters. No space is reserved in memory for
any variable in case of declaration.
Example: int a;
Here variable 'a' is declared of data type 'int'
Defining a variable means declaring it and also allocating space
to hold it.
We can say "Definition = Declaration + Space reservation".
Example: int a = 10;
Here variable "a" is described as an int to the compiler and
memory is allocated to hold value 10.

[55]
Precedence of C Operators:
National Institute of Science & Technology

Associativity
Their associativity indicates in what order operators of
equal precedence in an expression are applied

Precedence means Priority Of Operator

[56]
Precedence and Associativity are two characteristics of operators
National Institute of Science & Technology

that determine the evaluation order of subexpressions in absence of


brackets.

Associativity is only used when there are two or more operators of


same precedence.

All operators with same precedence have same associativity

Precedence and associativity of postfix ++ and prefix ++ are different

Comma has the least precedence among all operators and should be
used carefully

[57]
An Example:
National Institute of Science & Technology

#include<stdio.h>
int main()
{
int a;
a = 1, 2, 3; //Evaluated as (a = 1), 2, 3
printf("%d", a);
return 0;
}

[58]
National Institute of Science & Technology

.
.

[59]
National Institute of Science & Technology

Precedence Examples

a*b+c (a*b)+c
a-b+c (a-b)+c
a++b a+(+b)
a+++b (a++)+b not a+(++b)
a++++b (a++)+(+b)

[60]
Associativity of operators
National Institute of Science & Technology

Associativity indicates in which order two operators of


same precedence(priority) executes.

Let us suppose an expression:


a==b!=c

Here, operators == and != have same precedence. The


associativity of both == and != is left to right, i.e, the
expression in left is executed first and execution take pale
towards right.

Thus, a==b!=c equivalent to :


(a==b)!=c

[61]
.
National Institute of Science & Technology

This expression is evaluated in this order


1+2*2 1+(2*2)
1+2*2*4 1+((2*2)*4)
(1+2)*2*4 ((1+2)*2)*4
1+4,c=2|3+5 (1+4),(c=(2|(3+5)))
1 + 5&4 == 3 (1 + 5) & (4 == 3)
c=1,99 (c=1),99
!a++ + ~f() (!(a++)) + (~(f()))
s == "klas" || i < 9 (s == "klas") || (i < 9)
r = s == "sten" r = (s == "sten")

[62]
Type Conversion and Type casting in C
National Institute of Science & Technology

Type conversion occurs when the expression has data of mixed data
types.

In type conversion, the data type is promoted from lower to higher


because converting higher to lower involves loss of precision and value.
Rules explained below

Integer types are lower than floating point types

Signed types are lower than unsigned types

Short whole number types are lower than longer types

double>float>long>int>short>char

[63]
National Institute of Science & Technology

.
Long double
Double
Float
Unsigned long int
Long int
Unsigned int
Int
Short
Char

•Fig. Rule for data type promotion in an expression

.
[64]
Q1: What is the output of the following code
segment?
National Institute of Science & Technology

int main()
{
int var1=1,var2=12,var3=12;
var1=var2==var3;
printf("%d ", var1);
return 0;
}

Options:
1: 1
2: 0
3: blank space
4: Error
[65]
Answer for Q1:
National Institute of Science & Technology

Option 1: 1

Explanation:

12 == 12 is TRUE therefore var1=1

== has high priority than =

[66]
Q2: What is the output of the following code
segment?
National Institute of Science & Technology

int main()
{
int c= - -10;
printf("%d",c);
return 0;
}
Options:
1: -10
2: - - 10
3: 10
4: Error

[67]
Answer for Q2:
National Institute of Science & Technology

Option 3: 10

Explanation:
Output: 10
-ve(of -ve) is +ve if we write c=--10 it gives error lvalue
required as decrement operand
Hence we have to write - - i.e. a space in between.
Associativity of – (unary minus operator) is from right to
left.

[68]
National Institute of Science & Technology

Q3: Write a c program to print Hello world


without using any semicolon.

[69]
Answer for Q3:
#include<stdio.h>
National Institute of Science & Technology

int main(){
if(printf("Hello world")){
}
return 0;
}
---------------------------------------
#include<stdio.h>
int main(){
while(!printf("Hello world")){
}
return 0;
}

[70]
National Institute of Science & Technology

Q4: a variable yyyy contains the year [ e.g.,


1999 ] In just two lines calculate and print the
last 2 digits of the year which is read?

[71]
National Institute of Science & Technology

Answer for Q4:

yy = yyyy % 100;
printf("Last two digits of year is: %02d",yy);

[72]
National Institute of Science & Technology

Q5: What is the value of the N if printed?

Int m=1;
Int n;
N=(m=m+3, m%3);

Options:
1: O
2: 1
3: 0 1
4: Error

[73]
National Institute of Science & Technology

Option 2: N=1
Answer for Q5:

[74]
Q6: What is the output of the following code
segment?
National Institute of Science & Technology

Using Comma Operator along with Assignment


#include<stdio.h>
int main()
{ int i;
i = 1,2,3;
printf("i:%d\n",i);
return 0;
}
Output :
1: 1
2: 3
3: 0
4: Error

[75]
Answer for Q6:
National Institute of Science & Technology

Option 1: 1

i = 1,2,3;
Above Expression contain 2 comma operator and 1
assignment operator.
If we check precedence table then we can say that
“Comma” operator has lowest precedence than
assignment operator
So Assignment statement will be executed first .
1 is assigned to variable “i”

[76]
Q7: What is the output of the following code
segment?
National Institute of Science & Technology

int main()
{
int i;
i = (1,2,3);
printf("i:%d\n",i);
return 0;
}

Options:
1: 3
2: 1
3: 2
4: Error
[77]
National Institute of Science & Technology

Answer for Q7:

Option 1: 3:

Explanation: i = (1,2,3);
Bracket has highest priority than any operator.
Inside bracket we have 2 comma operators.
Comma operator has associativity from Left to
Right.
Comma Operator will return Rightmost operand

[78]
Q8 What is the output of the following code
segment?
National Institute of Science & Technology

int main()
{
int var1=15,var2=10,p,q;
p=var1>14;
q=var1>8 && var2==8;
printf("%d %d", p,q);
return 0;
}
Options:
1: O 0
2: 1 1
3: 1 0
4: Error

[79]
National Institute of Science & Technology

Answer for Q8:

Option 3: 1 0

Explanation:
15>14 is TRUE therefore p=1 but the second
one
15>8 && 10 == 8 is false and hence q=0

[80]
Q9: What is the output of the following code
segment?
National Institute of Science & Technology

#include<stdio.h>
int main()
{ printf("%d %d %d", sizeof(3.14f),sizeof(3.14),
sizeof(3.141L));
}

Options:
1: 4 8 12
2: 4 4 4
3: 1 1 1
4: Error

[81]
National Institute of Science & Technology

Answer for Q9:

Option 1: 1

Explanation:
3.14f is treated as float,
3.14 is promoted to double
and 3.141L is long double type.

[82]
Q10: What is the output of the following code
segment?
National Institute of Science & Technology

int main()
{
int x=4;
printf("%d ",4>>4);
printf("%d ",4<<4);
printf("%d ",x<<x>>x<<2<<x>>2);
printf("%d ",x);
}
Options:
1: 0 64 64 4
2: FBABD 0 1 2 3 4
3: 0 0 1 2 3 4
4: Error
[83]
National Institute of Science & Technology

Answer for Q10:

Option 10 64 64 4

Explanation:
3rd printf is L to R
X<<x is 4<<4 is 64
64>>x 64>>4 is 4
4<<2 is 16
16<<x is 16<<4 is 256
256 >>2 is 64

[84]
Q11: What is the output of the following code
segment?
National Institute of Science & Technology

#include<stdio.h>
int main()
{
int x=5,y;
y=~x;
printf("%d",y);
return 0;
}
Options:
1: -5
2: -6
3: 0
4: 5
[85]
National Institute of Science & Technology

Answer for Q11:

Option 2: -6
Explanation:
Bitwise 1‟s complement of 5 ( i.e., 0101 ) is
stored in y as 1010. [ left most bit is 1 so it is
sign bit].
Since the sign bit is set to 1 here so while
retrieving the value we have to find the 2‟s
compliment to get the no.
1010 „s 2complement is 0101+1 = 0110 (which is
6) since it is negative no hence -6 is printed.

[86]
Q12: What is the output of the following code
segment?
National Institute of Science & Technology

#include<stdio.h>
main(){
int i =0;
i = (2+3, 4>3, 3);
printf("%d", i);
}
Options:
1: 1
2: 5
3: 3
4: Error

[87]
National Institute of Science & Technology

Answer for Q12:

Option 3: 3
Explanation:
In the usage of comma operator, evaluation is
from the left to right, when brackets are there the
evaluation is from right to left

[88]
Q13: What is the output of the following program?
National Institute of Science & Technology

#include<stdio.h>
int main()
{
printf("%d",sizeof(5.2));
}

Options:
A. Compiler Error: Can't determine size of a constant
B. 4 (Size of float)
C. 8 (Size of double)
D. Garbage Value

[89]
National Institute of Science & Technology

Answer for Q13:

Correct answer is : C
Explanation The default type for decimal
constants is double and not float.
Hence the value 5.2 is treated as a double and 8
is printed.

[90]
Q14: What is the output of the following program?
National Institute of Science & Technology

#include<stdio.h>
int main(){
int x=4+2 % -8;
printf("%d",x);
x=4+ -2 % 8;
printf("%d",x);
return 0;
}
Options:
A. 6 2
B. 4 -2
C. 6 -2
D. -4 12
[91]
National Institute of Science & Technology

Answer for Q14:

Correct answer is : A : 6 2
The operator % is higher precendence than +

[92]
Question-15: What is the output of the
following code snippet?
National Institute of Science & Technology

#define x 5+2
int main(){
int i;
i=x*x*x;
printf("%d",i);
}

[93]
National Institute of Science & Technology

Answer:15 (explanation if any):


= 5+2 * 5+2 * 5+2
= 5+ 10 + 10 +2
= 27

ANS: 27

[94]
Question-16: What is the output of the
following code snippet?
National Institute of Science & Technology

int main(){
char c=125;
c=c+10;
printf("%d",c);
}

[95]
Answer 16: (explanation if any):
National Institute of Science & Technology

• Ans: -121

[96]
Question 17: What is the output of the
following code snippet?
National Institute of Science & Technology

int main(){
float a=5.2;
if(a==5.2)
printf("Equal");
else if(a<5.2)
printf("Less than");
else
printf("Greater than");
}

[97]
Answer -17(explanation if any):
National Institute of Science & Technology

• Ans: LESS THAN


• Explanation:
• 5.2 is double constant in c. In c size of double data is 8 byte while a
is float variable. Size of float variable is 4 byte.
• So double constant 5.2 is stored in memory as:
• 101.00 11001100 11001100 11001100 11001100 11001100
11001101
• Content of variable a will store in the memory as:
• 101.00110 01100110 01100110
• It is clear variable a is less than double constant 5.2
• Since 5.2 is recurring float number so it different for float and double

[98]
Question-18: What is the output of the
following code snippet?
National Institute of Science & Technology

int main(){
float a=4.5;
if(a==4.5)
printf("Equal");
else if(a<4.5)
printf("Less than");
else
printf("Greater than");
}

[99]
National Institute of Science & Technology

Answer -18(explanation if any):


• Ans : equal.
• Reason: Bit level representations of both are same

[100]
Question-19: What is the output of the
following code snippet?
National Institute of Science & Technology

int main() int main()


{ {
int a=2; int a=2;
a=-1<<1; a=~a+2<<1;
printf("%d",a); printf("%d",a);
} }

[101]
National Institute of Science & Technology

Answer-19 (explanation if any):


• -2 in both the cases.

[102]
Question-20: What is the output of the
following code snippet?
National Institute of Science & Technology

int main()
{
char *str="Hello world";
printf("%d",printf("%s",str));
}

[103]
National Institute of Science & Technology

Answer-20(explanation if any):

Output - Helloworld11

[104]
Question-21: A Simple prediction
National Institute of Science & Technology

int y = 2,
z = (y++, ++y);
printf("%d\n", z);

[105]
National Institute of Science & Technology

Answer-21(explanation if any):
Answer: 4

[106]
Question-22: Simple prediction
National Institute of Science & Technology

#include <stdio.h>
int main()
{
int a = 2 + 4 + 3 * 5 / 3 - 5;
printf("%d", a);
}

[107]
National Institute of Science & Technology

Answer-22(explanation if any):
ANSWER 6

[108]
Question-23: A simple prediciton
National Institute of Science & Technology

#include <stdio.h>
int main()
{
int a = 5 * 3 % 6 - 8 + 3;
printf("%d", a);
}

[109]
National Institute of Science & Technology

Answer-23(explanation if any):
ANSWER -2

[110]
Question-24: output ??
#include <stdio.h>
National Institute of Science & Technology

int main()
{
int b = 6;
int c = 7;
int a = ++b + c--;
printf("%d", a);
}

[111]
National Institute of Science & Technology

Answer(explanation if any):
ANSWER - 14

[112]
Question-25: Output??
#include <stdio.h>
National Institute of Science & Technology

int main()
{
double b = 5 % 3 & 4 + 5 * 6;
printf("%lf", b);
}

[113]
National Institute of Science & Technology

Answer(explanation if any):
ANSWER 2.0000000
The precedence of operators is
*
%
+
&

[114]
Question-26:
#include <stdio.h>
National Institute of Science & Technology

int main()
{
double b = 3 && 5 & 4 % 3;
printf("%lf", b);
}

[115]
National Institute of Science & Technology

Answer(explanation if any):
Output: 1.0000000000

The precedence of operators is


• %
• &
• &&

[116]
National Institute of Science & Technology

[117]
Question 27: Predict the output??
National Institute of Science & Technology

#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;

mean = (double) sum / count;


printf("Value of mean(double) sum / count= : %f\n", mean );
mean = (double) ( sum / count);
printf("Value of mean =(double) ( sum / count)= : %f\n", mean );

[118]
National Institute of Science & Technology

Answer:
Output:
Value of mean(double) sum / count = 3.4000000 Value of
mean =(double) ( sum / count)= 3.00000

[119]
Question 28 – SIMPLE guess!
National Institute of Science & Technology

#include<stdio.h>
int main()
{
int j=1;
j+= j+= +j++;
printf("%d ", j);
return 0;
}

[120]
National Institute of Science & Technology

• Output: 5

[121]
QUESTION-29
What is the output?
National Institute of Science & Technology

#include<stdio.h>
int main()
{
printf("%d %d %d ", sizeof(3.14f), sizeof
(3.14), sizeof(3.141L));
return 0;
}

[122]
• Output: 4 8 12
National Institute of Science & Technology

• 3.14f is treated as float


• 3.14 promoted to double
• 3.141L is long double type

[123]
QUESTION -30 – What is the output?
National Institute of Science & Technology

#include<stdio.h>
int main(main)
{
int k;
if(printf("%o",k=(~2|3) >-0? 7:8<<2));
return 0;
}

[124]
• Output: 30
• =(~2|3) >-0 generates FALSE hence 8<<2 is 32 and its
National Institute of Science & Technology

equivalent octal is 40

[125]
National Institute of Science & Technology

INPUT / OUTPUT in „C‟

[126]
There are two files attached to this device:
National Institute of Science & Technology

the standard input file (named stdin) and the standard


output file (named stdout).
These files are sequential files.

The frequently used C/C++ library functions for I/O


operations are:

For input: getch, getche, gets, scanf, sscanf ;


For output: putch, puts, printf, sprintf.
Macros getchar, for input, and putchar, for output,
supplement these set.

[127]
gets and puts functions:
char *gets (char *s);
National Institute of Science & Technology

int puts (const char *s);

example is:

#include <stdio.h>
int main()
{
char s[200];
printf("\nPlease input a character string and press ENTER\n");
gets(s);
printf("\nThe character string is\n");
puts(s);
return 0;
}

[128]
scanf ( )
The scanf function allows you to accept input from standard in i.e.,
National Institute of Science & Technology

keyboard.
Format of scanf is:

int scanf(const char *format , variable list);

format describes the format of the input and the variables are the
pointers to the variables in which the input will be stored..

List of format specifiers are :

[129]
Type Conversion
specifier
. Char %c
National Institute of Science & Technology

Short int %hd


Int %d
Unsigned int %u
Long int %ld
Unsigned long %lu
Long long int %lld
Float %f
Double %f
Long double %Lf
Scientific notation %e
(mantissa/exponent)
using e character
Scientific notation %E
(mantissa/exponent)usi
ng E character
String of character %s
Unsigned hexadecimal %x
Unsigned hexadecimal %X
integers(capitals)
Pointer address %p
Signed octal %o
Use the shorter of %e %g
or %f.
. Use the shorter of %E %G
or %f

[130]
The. prototype for scanf is located in the header file named stdio.h, and
is as follows:
National Institute of Science & Technology

% [*] [field_width] [length_modifier] conversion_character


where components in brackets [ ] are optional.
The general form of a scanf() specifier is
* optional, read but do not assign value to an object. The suppression flag(*)
tells scanf that the next input field to be read but not stored. It is discarded.

[131]
Example program to show the reading input with the floating
point conversion specifiers
National Institute of Science & Technology

#include<stdio.h>
int main()
{

double a,b,c;
printf("enter three floating point numbers \n");
scanf("%le%lf%lg",&a,&b,&c);
printf("numbers entered in plain floating point notation\n ");
printf("%f\n%f\n%f\n",a,b,c);
return 0;
}
Output:
enter three floating point numbers
1.23456
1.23456e+03
3.15152e-06
numbers entered in plain floating point notation
1.234560
.
1234.560000
0.000003
[132]
A scan set scans the characters in the input stream , looking only for
National Institute of Science & Technology

those characters that match the characters contained in the scan set,
if match occurs then stored else not.

#include<stdio.h>
int main()
{
char c;
char y[10];
printf(“enter a string \n”);
scanf("%[aeiou]s",y);
printf("char is %s ",y);
return 0;
}
Output:
Enter a string : aaeeppiioouu
char is aaee

[133]
printf( )
National Institute of Science & Technology

int printf(const char *format ,expression list);

values displayed with e,E,f show six digits of precission to


the right of the decimal point by default.

e and E prints lowercase and uppercase preceeding the


exponent

printf("%e\n",123.89); // prints as 1.238900e+002


printf("%E\n",1234567.89); // prints as 1.234568E+006
printf("%f\n",1234567.89); // prints as 1.234567.890000

[134]
int x=12345;
float z=123.45;
National Institute of Science & Technology

printf("%09d \n",x); //right justified with four 0's before


printf("%010.2f \n",z);//padding for a float varaible right
justified
printf("%-10.2f \n",z); //no padding for left justification

[135]
The program shows the format specifier for the floating variable -ve
number so left justifed value will come here
National Institute of Science & Technology

#include<stdio.h>
#include<stdlib.h>
int main()
{
float z=123.45f;
printf("%-f\n",z); // note: 123.44997 will not come here.
printf("%-9.0f\n",z); // total 9 spaces, 0 space for decimal
printf("%-9.1f\n",z); // total 9 spaces, 1 space for decimal
printf("%-9.2f\n",z); // total 9 spaces, 2 space for decimal
printf("%-9.3f\n",z); // total 9 spaces, 3 space for decimal
return 0;
}

[136]
float neg=-123.4500f;
National Institute of Science & Technology

float pos=123.4500f;

printf("%f\n",neg);
printf("%e\n",neg);
printf("%f\n",pos);
printf("%e\n",pos);

[137]
Program to show the various output examples
printf("%5d\n",123);
printf("%-5d\n",123);
National Institute of Science & Technology

printf("%05d\n",123);
printf("%x\n",123u);
printf("%#x\n",123u);

printf("|%-10.2f|\n",12.3333);
printf("|%-10.3f|\n",12.3333);
printf("|%-10.4f|\n",12.3333);

printf("|%10.2f|\n",12.3333);
printf("|%10.3f|\n",12.3333);
printf("|%10.4f|\n",12.3333);

printf("the number is: %6d \n",123);


printf("the number is: %-6d\n",123);

printf("the number is:%8.2f\n",233.12);


printf("the number is:%-8.2f\n",233.12);

printf("the number is:%08.2f\n",233.12);

printf("the character is %8c\n",'A');

printf("|%+12.2f|\n",-93.2);
printf("|%0+12.2f|",-93.2);
[138]
National Institute of Science & Technology

Thank you ..
[139]

You might also like