230
C (Not SHE) ki PATHSHALA (SUSWAGATAM) Sabhi ko mera yane Ketan urf Nano ka Pyar Bhara Namshkar Ap aye hum khush ho gaye

Tech tut

Embed Size (px)

Citation preview

Page 1: Tech tut

C (Not SHE) ki PATHSHALA(SUSWAGATAM)

Sabhi ko mera yane Ketan urf Nanoka Pyar Bhara Namshkar

Ap aye hum khush ho gaye

Page 2: Tech tut

In Points pe Gaur Kijiye

• We r here for Discussing C programming Fundas…so that u will rock ur campus placements

• I will discuss some points with you. Yeh koiroutine class nahi hai…I feel u will enjoy these sessions..as Mera moto hai classes fun honichahiye….

Page 3: Tech tut

What u expect from me and answers

• If you expect that u will be a champ after attending these sessions then u ve wrong impression…mai bhagwan nahi hun ki joh apkic chand dino me acchi kar dunga….

• If u ask kya mere sessions boring( boys kibhasha me c se start hone wala word) hoge tohmy answers is at some points can be boring but overall they will be fun

Page 4: Tech tut

• U will keep ur Cell phones in Silent modes….

• If u r seating near ur bf(for girls I guess :P),ff(for both boys and girls) and gf ( again for boys I guess :P) make sure u do not chit chat with them as it disturbs me and itz really annoying

• You will get plenty of time for discussions, games and masti for making noise

What I expect from you and answers

Page 5: Tech tut

• Pz do not be shy in asking me any difficulty…for personally asking ur difficulty write ur problem on any blank page…rt urname and email id…or I will rt to you uranswer the next day…

• OR SIMPLY RAISE UR HAND AND ASK….

Page 6: Tech tut

Bhaiyo & Behno PZ NOTE IT…..

• If you want be a real gud programmer in C do following things :-

A] Always make a flowchart before writing the program..HUM SAB PRACTICALS ME PAHILE PROGRAM TAPTE HAI…THEN WE MAKE FLOWCHART…REALLY BAD PRACTISE….

B]Make Memory Blocks on paper for any kind of variables or operations…apki adhi se jaydadifficulties yehi solve ho jayegi…C LANG is all abt Memory Management

Page 7: Tech tut

C]Practice makes the MAN as well as the WOMEN perfect…so do it as much as you can…

D]AB what u need to crack campus questions is Develop understanding of basic things in C and develop the skill of debugging a program

E]They try to test ur debugging skills by asking yourself simple questions on basic concepts…like for eg rules for integer declaration…

Page 8: Tech tut

My way…..

• My way is Simple…I will mostly try to cover THEORY concepts with the help of problems …which will help you to crack the questions

• The questions have been compiled and tested and have been directly taken from campus placement tests of MNCs…which will basically show you how they ask…and What they ask…

Page 9: Tech tut

• I need ur support so that u shud read material like any gud c book of kanitker sir alongside my sessions after going home…so that it will help you…

• I can not teach you everything in detail as I do not have time…you will see that at the end of the course u will know what kind of questions are asked and what shud be ur attitude and approach towards solving them and what data is required to solve them

Page 10: Tech tut

Topics which we will do… 1]Types, Operators and Expressions

2]Control Flow

3]Functions and Program Structure

4]Pointers and Arrays

5]Structures

6]Input and Output

Page 11: Tech tut

Variables & Constants :-

Def :- They are the basic data objects manipulated in program…

Ab dekhte hai variables ke bare me info joh apkopata hona chahiye for Questions….

1.Types , Operators, Expressions

Page 12: Tech tut

• You will be asked questions on variable naming rules….Typical rules on which questions are asked are :-

Page 13: Tech tut

What will be output of the following c program?#include<stdio.h>int main()

{int _=5;int __=10;int ___;___=_+__;printf("%i",___);return 0;

}

A]5 B]10 C]15 D]Compilation Error E]None of these

Page 14: Tech tut

• ANS – C]15…..Reason :- Important rule for variable naming says that the first character in the name must be a letter…But “_” underscore is counted as a letter….Yeh Trick thi wahan pe….

So ap Dekh sakte hai…question was not difficult…bas yeh simple rule yad rakhiye…

Page 15: Tech tut

What will be output of the following c program?

#include<stdio.h>

int main()

{

int goto=5;

printf("%d",goto);

return 0;

}

A]5 B]* C]** D]Compilation Error E]None of these

Page 16: Tech tut

• ANS – D] Compilation Error

Reason :- We have used the word “goto” as the name for the variable and assigned it the value 5…But “goto” is a keyword in C which already has a predefined function…..so Rule kehtahai…Ki Variable Name must not contain Keyword..Note this rule…Ispe Kafi bar sawal Ata hai…

To tackle this…Just go thru the list of keywords in C..

Page 17: Tech tut

What will be output of the following c program?

#include<stdio.h>

int main(){

long int 1a=5l;

printf("%ld",1a);

return 0;

}

A]5 B]51 C]6 D]Compilation Error E]None of these

Page 18: Tech tut

• ANS :- D]Compilation ErrorReason :- Variable name must start with a Letter … But we have declared ‘1a’ and the first character in this name is a number…which is a wrong practice…

Correct Rule is the first character in variable name must be a Letter….

Page 19: Tech tut

Now , This is a very Special and Tricky question..What will be output of the following c program?

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

int class=150;int public=25;int private=30;class = class/( private – public);printf("%d",class);return 0;

}A]30 B] 2 C]Compilation Error D]None of these

Page 20: Tech tut

• ANS :- A] 30…Reason :- Now Why 30?????You see Class , Public, Private….Yeh 3 joh hai yehtin tighda kam bighda nahi hai…balki C++ kekeywords hai…

So the Point to note is…Even if you can not use the “KEYWORDS OF C” as variable names but YOU CAN USE THE KEYWORDS OF C++ AS VARIABLE NAMES…PLEASE NOTE DOWN THIS POINT….

Page 21: Tech tut

What will be output of the following c program?

#include<stdio.h>

int xyz=10;

int main()

{

int xyz=20;

printf("%d",xyz);

return 0;

}

A]10 B]20 C]30 D]Compilation Error E]None of these

Page 22: Tech tut

• ANS :- B]20Reason :- ????

You will observe that we gave the same name to both the variables…But Differences aisa haiki…Ek Variable main ke ander hai…and ek main ke bahar…so Scope of that variable inside the main remains for that main…that is it can be manipulated inside the main…

SO IMP RULE :- TWO VARIABLES CAN HAVE SAME NAME BUT IN DIFFRERENT SCOPES…

NOW SEE THE VARIATION IN THE NEXT QUESTION…..

Page 23: Tech tut

What will be output of the following c program?#include<stdio.h>int main(){

int xyz=20;{

int xyz=40;}printf("%d",xyz);return 0;

}

A]20 B]40 C]0 D] Compilation Error E]None of these

Page 24: Tech tut

• ANS – A]20

Reason :- Observe the braces…The scope of variable xyz =40 is limited to the braces in which it is declared..But the printf statement is written in the main and not in the braces…and the declaration xyz=20 is in main…so the printfwill print as 20….

AGAIN IMP RULE IS…. TWO VARIABLES CAN HAVE SAME NAME BUT IN DIFFRERENT SCOPES…

Page 25: Tech tut

What will be output of the following c program?

#include<stdio.h>

int main()

{

int main = 80;

printf("%d",main);

return 0;

}

A] 80 B]0 C]Garbage Value D]Compilation Error E]None of these

Page 26: Tech tut

• ANS :- A]80

Reason :- Yahan pe note the point ki we can declare the variable name as main….C ko koiissues nahi hai is bare me….

Page 27: Tech tut

What will be output of the following c program?

#include<stdio.h>

int main()

{

int ABC=10;

printf("%d",abc);

return 0;

}

A]10 B]0 C]5 D]Compilation Error E]None of these

Page 28: Tech tut

• ANS :- D] Compilation Error

Reason :- Variable names are character sensitive and so abc and ABC are different…

Page 29: Tech tut

Data Types

There r few data types in C viz :-

1] char :- a single byte, capable of holding one character in the local character setfor eg. Char kp =‘A’;

2] int :- an integer, typically reflecting the natural size of integers on the host machine

for eg int kp =81;

Page 30: Tech tut

3]float :- single-precision floating point (For this please check IEEE 754 2008

format.)

for eg float kp=0.23;

4] double :- double-precision floating point

(For this please check IEEE 754 2008 format.)

for eg double kp =0.23;

Page 31: Tech tut

Qualifiers

• Integers can be applied two qualifiers viz short and long.For eg.

short int sh;

long int counter;

The word int can be omitted in such declarations…

• The qualifier signed and unsigned may be applied to char or any integer….

Page 32: Tech tut

• Unsigned numbers are always positive or zero

• Obey Law of Arithmetic modulo 2n

• Where n is number of bits in the type

• So if chars are 8 bits unsigned char variables have values between 0 and 255, while signed chars have values between -128 and 127

• Whether plain chars are unsigned or signed is machine dependent

Page 33: Tech tut

What abt the sizes?• For the sizes of Data Types each compiler is free

to choose appropriate sizes for its own hardware

• But the **Conditions Applied are :-

A]Shorts and Ints are at least 16 bits

B]Longs are at least 32 bits

C]Long > Int > Short

Page 34: Tech tut

• The type long double specifies extended-precision floating point.

• float, double and long double could represent one, two or three distinct sizes

• The standard headers <limits.h> and <float.h> contain symbolic constants for all of these sizes, along with other properties of the machine and compiler.

Page 35: Tech tut

Constants • There are 5 types of Constants viz :-

1] Integer Constant :- for eg 1234 is int constant

1234l or 1234L is Long Int Constant

1234ul or 1234 UL indicates unsigned Long

1234u or 1234 U indicates unsigned int

2]Floating Point Constants :- They Contain a decimal point for eg 123.4 or 1e -2.Type is double unless suffixed… 123.4 is Double Constant

123.4f or 123.4F is floating Constant

123.4l or 123.4L is Long Double Constant

Page 36: Tech tut

3] Character Constant :- A character constant is an integer, written as one character within single quotes, such as ‘0’.The value of this is 48 according to the ASCII table and not numeric 0 as we have attached single quotes….

4]String Constant :- A string constant, or string literal, is a sequence of zero or more characters surrounded by double quotes, as in

"I am a string"

Page 37: Tech tut

• 5]Enumeration Constant :- An enumeration is a list of constant integer values, as in

enum boolean { NO, YES };

Specialty of this enum is by default the value of no wud be 0 and yes wud be 1.Boolean the name of the enum. The user can also specify the value of the constants inside. If not given then only default values are given as 0 1 2 and so on….

For eg. enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t',NEWLINE = '\n', VTAB = '\v', RETURN = '\r' };

Page 38: Tech tut

What will be output when you will execute following c code?

#include<stdio.h>

void main(){

printf("%d\t",sizeof(6.5));

printf("%d\t",sizeof(90000));

printf("%d",sizeof('A'));

}

There can not be a specific answer to this question…Why????

Page 39: Tech tut

ANS :- As we saw the values of sizes depend on the compiler choosing appropriate sizes for the hardware…there can not be a specific answer to this question….

Page 40: Tech tut

This is an information question to you…Please note the answer…

Consider on following declaring of enum.

(i) enum cricket {Gambhir,Smith,Sehwag}c;

(ii) enum cricket {Gambhir,Smith,Sehwag};

(iii) enum {Gambhir,Smith=-5,Sehwag}c;

(iv) enum c {Gambhir,Smith,Sehwag};

Which one of the above is Correct Declaration?

ANS :- ALL ARE CORRECT….

Page 41: Tech tut

Syntax of enum data type is:

enum [<tag_name>]{

<enum_constanat_name> [=<integer_ value>],

} [<var_name>,…]

Note:

[] : Represents optional .

<>: Represents any valid c identifier

Page 42: Tech tut

• This question is combined of operator and type casting that happens in C :-

What will be output when you will execute following c code?

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

signed x;unsigned y;x = 10 +- 10u + 10u +- 10;y = x;if(x==y)

printf("%d %d",x,y);else if(x!=y)

printf("%u %u",x,y);}

A] 0 0 B] 65536 -10 C] 0 65536 D]65536 0

Page 43: Tech tut

ANS :- A] 0 0… WHY???

Reason :-

x = 10 +- 10u + 10u +- 10;

10: It is signed integer constant.

10u: It is unsigned integer constant.

x :signed integer variable….

Lower data type operand always automatically

type casted into the operand of higher data type

before performing the operation and result will

be higher data type

Page 44: Tech tut

a +- b

a +(THIS IS FOR EXPRESSION) –(this gets attached as a sign of no)b

a + (-b)

This is Calculated….

Page 45: Tech tut

Signed is higher data type than unsigned int.

So, Corresponding signed value of unsigned 10u

Is +10

And As we know operators enjoy higher precedence than binary operators. So our expression is:

x = 10 + (-10u) + 10u + (-10);

= 10 + -10 + 10 + (-10);

= 0

y = x =0

Page 46: Tech tut

What will be output when you will execute following c code?

#include<stdio.h>const enum Alpha{

X,Y=5,Z

}p=10;void main(){

enum Alpha a,b;a= X;b= Z;printf("%d",a+b-p);

}A] -4 B]-5 C]11 D] 10 E]Error :- Can not modify object

Page 47: Tech tut

ANS – A]-4

Reason :- Default value of enum constant X is zero and

Z = Y + 1 = 5 + 1 = 6

So, a + b – p = 0 + 6 -10 = -4

Page 48: Tech tut

Operators

• The important operators for questions are Increment and Decrement operators, Unary operators and Logical Operators…

• Another thing that must be taken into account is precedence of operators…

Page 49: Tech tut

Increment and Decrement Operator

• The increment operator ++ adds 1 to its operand, while the decrement operator --subtracts 1.

• But the confusing and interesting part is they can be used prefix or post fix …

• For example

If n is 5

Then x = n++ will give x to be 5…as n is postfix and is calculated after the expression…

Page 50: Tech tut

• But if n is 5

And x = ++n

Then x is 6…as now ++ is pre increment and n is incremented before expression is calculated…

+ and – in unary form are the important operators in example like 10 + -(10u)

Here precedence is given to -10u and –ve sign is the unary operator and + is binary operator…

Page 51: Tech tut

• Logical operators are :-

Logical and :- &&

Logical or :- ||

These should not be confused with bitwise operators & (bitwise and) and |(bitwise or)

Page 52: Tech tut

Precedence of Operators…

Page 53: Tech tut

What will be output of the following program?

#include<stdio.h>

int main(){

int i=1;

i=2+2*i++;

printf("%d",i);

return 0;

}

Page 54: Tech tut

• ANS :- 5

Reason :- i++ is a postfix operator…so the expression i = 2 + 2 *1 will be evaluated… i = 4 and then i++ will be evaluated so it will be i =5 and i will be printed as 5…

Page 55: Tech tut

What will be output of the following program?

#include<stdio.h>

int main(){

int a=2,b=7,c=10;

c=a==b;

printf("%d",c);

return 0;

}

Page 56: Tech tut

ANS :- 0 KYUN?????

Go Back To the operator precedence table and you will see the expression a==b will be evaluated first….a = 2 and b = 7…so a is not equal to b and so the condition a==b is false and the value of the expression is 0 as the condition is false…now therefore c = 0…also observe c is declared as intand thus c= 10 will not matter and a new value will be assigned to c....

Now my questions is….if it was const c i.e. constant c in place of int c...

Page 57: Tech tut

What will be output of the following program?

#include<stdio.h>

void main()

{

int x;

x=10,20,30;

printf("%d",x);

return 0;

}

Page 58: Tech tut

ANS :- 10

Reason :- Since assignment operator (=) has more precedence than comma operator .So = operator will be evaluated first than comma operator. In the following expression

x = 10, 20, 30

First 10 will be assigned to x then comma operator will be evaluated.

Page 59: Tech tut

What will be output of the following program?

#include<stdio.h>

int main(){

int a;

a=015 + 0x71 +5;

printf("%d",a);

return 0;

}

Page 60: Tech tut

ANS :- 131….Kaise????

Reason :- Here we introduce type casting…u will observe the variable a is int…so 015 is octal number its decimal equivalent is = 5 * 8 ^ 0 + 1 * 8 ^ 1 = 5 + 8 = 13 0x71 is hexadecimal number (0x is symbol of hexadecimal) its decimal equivalent is = 1 * 16 ^ 0 + 7 * 16 ^ 1 = 1 + 112 = 113

So, a = 13 + 113 + 5 = 131

Page 61: Tech tut

Control Flow

IF – Else

if (expression)

statement1

else

Statement2

else part of an if-else is optional

Page 62: Tech tut

Common Mistake :- Use Proper Braces….Nested If

if (n > 0) if(n>0)

{ if(a>b)

if (a > b) {

z = a; z=a;

} }

else else

{ {

z = b; z=b;

} }

Page 63: Tech tut

Another Common Mistake is Use of Symbol = instead of == during comparison for eg

If(a=b) instead of if(a==b)

a=b assigns value of b to a

Where a==b properly compares the value of a

with b

Page 64: Tech tut

Else If

if (expression)

statement

else if (expression)

statement

else if (expression)

statement

else if (expression)

statement

else

statement

Page 65: Tech tut

expressions are evaluated in order

if an expression is true, the statement associated

with it is executed, and this terminates the

whole chain.

else

statement

can be omitted, or it may be used for error checking to catch an ``impossible'' condition.

Page 66: Tech tut

Switch :-

The switch statement is a multi-way decision that

tests whether an expression matches one of

a number of constant integer values, and branches

accordingly.

switch (expression) {

case const-expr: statements

case const-expr: statements

default: statements

}

Page 67: Tech tut

All case expressions must be different. The case

labeled default is executed if none of the other

cases are satisfied. A default is optional; if it isn't

there and if none of the cases match, no action at

all takes place. Cases and the default clause can

occur in any order.

Page 68: Tech tut

Break Statement…

switch (expression) {

case const-expr: statements break;

case const-expr: statements break;

default: statements

}

• By break it will leave the switch…otherwise if there is no brake statement it will go on falling and executing next cases….

• We can type return also instead of break…

Page 69: Tech tut

What will be output when you will execute following c code?

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

int a=100;if(a>10)

printf("M.S. Dhoni");else if(a>20)

printf("M.E.K Hussey");else if(a>30)

printf("A.B. de villiers");}

A] M.S.Dhoni B] M.E.K. Hussey C]A.B.de villiers

Page 70: Tech tut

ANS :- A]M.S.Dhoni

Yenna Rascala Mind it well ……

Reason :-

In case of if – if else – if else … Statement if first if

clause is true the compiler will never check rest of

the if else clause and so on.

Please Note Down…..

Page 71: Tech tut

What will be output when you will execute

following c code?

#include<stdio.h>

void main(){

int x=-1,y=-1;

if(++x=++y)

printf("R.T. Ponting");

else

printf("C.H. Gayle");

}

A] R.T.Pointing B]C.H.Gayle C]Compilation Error

Page 72: Tech tut

ANS :- C] Compilation Error …WHY ?????

Consider following statement:

++x=++y

As we know ++ is pre increment operator in the above statement. This operator increments the value of any integral variable by one and return that value. After performing pre increments above statement will be:

0=0

In C language it is illegal to assign a constant value to another constant.

Page 73: Tech tut

What will be output when you will execute

following c code?

#include<stdio.h>

void main(){

int m=5,n=10,q=20;

if(q/n*m)

printf("William Gates");

else

printf(" Warren Buffet");

printf(" Carlos Slim Helu");

}

A]William Gates B]William Gates Carlos Slim Helu

Page 74: Tech tut

ANS :- B] William Gates Carlos Slim Helu

Reason :-

Consider the following expression:

q / n * m

In this expression there are two operators. They

are: /: Division operator

*: Multiplication operator

Precedence and associate of each operator is as

follow:

Page 75: Tech tut

PRECEDENCE OPERATOR ASSOCIATE

1 /,* Left to Right

Precedence of both operators is same. Hence associate will decidewhich operator will execute first. Since Associate is left to right. So/ operator will execute then * operator will execute.= q / n * m= 20 / 10 * 5= 2 * 5=10

As we know in c zero represents false and any non-zero numberrepresents true. Since 10 is non- zero number so if clause willexecute and print: William Gates

Page 76: Tech tut

Since in else clause there is not any opening and

closing curly bracket. So compiler will treat only

one statement as a else part. Hence last

statement i.e. printf(" Carlos Slim Helu");is not

part of if-else statement. So at the end compiler

will also print: Carlos Slim Helu So output of

above code will be: William Gates Carlos Slim

Helu

Page 77: Tech tut

What will be output when you will execute following c

code?

#include<stdio.h>

void main(){

if("ABC") printf("Barack Obama\n");

if(-1) printf("Hu Jintao\n");

if(.92L) printf("Nicolas Sarkozy\n");

if(0) printf("Ben Bernanke\n");

if('W') printf("Vladimir Putin\n");

}

Page 78: Tech tut

ANS :- Barack ObamaHu JintaoNicolas SarkozyVladimir Putin

Reason :- “ABC”: It is string constant and it will always return a non-zero memory address.0.92L: It is long double constant.‘W’: It is character constant and it has ASCII Value which is non zero Number

As we know in c language zero represents false and any non-zero number represents true. In this program condition of first, second, third and fifth if statements are true.

Page 79: Tech tut

What will be output when you will execute

following c code?

#include<stdio.h>

void main(){

int a=5,b=10;

if(++a||++b)

printf("%d %d",a,b);

else

printf("John Terry");

}

Page 80: Tech tut

ANS :- 6 10

Reason :-

Consider the following expression:

++a || ++b

In this expression || is Logical OR operator. Two

important properties of this operator are:

Property 1:

(Expression1) || (Expression2)

|| operator returns 0 if and only if both expressions return a zero otherwise it || operator returns 1.

Page 81: Tech tut

Property 2:

To optimize the execution time there is rule, Expression2 will only evaluate if and only if Expression1 return zero.

In this program initial value of a is 5. So ++a will be 6. Since ++a is returning a non-zero so ++b will not execute and if condition will be true and if clause will be executed.

Page 82: Tech tut

What will be output when you will execute following c code?

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

int x=1;if(x--)

printf("The Godfather");--x;

elseprintf("%d",x);

}

Page 83: Tech tut

ANS :- Compilation ERROR….

Reason :- If you are not using { and } in if clause then you can write only one statement.

Page 84: Tech tut

What will be output when you will execute

following c code?

#include<stdio.h>

void main(){

int a=2;

if(a--,--a,a)

printf("The Dalai Lama");

else

printf("Jim Rogers");

}

A]The Dalai Lama B]Jim Rogers C] Compile Error

Page 85: Tech tut

ANS :- B] Jim RogersReason :-Consider the following expression:a-- , --a , a

In c comma is behaves as separator as well as operator. In the above expression comma is behaving as operator. Comma operator enjoy lest precedence in precedence table and its associatively is left to right. So first of all left most comma operator will perform operation then right most comma will operator in the above expression.

Page 86: Tech tut

After performing a-- : a will be 2

After performing --a : a will be 0

a=0

As we know in c zero represents false and any non-

zero number represents true. Hence else part will

execute.

Page 87: Tech tut

What will be output when you will execute following

c code?

#include<stdio.h>

void main(){

int check=2;

switch(check){

case 1: printf("D.W.Steyn");

case 2: printf(" M.G.Johnson");

case 3: printf(" Mohammad Asif");

default: printf(" M.Muralidaran");

}

}

Page 88: Tech tut

ANS :- M.G.Johnson Mohammad Asif

M.Muralidaran

If we will not use break keyword in each case the

program control will come in each case after the

case witch satisfy the switch condition.

Page 89: Tech tut

What will be output when you will execute following c code?

#include<stdio.h>

enum actor{

SeanPenn=5,

AlPacino= -2,

GaryOldman,

EdNorton

};

void main(){

enum actor a=0;

switch(a){

case SeanPenn: printf("Kevin Spacey");

break;

case AlPacino: printf("Paul Giamatti");

break;

case GaryOldman:printf("Donald Shuterland");

break;

case EdNorton: printf("Johnny Depp");

}

}

Page 90: Tech tut

ANS :- Johny Depp …WHY????

Reason :- Default value of enum constant

GaryOldman = -2 +1 = -1

And default value of enum constant

EdNorton = -1 + 1 = 0

Note: Case expression can be enum constant.

Page 91: Tech tut

What will be output when you will execute following code?#include<stdio.h>void main(){

switch(6){case 6.0f:printf("Salma Hayek");

break;case 6.0: printf(“Katrina Kaif");

break;case 6.0L:printf(“Gerard Butler");

break;default: printf(“Jonathan Rhys Meyers");

}}A]Salma Hayek B]Katrina Kaif C]Gerard Butler D] Jonathan Rhys Meyers E]Compilation Error

Page 92: Tech tut

ANS :- E]Compilation Error

Reason :-

Case expression must be integral constant

expression. If it is not integer then it is

automatically type casted into integer value.

so. (int)6.0f = 6

(int)6.0 = 6

(int)6.0L = 6

In c duplicate case is not possible.

Page 93: Tech tut

What will be output when you will execute following c code?#include<stdio.h>void main(){

switch(5/2*6+3.0){case 3:printf("David Beckham");

break;case 15:printf("Ronaldinho");

break;case 0:printf("Lionel Messi");

break;default:printf("Ronaldo");

}}A]David Beckham B] Ronaldinho C] Lionel Messi D] RonaldoE]Compilation Error

Page 94: Tech tut

ANS :- E]Compilation Error

Reason :- Consider on the expression:

5/2*6+3.0

=2*6+3.0

=12 + 3.0

=15.0

In c switch expression must return an integer

value. It cannot be float, double or long double

Page 95: Tech tut

What will be output when you will execute following c code?

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

int a=5;a=a>=4;switch(2){

case 0:int a=8;case 1:int a=10;case 2:++a;case 3:printf("%d",a);

}}A] 2 B] Compilation error C] 11

Page 96: Tech tut

ANS :- B] Compilation Error

Reason :- We can not declare any variable in any

case of switch case statement.

Suppose Now I remove the int part behind int a = 10 and int a =8 ….Now what will be the o/p????

Page 97: Tech tut

Loops

While and For

While Loop :-

while (expression)

Statement

The expression is evaluated. If it is non-zero,

statement is executed and expression is reevaluated.

This cycle continues until expression becomes zero,

at which point execution resumes after statement.

Page 98: Tech tut

For Loop :-The for statementfor (expr1; expr2; expr3)Statement

Grammatically, the three components of a for loop are expressions. Most commonly, expr1 and expr3 are assignments or function calls andexpr2 is a relational expression. Any of the three parts can be omitted, although the semicolons must remain. If expr1 or expr3 is omitted, itis simply dropped from the expansion. If the test, expr2, is not present, it is taken as permanently true, sofor ( ; ; ) {...}is an ``infinite'' loop, presumably to be broken by other means, such as a break or return.

Page 99: Tech tut

Do while Loop

The syntax of the do is

do

statement

while (expression);

The statement is executed, then expression is

evaluated. If it is true, statement is evaluated

again, and so on. When the expression becomes

false, the loop terminates.

Page 100: Tech tut

Break and Continue

Break:-

The break statement provides an early exit from

for, while, and do, just as from switch. A break

causes the innermost enclosing loop or switch to

be exited immediately.

Page 101: Tech tut

Continue :-

The continue statement is related to break, but

less often used; it causes the next iteration of

the enclosing for, while, or do loop to begin.

for (i = 0; i < n; i++)

if (a[i] < 0) /* skip negative elements */

continue;

Basically used in nesting of loops

Page 102: Tech tut

Go To and Labels

C provides the infinitely-abusable goto statement,

and labels to branch to. Formally, the goto

statement is never necessary, and in practice it is

almost always easy to write code without it.

Page 103: Tech tut

Nevertheless, there are a few situations where gotos may find a place. The most common is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from theinnermost loop. Thus:

for ( ... )I Love You;for ( ... ) {...if (disaster)goto error;}...error:/* clean up the mess */

Page 104: Tech tut

With a few exceptions like those cited here, code

that relies on goto statements is generally

harder to understand and to maintain than code

without gotos.

So it must be rarely used…The Consiquences can

be disastrous….

Page 105: Tech tut

What will be output of following c code?#include<stdio.h>extern int x;int main(){

do{do{

printf("%o",x);}while(!-2);

}while(0);return 0;

}int x=8;

Page 106: Tech tut

ANS :- 10Reason :- Here variable x is extern type. So it will search the definition of variable x. which is present at the end of the code. So value of variable x =8There are two do-while loops in the above code. AS we know do-while executes at least one time even that condition is false. So program control will reach at printfstatement at it will print octal number 10 which is equal to decimal number 8.Note: %o is used to print the number in octal format.In inner do- while loop while condition is ! -2 = 0In C zero means false. Hence program control will come out of the inner do-while loop. In outer do-while loop while condition is 0. That is again false. So program control will also come out of the outer do-while loop.

Page 107: Tech tut

What will be output of following c code?

#include<stdio.h>

int main(){

int i=2,j=2;

while(i+1?--i:j++)

printf("%d",i);

return 0;

}

HINT :- Condition ? (if true executes this) : (if false executes this)

? :- ternary operator

Page 108: Tech tut

ANS :- 1

Reason :- Consider the while loop condition: i + 1 ? -- i :++j

In first iteration: i + 1 = 3 (True)

So ternary operator will return --i i.e. 1

In c 1 means true so while condition is true. Hence printf

statement will print 1

In second iteration:

i+ 1 = 2 (True)

So ternary operator will return -–i i.e. 0

In c zero means false so while condition is false. Hence

program control will come out of the while loop.

Page 109: Tech tut

What will be output of following c code?

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

int x=011,i;for(i=0;i<x;i+=3){

printf("Start ");continue;printf("End");

}return 0;

}

Page 110: Tech tut

ANS :- Start Start Start

Reason :- 011 is octal number. Its equivalent

decimal value is 9.

So, x = 9

First iteration:

i = 0

i < x i.e. 0 < 9 i.e. if loop condition is true.

Hence printf statement will print: Start

Page 111: Tech tut

Due to continue keyword program control will

come at the beginning of the for loop and value of

variable i will be:

i += 3

i = i + 3 = 3

Second iteration:

i = 3

i < x i.e. 3 < 9 i.e. if loop condition is true.

Hence printf statement will print: Start

Page 112: Tech tut

Due to continue keyword program control will

come at the beginning of the for loop and value of

variable i will be:

i += 3

i = i + 3 = 6

Third iteration:

i = 3

i < x i.e. 6 < 9 i.e. if loop condition is true.

Hence printf statement will print: Start

Page 113: Tech tut

Due to continue keyword program control will

come at the beginning of the for loop and value of

variable i will be:

i += 3

i = i + 3 = 9

fourth iteration:

i = 6

i < x i.e. 9 < 9 i.e. if loop condition is false.

Hence program control will come out of the for loop.

Page 114: Tech tut

What will be output of following c code?#include<stdio.h>int main(){

static int i;

for(++i;++i;++i) {

printf("%d ",i);

if(i==4) break;

}return 0;

}Hint :- Value of Static int in c by default is 0.

Page 115: Tech tut

ANS :- 2 4

Reason :- Default value of static int variable in c is

zero. So, initial value of variable i = 0

First iteration:

For loop starts value: ++i i.e. i = 0 + 1 = 1

For loop condition: ++i i.e. i = 1 + 1 = 2 i.e. loop

condition is true. Hence printf statement will print2

Page 116: Tech tut

Loop incrimination: ++I i.e. i = 2 + 1 =3

Second iteration:

For loop condition: ++i i.e. i = 3 + 1 = 4 i.e. loop

condition is true. Hence printf statement will print

4.

Since is equal to for so if condition is also true.

But due to break keyword program control will

come out of the for loop.

Page 117: Tech tut

What will be output of following c code?

#include<stdio.h>

int main(){

int i=1;

for(i=0;i=-1;i=1) {

printf("%d ",i);

if(i!=1) break;

}

return 0;

}

Page 118: Tech tut

ANS :- -1

Reason :- Initial value of variable i is 1.

First iteration:

For loop initial value: i = 0

For loop condition: i = -1 . Since -1 is non- zero

number. So loop condition true. Hence printf

function will print value of variable i i.e. -1

Since variable i is not equal to 1. So, if condition is

true. Due to break keyword program control will

come out of the for loop.

Page 119: Tech tut

What will be output of following c code?

#include<stdio.h>

int main(){

for(;;) {

printf("%d ",10);

}

return 0;

}

Page 120: Tech tut

ANS :- Infinite Loop

Reason :- In for loop each part is optional.

Page 121: Tech tut

What will be the output ?

include<stdio.h>

int main(){

int i;

for(i=0;i<=5;i++);

printf("%d",i);

return 0;

}

Page 122: Tech tut

ANS :- 6

Reason :- Its possible for loop without any body

Page 123: Tech tut

Finite or Infinite????

#include<stdio.h>

int main(){

char c=125;

do

printf("%d ",c);

while(c++);

return 0;

}

Page 124: Tech tut

ANS :- Finite times

Reason :- If we will increment the char variable c

it will increment as:

126,127,-128,-127,126 . . . . , 3, 2, 1, 0

When variable c = 0 then loop will terminate.

Page 125: Tech tut

3.Functions and Program Structures

• What is function in C programming?

• DefinitionFunction is block or part of program. When any program is very long or same code is repeating many times then we try to cut the program in different parts (or blocks) so that whole program became more understandable, easier to debug (error checking) and size of code will be lesser.

Page 126: Tech tut

Syntax of Function :-

// Function Declaration

<return_type> <function_name>(<parameters>,…);

//Function Defination :-

<return_type> <function_name>(<parameters>,…){

Statement 1;

Statement 2;

return expression;

}

Page 127: Tech tut

Simple example of function structure

int sum (int,int); //function declaration

void main(){

int p;

p=sum(3,4); //function call

printf(“%d”,sum);

}

int sum( int a,int b) //function definition{

int s; //function body

s=a+b;

return s; //function returning a value }

Page 128: Tech tut

There are Rules for Function naming…Please chk

them out…I leave this as exercise to you…

Return type of function in c programming:-

return is keyword of c. When the control reaches

to the return keyword it immediately terminates

the execution of that function and transfer the

control to the calling function.

Page 129: Tech tut

void dev();void main(){

clrscr();printf("one\n");dev();printf("two\n");getch();

}void dev(){

printf("three\n");return;printf("four\n");

}

Page 130: Tech tut

ANS :- one three two

As after return nothing wud be executed

Page 131: Tech tut

Primitive data type.

Primitive data types are: char, int, float, double, void

Examples:

a. function which is returning char data type

b. function which is returning int data type

c. function which is returning float data type

d. function which is returning double data type

e. function which is returning void data type

Page 132: Tech tut

Derived data type.

Derived data types are: array, function, pointer

Examples:

a. Function which is returning array

b. function which is returning function

c. function which is returning pointer

Page 133: Tech tut

User defined data type.

User defined data types are: structure, union, enum

Examples:

a. Function which is returning structure

b. Function which is returning union

c. Function which is returning enum

Page 134: Tech tut

Function can return only one value at time…

Storage classes allowed with return type are

static, extern, typedef i.e. we cannot use auto and

register storage class with the return type of any

function.

For eg

Page 135: Tech tut

auto int tcs(int);

void main(){

int a=5;

a=tcs(a);

printf("%d",a);

}

auto int tcs(int x){

return x++;

}

Output: Compilation error

Page 136: Tech tut

In return type we can use modifier like short, long, signed, unsigned, extern, static, const, volatile etc.

long unsigned static const ddlg(){static const long unsigned a=0101; // This is octal number….

return a;

}

void main(){

long number;

number=ddlg();

printf("%X",number); // %x – Hexadecimal equivalent

}

Output:41

Page 137: Tech tut

Parameter or argument of function

Parameter of function can be:

1. Primitive data type.

2. Derived data type.

3. User defined data type.

4. Ellipsis i.e. variable number of parameter.

Page 138: Tech tut

float sachin(int x){

float r=(float) x;

return r;

}

void main(){

float f;

f=sachin(33);

printf("%f",f);

}

Output : 33.000000

Page 139: Tech tut

void main(){

float f;f=sachin(33);printf("%f",f);

}

float sachin(int x){

float r=(float)x;

return r;

}

Output : Compilation error

Page 140: Tech tut

float sachin(int);

void main(){float f;

f=sachin(33);

printf("%f",f);

}

float sachin(int x){

float r=(float)x;

return r;

}

Output: 33.000000

Page 141: Tech tut

typedef float kp (int,char);

void main(){

float num,num1,num2;

kp a,b;

num1=a(5,'a');

num2=b(6,'0');

num=num1+num2;

printf("%f",num);

}

Page 142: Tech tut

float a(int x, char y){

x=x+y;

return (float)x;

}

float b(int p,char q){

p=q-p;

return p;

}

Output: 144.000000

Page 143: Tech tut

void main(){

float num,num1,num2;

num1=a(5,'a');

num2=b(6,'0');

num=num1+num2;

printf("%f",num);

}

Page 144: Tech tut

float a(int x, char y){

x=x+y;

return (float)x;

}

float b(int p,char q){

p=q-p;

return p;

}

Output: Compilation error

Page 145: Tech tut

Remember this For interview that

Function’s declaration doesn’t reserve any

memory space.

Page 146: Tech tut

Function Recursion in C

Calling of same function from its function body is

known as function recursion. It is alternative of

loop. Any c program which is possible using loop

it must be possible using function recursion.

Page 147: Tech tut

Find the sum of all even numbers from 0 to 20 using function recursion.

Program:

void main(){

int total;

total=sum(2);

printf("%d",total);

}

Page 148: Tech tut

int sum(int i){

static int even=0; // between successive calls we have to make sure even becomes zero so we use static……

if(i<=20){

even=even+i;

sum(i+2); //calling same function

}

return even;

}

Output: 110

Page 149: Tech tut

It is very difficult to understand the execution as

well as to write the function recursion program.

If any person is writing such program directly he

may be memorized that program.

Now note down the steps for writing the

program…

Page 150: Tech tut

Step 1: Write the same program using while loop and function. Here function is sum.

void main(){

int total;

total=sum(2);

printf("%d",total);

}

Page 151: Tech tut

int sum(int i){

int even=0;

while(i<=20){

even=even+i;

i=i+2;

}

return even;

}

Page 152: Tech tut

Step 2: Make local variable even as static variable

int sum(int i){

static int even=0;

while(i<=20){

even=even+i;

i=i+2;

}

return even;

}

Page 153: Tech tut

Step 3: Replace while keyword by if keyword.

int sum(int i){

static int even=0;

if(i<=20){

even=even+i;

i=i+2;

}

return even;

}

Page 154: Tech tut

Step 4: Since here variable i has used in condition checking. So replace the statement i=i+2 by sum(i+2).

int sum(int i){

staic int even=0;

if(i<=20){

even=even+i;

sum(i+2);

}

return even;

}

Page 155: Tech tut

Points to note about Recursion are :-

It is very slow process.

One problem with function recursion is it creates a

function frame in each function call. This makes

program very slow. This is main reason to

introduce for, while and do-while loop in c event

that it is also possible by using function recursion.

Page 156: Tech tut

We cannot use break keyword in function

recursion.

Keyword break can be use to stop any loop. Since

function recursion is no a loop .So, we cannot use

break and continue keyword.

Page 157: Tech tut

We can not use goto keyword to switch the

control from one function to another function.

Page 158: Tech tut

Nesting of Function calls :-

If we are calling any function inside another

function call is known as nesting function call.

Sometime it converts a difficult program in easy

one.

For eg :-

Page 159: Tech tut

Find the maximum number among five different integers using nested function call.

Answer:

int max(int x,int y){return x>y?x:y;}

void main(){

int m;

m=max(max(4,max(11,6)),max(10,5));

printf("%d",m);

}

Page 160: Tech tut

How to calculate size of a function in c?

Answer:

Size of any function is calculated as:

Size of function = Size of all local variable which

has declared in function + Size of those global

variables which has used in function+ Size of all

its parameter+ Size of returned value if it is an

address.

Page 161: Tech tut

There are two types of function parameter standard:

1. ANSI standard

In this standard function definition is written as

int calculate(int a, int b){

int c;

c=a+b;

return c;

}

This standerd is also called as modern style.

Page 162: Tech tut

2. Old Standard

int calculate(a, b)

int a,b;

{

int c;

c=a+b;

return c;

}

This standard is also called as old style.You should also known this style if you want to read old c code.

Page 163: Tech tut

4.Pointers — Before and After

There's a lot of nice, tidy code you can write without

knowing about pointers. But once you learn to use the

power of pointers, you can never go back. There are

too many things that can only be done with pointers.

But with increased power comes increased

responsibility. Pointers allow new and more ugly types

of bugs, and pointer bugs can crash in random ways

which makes them more difficult to debug

Nonetheless, even with their problems, pointers are an

irresistibly powerful programming construct.

Page 164: Tech tut

What is a Pointer???

Page 165: Tech tut
Page 166: Tech tut
Page 167: Tech tut
Page 168: Tech tut

Shallow and Deep Copying

Page 169: Tech tut

Bad Pointers

Page 170: Tech tut

Correct LOGIC ?????

Page 171: Tech tut
Page 172: Tech tut

The & operator :- Reference to

Page 173: Tech tut
Page 174: Tech tut
Page 175: Tech tut
Page 176: Tech tut
Page 177: Tech tut
Page 178: Tech tut
Page 179: Tech tut
Page 180: Tech tut
Page 181: Tech tut
Page 182: Tech tut
Page 183: Tech tut
Page 184: Tech tut
Page 185: Tech tut
Page 186: Tech tut
Page 187: Tech tut
Page 188: Tech tut
Page 189: Tech tut
Page 190: Tech tut
Page 191: Tech tut
Page 192: Tech tut

Structures

Page 193: Tech tut
Page 194: Tech tut

Arrays

Page 195: Tech tut
Page 196: Tech tut
Page 197: Tech tut
Page 198: Tech tut
Page 199: Tech tut

Strings

Page 200: Tech tut
Page 201: Tech tut
Page 202: Tech tut
Page 203: Tech tut
Page 204: Tech tut
Page 205: Tech tut
Page 206: Tech tut
Page 207: Tech tut
Page 208: Tech tut
Page 209: Tech tut
Page 210: Tech tut

Last Lecture on Saturday….

We will do some 10-12 theory interview

questions and answers….and it will be over..no

more Subah uthna and no more pain…I hope you

liked my teaching…

Thanks for Attending the Series….

Page 211: Tech tut
Page 212: Tech tut
Page 213: Tech tut
Page 214: Tech tut
Page 215: Tech tut
Page 216: Tech tut
Page 217: Tech tut
Page 218: Tech tut
Page 219: Tech tut
Page 220: Tech tut
Page 221: Tech tut
Page 222: Tech tut
Page 223: Tech tut
Page 224: Tech tut

Why n++ executes faster than n+1 ?

The expression n++ requires a single machine

instruction such as INR to carry out the increment

operation whereas, n+1 requires more instructions

to carry out this operation.

Page 225: Tech tut

What is C language?

The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications.

Page 226: Tech tut

What is the main difference between

STRUCTURE and UNION?

1.]

important difference is in the size allocated to a

structure and an union. for eg:

struct example {

int integer;

float floating_numbers; }

the size allocated here is sizeof(int)+sizeof(float);

Page 227: Tech tut

where as

in an union

union example {

int integer;

float floating_numbers;

}

size allocated is the size of

the highest member. so size is=sizeof(float);

Page 228: Tech tut

2 . if we declare two structure variables asstruct strct1 x y;then the two structure variables x and y have different memory location.But we declared tow unio variables asunion uni1 x y;then the two union variables x and y have same memory location.

Page 229: Tech tut

Gud sites

• www.flazx.com

• www.codeproject.com

• www.academicearth.org

• www.securitytube.net

Page 230: Tech tut

Thank You Very Much for attending the series….

If you wish to contact me :-

Mobile :- 9028199481

Email :- [email protected]

Blog :- www.nanoketya.blogspot.com

Facebook :- Ketan Paithankar

ALL THE BEST FOR YOUR LIFE………