You are on page 1of 124

Time: 36 hours

INDEX

1. Introduction to C Language
2. Basics and Data Types
3. Operators
4. Control Statements
a. Selection/Conditional Statements
b. Loops
c. Jump Statements
5. Arrays
6. Strings
7. Pointers
a. Pointes with Arrays
b. Pointers with Strings
8. Functions
a. Functions with Arrays
b. Functions with Strings
c. Functions with Pointers
9. Storage Classes
10. Structures and Bit Fields
a. Structures with Arrays
b. Structures with Pointers
11. Unions
12. Enums
13. Preprocessing
14. Dynamic Memory Allocation
15. Files

1. Introduction to C Language

1
C Language was developed by Dennis Ritchie in the year 1972 at AT&T bell labs. It is
procedural oriented language.

Sno Year Language Developed by


1 1960 ALGOL International committee
2 1963 CPL Cambridge university
3 1966 BCPL Martin Richards
4 1967 B Ken Thompson
5 1972 C Dennis Ritchie

Languages

High Level Languages Low Level Languages


User understandable Machine Understandable
Ex: Telugu, English…. Ex: Binary

What is the use of Operating System?


It takes the user input in high level language, and coverts into machine understandable
form.

OS cannot convert the language directly to machine understandable form , It takes the
support of translators.

Translator: It is software which converts high level language into low level language and
vice versa.

Types of Translators:-
1. Assembler
2. Compiler
3. Interpreter

Assembler: It converts the assembly language into machine understandable form line by
line.

2
Compiler: A compiler is a software that translates high-level language source code to
machine language code(object code).

Compiler Vs Interpreter
Compiler converts the entire code at a time where as interpreter converts the code line
by line.
Procedure – oriented programming:
Conventional programming using high level languages such as COBOL, FORTRAN and C
are commonly known as procedure-oriented programming language. In the procedure-
oriented approach, the problem is viewed as a sequence of things to be done, such as
reading, calculating and printing. A number of functions are written to accomplish these
tasks.

Applications of C language
 We can develop
 Games
 Drivers
 language translators
 spread sheets,
 data bases and
 part of windows is also designed using c language.

2. Basics and Data Types

Comments: It improves the program readability, It hides the information from the
compiler, It is good practice to use comments in the program.

Two types of comments

i)Single Line Comment


To make a single line as a comment.
//comment

ii)Multi Line Comment


3
To make more than one line as comment.
/* comment */

stdio.h :It stands for standard Input and Output header file.

#include<stdio.h>

Output functions:
printf(); is used to print formatted data on the screen
puts(); is used to print a string on the screen.
putc(); is used to print a single character.

Input functions:
scanf(); is used to read formatted data from std input device
gets(); is used to read a string from std input device
getc(); is used to read a single character.

when we are writing these functions in program we have to include this header file
#include<stdio.h>

header file:it is the collection of pre(already)defined functions.

conio.h: console input output header file


clrscr() : clear screen
it removes previous output
getch() : get character
gets the char from keyboard.

when we are writing these functions in program we have to include conio.h header file
#include<conio.h>

Execution of C program
Execution starts with main function.
void main():
4
main is the special function, program execution always starts from main function.
void main()
{
=====
Entry point ====== executable part
======
} Exit Point
void fun1()
{
======
======
}
We can write main function in different ways.
void main() void main(void) int main()
{ { { retun 0;
} } }

main() //default return type of function is int


{
}
void main(int argc,char *argv[])
{
}
Can we execute the program without using main() function ?
We can compile the code without using main function but we cannot execute the code.

Can we start the program execution with other function?


Yes, Using #pragma startup
we can start the execution of the program with other function.

printf(): It performs two tasks


1. It prints the string
2. It returns the length of the string.

5
//Sample C program to print a welcome message
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr(); // clears the screen
printf("Welcome to C programming\n");
getch(); //reads a character from std input device
}

Data Types
Two types of data
1. Constant
2. Variable

Constant: It cannot be modified


4 types of constants:
1. Integer constant: 12,25,689,1547
2. Floating point constant: 12.365, 26.21, 25.36
3. Character constant: 'c','a','e','3'
4. String constant: "Hello","Hyderabad"

Variable: variable is a temparory name given to a memory location where different


values are stored.

Data Types: The data type of a variable is a keyword used to determine, that what
kind (format) of data it can store.

Type Length Range


unsigned char 1 byte 0 to 255
char 1 bytes -128 to 127
enum 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
short int 2 bytes -32,768 to 32,767
6
int 2 bytes -32,768 to 32,767
unsigned long 4 bytes 0 to 4,294,967,295
long int 4 bytes -2,147,483,648 to 2,147,483,647
float 4 bytes 3.4 * (10^-38) to 3.4 *(10^+38)
double 8 bytes 1.7 *(10^-308)to 1.7 * (10^+308)
long double 10 bytes 3.4 * (10^-4932)to 3.4 * (10^+4932)

Syntax for declaring variables:


datatype var1,var2,....;

ex:
int num1,num2;
float f;
char ch;

Rules to declare variables:


1. case sensitive.
2. variable names should start with an alphabet
3. Variable names can contain numbers
4. White spaces and special symbols(!,@,#,$,^,&) are not allowed except ( _ )
underscore.
5. Variable name should not be a keyword.

Format Specifiers:
They are used to specify the type of data to display or to read.
int %d or %i
long int %ld
float %f
double %lf
long double %Lf
char %c
String %s
Hexadecimal %x
Unsigned Integer %u

7
Escape sequence characters (non-printable characters)
\n - new line
\t - tab space
\r - carriage return
\a - alarm or bell
\b - back space
\" - to print double quotes
\\ - to print back slash

/*program to read a number user and display it */

#include<stdio.h>
#include<conio.h>
void main()
{
int num1;
printf("Enter a number\n");
scanf("%d",&num1);
printf("You entered %d",num1);
getch();
}
/*program to read a floating point number from user and display it on the screen
*/
#include<stdio.h>
#include<conio.h>
void main()
{
float f;
clrscr();
printf("Enter a number\n");
scanf("%f",&f);
printf("You entered %.1f",f);
getch();
}
8
/*program to read a string from user and display it on the screen */
#include<stdio.h>
#include<conio.h>
void main()
{
char name[15];
clrscr();
printf("Enter Name\n");
scanf("%s",&name);
printf("Hello %s",name);
getch();
}

3. Operators
Operators in C:
1.Arithmetic operators
2.Relational operators
3.Logical operators
4.Assignment operators
5.Increment or decrement operators
6.Conditional operators
7.Bitwise Operators

1.arithmetic operators:(+,-,*,/,%)
Arithmetic operators are used to perform arithmetic operations like addition,
subtraction, multiplication, division and remainder.

Ex:- a=10, b=3


a+b = 10+3 =13
a-b = 10 - 3 = 7
a*b = 10 * 3 =30
a/b= 10 / 3 = 3
9
a%b=10%3=1

2.Relational operators: (<,>,<=,>=,==,!=)


Relational operators are used to check the relation between two values. Using relational
operators we write relational expressions, a relational expression returns a Boolean
value either 1 or 0. 1 indicates true, 0 indicates false.

ex:
a>b
a<c
a==b
a!=c
a>=b
a<=c

3. Logical operators: (&&(and), ||(or), !(not))


Logical operators are used to combine two or more relational expressions. C language
contains 3 logical operators.

&& : It is used to combine two or more relational expressions, it returns true when all
conditions are true, other wise it returns false.

Truth Table:
T T T
T F F
F T F
F F F

|| : This operator is used to combine two or more relational expressions, it returns true
when any one of the condition is true, else it returns false.

Truth table:
T T T
T F T
10
F T T
F F F

! (not): This is the negative operator, we can place the not operator before any one of
the condition. It returns the opposite result of the condition. i.e. It converts true to false
and false to true.

Truth table:
T F
F T

3.Assignment operator: C language contains equal to (=) operator to assign a value or


expression into a variable.
Ex: a=10;
a=a+10;

C language has the following short cut assignment operators.


+= a=a+10 a+=10
-= a=a-10 a-=10
*= a=a*10 a*=10
/= a=a/10 a/=10
%= a=a%10 a%=10

5.Increment and decrement operators:


1)++ increment operator
2) -- decrement operator

++: it is used to increment 1 to a variable.


a. pre increment( ++a)
ex:- printf(“%d”,++a);

First the value will be incremented, and then the new value will be printed.
b. post increment(a++)
ex:- printf(“%d”,a++);

11
First the value will be printed and then the value will be incremented.

2)- - : It is used to decrement the value by 1.


a. pre decrement (--a)
b. post decrement (a--)

6. Conditional operators: C language contains conditional operators(? , : ) to return a


value from 2 values based on a condition.
Syntax: (condition) ? value1 : value2;
If the condition is true then value1 will be returned, if the condition is false then value2
will be returned.
Ex:- a=40, b=20
max=a>b ? a : b;
max=40

7. Bitwise Operators
C provides six operators for bit manipulation; these may only be applied to integral
operands, that is, char, short, int, and long, whether signed or unsigned.
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one's complement (unary)

/* program to read 2 numbers from user and calculate the sum and display the sum*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,sum;
clrscr();
printf("Enter 2 numbers\n");
12
scanf("%d%d",&n1,&n2);
sum=n1+n2;
printf("%d + %d : %d\n",n1,n2,sum);
getch();
}

/* program to find the area of circle */


#include<stdio.h>
#include<conio.h>
void main()
{
int radius;
float area;
clrscr();
printf("Enter the radius of circle\n");
scanf("%d",&radius);
area=3.14*r*r;
printf("The area of the circle is %f\n",area);
getch();
}

4. Control Statements
Control structures: Control structures are used to control the flow of the program.

1.Conditional statements.
2.Loops
3.Multibranching statement
4.Unconditional statement

Conditional Statements:
i) if
ii) if
else
iii) if
13
else if
else
iv) Nested if

Syntax:
i)
if(condition)
{
set of statements; block1
}

ii)
if(condition)
{
set of statements; //block 1
}
else
{
set of statements; //block 2
}
if Condition is true block 1 statements will be executed, if condition is false block 2
statements will be executed.

iii)
if(condition1)
{
set of statements; //block 1
}
else if(condition2)
{
set of statements; //block 2
}
else
{
set of statements; //block 3
14
}

if Condition1 is true block 1 statements will be executed, if condition1 is false and


condition2 is true block 2 statements will be executed, if both conditions are false
block3 statements will be executed.

iv)Nested if
if(condition1)
{
if(condition2)
{
set of statements; //block 1
}
else
{
set of statements; //block 2
}
}
else
{
if(condition3)
{
set of statements; //block 3
}
else
{
set of statements; //block 4
}
}

if Condition1 is true and Condition 2 is true then block 1 statements will be executed, if
condition1 is true and condition2 is false block 2 statements will be executed, if
Condition1 is false and Condition 3 is true then block 3 statements will be executed, if
condition1 is false and condition3 is false block 4 statements will be executed.

15
/* program to find whether the given number is Even or Odd */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
if(n%2==0)
{
printf("The number is even\n");
}
else
{
printf("The number is Odd\n");
}
getch();
}

/*program to find the greatest of 2 numbers */


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("Enter 2 numbers\n");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("A is greater\n");
}
else
16
{
printf("B is greater\n");
}
getch();
}

/* program to find whether a given number is positive ,negative or zero*/

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf("Enter a number\n");
scanf("%d",&n);
if(n>0)
{
printf("The number is Positive\n");
}
else if(n<0)
{
printf("The number is Negative\n");
}
else
{
printf("Zero\n");
}
getch();
}

/* program to find the greatest of three numbers using nested if*/


#include<stdio.h>
#include<conio.h>
17
void main()
{
int a,b,c;
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("A is greater\n");
}
else
{
printf("C is greater\n");
}
}
else
{
if(b>c)
{
printf("B is greater\n");
}
else
{
printf("C is greater\n");
}
}
getch();
}

/* program to find the greatest of 3 numbers using conditional operator */


#include<stdio.h>
#include<conio.h>
void main()
{
18
int a,b,c;
clrscr();
printf("Enter three numbers\n");
scanf("%d%d%d",&a,&b,&c);
(a>b)?(a>c)?printf("A is greater"):printf("C is greater"):(b>c)?printf("B is
greater"):printf("C is greater");
getch();
}

/* program to read student num,name,marks and calculate total and average and
print result and division */
#include<stdio.h>
#include<conio.h>
void main()
{
int sno,m1,m2,m3,total,avg;
char sname[15];
clrscr();
printf("Enter Student number\n");
scanf("%d",&sno);
printf("Enter Student name\n");
scanf("%s",&sname);
printf("Enter 3 subjects marks\n");
scanf("%d%d%d",&m1,&m2,&m3);
total=m1+m2+m3;
avg=total/3;
clrscr();
printf("Student Profile\n");
printf("Student No: %d\n",sno);
printf("Student Name: %s\n",sname);
if(m1>=40 && m2>=40 && m3>=40)
{
printf("Result: Pass\n");
19
printf("Total marks : %d\n",total);
if(avg>=75)
printf("Distinction\n");
else if(avg>=60)
printf("First Division\n");
else if(avg>=50)
printf("Second Division\n");
else
printf("Third Division\n");
}
else
{
printf("Result: Fail\n");
printf("Total marks : %d",total);
}
getch();
}

/*program to read eno,ename,basic salary and calculate pf,hra,da,net salary and


gross salary and print eno,ename,basic salary,gross salary and net salary*/

pf= 12% of basic salary.


hra=20% of basic salary.
da= 15% of basic salary.
gross salary=pf+hra+da+basic salary;
net salary=gross salary - pf;

#include<stdio.h>
#include<conio.h>
void main()
{
int basic_salary,gross_salary;
int net_salary,pf,hra,da,eno;
char ename[15];
20
clrscr();
printf("Enter employee no:\n");
scanf("%d",&eno);
printf("Enter employee name:\n");
scanf("%s",&ename);
printf("Enter Basic salary:\n");
scanf("%d",&basic_salary);
pf=0.12*basic_salary;
hra=0.25*basic_salary;
da=015*basic_salary;
gross_salary=basic_salary+pf+hra+da;
net_salary=gross_salary-pf;
clrscr();
printf("Employee profile\n");
printf("Employee No: %d\n",eno);
printf("Employee Name: %s\n",ename);
printf("Basic salary: %d\n",basic_salary);
printf("Gross salary: %d\n",gross_salary);
printf("Net salary: %d\n",net_salary);
getch();
}

Switch:

Switch is used to execute one of the options from number of options. It is also called as multi branching
conditional statement.

Syntax:

switch(expression)

case value1:statements1; break;

case value2:statements2; break;

21
.

default:statements; break;

The expression value may be numeric or character type. The switch statement evaluates the expression. It will
select one of the cases based on the expression. It will execute default statements when no case is selected

break statement:

It is used to exit from a looping statement. We can use this in for, while , do while, and switch statement.

ex:- break;

/*program to read a character from user and check whether it is vowel or not using switch*/

#include<stdio.h>

#include<conio.h>

void main()

char ch;

clrscr();

printf("Enter a character\n");

scanf("%c",&ch);

switch(ch)

22
case 'a':

case 'e':

case 'i':

case 'o':

case 'u': printf("You entered Vowel\n");break;

default: printf("You entered Consonant\n");

getch();

Output:

2)accept a number from the user(0-5) print in words?

#include<stdio.h>

#include<conio.h>

void main()

int n;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

switch(n)

case 1: printf("ONE");break;

case 2: printf("TWO");break;
23
case 3: printf("THREE");break;

case 4: printf("FOUR");break;

case 5: printf("FIVE");break;

default: printf("Number greater than 5");

getch();

Output:

unconditional statement:

goto statement: It is used to transfer the control from one place to another place in the program. It is also
called as unconditional jumping statement

syntax:

goto <label name> ;

example:-

goto print;

// program to read a number and print corresponding month

#include<stdio.h>

#include<conio.h>

void main()

int n;

start:

24
clrscr();

printf("Enter a number between 1 and 12\n");

scanf("%d",&n);

switch(n)

case 1: printf("Jan");break;

case 2: printf("Feb");break;

case 3: printf("Mar");break;

case 4: printf("Apr");break;

case 5: printf("May":);break;

case 6: printf("Jun");break;

case 7: printf("Jul");break;

case 8: printf("Aug");break;

case 9: printf("Sep");break;

case 10: printf("Oct");break;

case 11: printf("Nov");break;

case 12: printf("Dec");break;

default: goto start;

getch();

output

25
Ex:4Which of the following errors would be reported by the compiler on compiling the program given
below?

#include<stdio.h>

int main()

int a = 5;

switch(a)

case 1:printf("First");

case 2:printf("Second");

case 3 + 2:printf("Third");

case 5:printf("Final");break;

return 0;

A. There is no break statement in each case.

B. Expression as in case 3 + 2 is not allowed.

C. Duplicate case case 5:

D. No error will be reported.

Answer: Option C

6.Point out the error, if any in the program.

#include<stdio.h>

int main()

26
int P = 10;

switch(P)

case 10:printf("Case 1");

case 20: printf("Case 2");break;

case P:printf("Case 2");break;

return 0;

A. Error: No default value is specified

B. Error: Constant expression required at line case P:

C. Error: There is no break statement in each case.

D. No error will be reported.

Answer: Option B

7. What is the output of this C code?

#include <stdio.h>

void main()

int i = 5, k;

if (i == 0)

goto label;
27
label: printf("%d", i);

printf("Hey");

a) 5

b) Hey

c) 5 Hey

d) Nothing

output:C

8. What is the output of this C code?

#include <stdio.h>

int main()

printf("%d ", 1);

goto l1;

printf("%d ", 2);

l1:goto l2;

printf("%d ", 3);

l2:printf("%d ", 4);

a) 1 4

b) Compile time error

c) 1 2 4

d) 1 3 4
28
output:a

9. What is the output of this C code?

#include <stdio.h>

int main()

printf("%d ", 1);

l1:l2:

printf("%d ", 2);

printf("%d\n", 3);

a) Compile time error

b) 1 2 3

c) 1 2

d) 1 3

ans :b

10. What is the output of this C code?

#include <stdio.h>

int main()

{
29
printf("%d ", 1);

goto l1;

printf("%d ", 2);

void fun1()

l1: printf("3 ", 3);

a) 1 2 3

b) 1 3

c) 1 3 2

d) Compile time error

ans :d

explanation: goto is a jumping statement from one place to another place with in the funtion.in above
program lable existed in fun1() goto statement existed in main.

11. What is the output of this C code?

#include <stdio.h>

int main()

int i = 0, j = 0;

while (i < 2)

30
l1: i++;

while (j < 3)

printf("loop\n");

goto l1;

a) loop loop

b) Compile time error

c) loop loop loop loop

d) Infinite loop

ans:

LOOPS

Looping statements: when we want to execute a statement or set of statements repeatedly then we use
loops.

while statement:

It is used to execute a statement or set of statements repeatedly as long as the given condition is true.

syntax:

while(condition)

set of statements; //body of while loop

31
First the condition will be tested, if it is true the body of the while loop will be executed first time, again the
control will be transferred back to while loop. If it is false the control will come out of the while loop.

/* program to print numbers from 1 to n(user input) using while loop*/

#include<stdio.h>

#include<conio.h>

void main()

int i=1,n;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

while(i<=n)

printf("%d\t",i);

i++;

getch();

} ouput:

/* program to print even numbers from 1 to n(user input) using while loop*/

#include<stdio.h>

#include<conio.h>

void main()

int i,n;

clrscr();

32
printf("Enter a number\n");

scanf("%d",&n);

i=1;

while(i<=n)

if(i%2==0)

printf("%d\t",i);

i++;

getch();

Output:

/* program to find the sum of numbers from 1 to n(user input) using while loop*/

#include<stdio.h>

#include<conio.h>

void main()

int i,n,sum=0;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);
33
i=1;

while(i<=n)

sum=sum+i;

i++;

printf("The sum of numbers from 1 to %d : %d\n",n,sum);

getch();

Output:

/* accept a number from the user print given number in reverse*/

#include<stdio.h>

#include<conio.h>

void main()

int n,r,rev=0,temp;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

temp=n;

while(n>0)

r=n%10;

n=n/10;
34
rev=rev*10+r;

Printf(“\n reverse number is :%d”,rev);

getch();

Output:

/*accept a number from the user findout given number is polindrum or not?

#include<stdio.h>

#include<conio.h>

void main()

int n,r,rev=0,temp;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

temp=n;

while(n>0)

r=n%10;

n=n/10;

rev=rev*10+r;

Printf(“\n reverse number is :%d”,rev);


35
If(temp==rev)

Printf(“\n given number is polindrum ”);

Else

Printf(“\n given number is not polindrum ”);

getch();

Output:

/* program to check whether the given number is armstrong or not*/

#include<stdio.h>

#include<conio.h>

void main()

int n,r,total=0,n1;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

n1=n;

while(n>0)

r=n%10;

n=n/10;

total=total*(r*r*r);
36
}

if(total=n1)

printf(" %d is an armstrong number\n",n1);

else

printf(" %d is not an armstrong number\n",n1);

getch();

Output:

/* program to generate fibbonacci series(0 1 1 2 3 5 8 13 21 34 55...) upto n(user input)*/

#include<stdio.h>

#include<conio.h>

void main()

int a=0,b=1,fib,n;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

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

fib=a+b;

while(fib<=n)

printf("%d\t",fib);

a=b;

b=fib;

fib=a+b;
37
}

getch();

Output:

Assignment:

1)accept a number from user findout sum of even elements upto that number (1 to n)?

2)accept a number from the user fincout avg of even elements and odd elements (1 to n)?

3)accept a number from the user findout given number is prime or not?

4)accept a number from the user findout given number is perfect number or not?

if

----------------------------------------------------------------

1)Accept age from the user print major when it is >18?

2)Accept marks from the user print fail when marks <35?

if-else

--------------------------------------------------------

3)Accept a number from the user print given number is +ve r not?

4)Accept a Character from the user print female if given char is f


or m?

5)Accept 2 numbers from the user findout smallest no?

6)Accept sal from the user calc hra,and gs?

sal>10000 then hra is 10%

else 20%

7)Accept a character from the user print male if given char 'm' or

38
'M' else female ?

8) Accept a char from the user find out given char ovel or not?

9) Accept a number from the user and check whether the given number
is divided by 3 or 7?

10) Accept 3 subjects marks from the user and find the result? (Note : pass marks are greater than 34 in all
subjects )

if-else-if

--------------------------------------------------------

11) Accept numbers from the user (0 - 5) print in letters

12) Accept age from the user print status of the candidate

(Note: if age < 13 print child

if age < 20 print teenage

if age < 40 print middle age

else print old age )

13) Accept a number from the user and find the number of digits

in the given number

(Note: if the given digit is b/w 0 - 9 print 1 digit

if the given digit is b/w 10 - 99 print 2 digit and

so on.)

14) Accept 3 numbers from the user and find the largest.

nested if

-----------

15) Accept 3 subject marks from the user, calculate total,average

and print result and division.

39
Do-while

do while loop:

This statement executes a set of statements as long as the condition is true.

syntax:

do

set of statements;

}while(condition);

This is similar to while loop, but the difference is this loop will execute the statements at least once.

/* program to read student details using do while loop */

#include<stdio.h>

#include<conio.h>

void main()

int i=1,sno,marks;

char sname[15],ch;

clrscr();

do

printf("\nEnter student number\n");

scanf("%d",&sno);

printf("Enter student name\n");


40
scanf("%s",&sname);

printf("Enter student marks\n");

scanf("%d",&marks);

printf("Student %d Details\n",i++);

printf("Student number: %d\n",sno);

printf("Student name: %s\n",sname);

printf("Student marks: %d\n",marks);

printf("Would you like to continue....\n y/n");

ch=getch();

}while(ch=='y');

getch();

Output:

for loop :

It is used to execute a set of statements repeatedly as long as the given condition is true.

syntax:

for(initialization; condition ; increment / decrement)

set of statements; //body of for loop

When the for loop is executing for the very first time the initial value will be stored in the given variable.
Then the condition will be tested. If it is true, the statements will be executed. After executing the last

41
statement the control will return back to the for loop. Then the value will be incremented / decremented.
Again the condition is tested, if it is false the control will come out of the for loop.

ex:

for(i=1; i<=10; i++)

for( ;i<=10;i++)

for(; i<=10 ; )

for(i=1,j=10;i<=10;i++,j--)

for(i=1;i<=10;i++); //body less for loop

/* program to calculate the power of a given number */

#include<stdio.h>

#include<conio.h>

void main()

int base,exp,i,res=1;

clrscr();

printf("enter base and exponent\n");

scanf("%d%d",&base,&exp);

for(i=1;i<=exp;i++)

res*=base;

getch();

Output:

42
/* program to check whether the number is prime or not */

#include<stdio.h>

#include<conio.h>

void main()

int n,I,nf=0;

clrscr();

printf("Enter a number\n");

scanf("%d",&n);

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

if(n%i==0)

nf++;

If(nf==2)

printf("The number is prime\n");

else

printf("The number is not a prime\n");

getch();

Output:

//program to print armstrong numbers from n1 to n2

#include<stdio.h>

#include<conio.h>

void main()

{
43
int n1,n2,r,t,i;

clrscr();

printf("Enter range(n1,n2)\n");

scanf("%d%d",&n1,&n2);

for(i=n1;i<n2;i++)

t=0;

n1=i;

while(n1>0)

r=n1%10;

n1=n1/10;

t=t+r*r*r;

if(t==i)

printf("%d\n",i);

getch();

} output:

/*program to print numbers from 1 to 5(R to L)

#include<stdio.h>

#include<conio.h>

void main()

int i,j,k;

for(i=1;i<=5;i++)
44
{

for(k=5;k>=i;k--)

printf(" ");

for(j=1;j<=i;j++)

printf("%d",j);

printf("\n");

getch();

/*program to print the output as following

**

***

****

*****

*/

#include<stdio.h>

#include<conio.h>

void main()

int i,j,k;

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

{
45
for(k=5;k>i;k--)

printf(" ");

for(j=1;j<=i;j++)

printf("*");

printf("\n");

getch();

Output:

Arrays
========

Array is a group of values that belongs to similar data type that can share a common name.

Array values can be called by using the index number, index number starts from 0 and ends with the total size-
1. It allocates memory continuously.By default it will have all garbage values.

Arrays are divided into 2 types.

1)Single dimensional arrays. or One dimensional arrays

2) Multi dimensional arrays


46
1) One dimensional arrays:- The array which is using only 1 subscript is known as one dimensional array. In
One dimensional array the elements are represented in single row or single column.

Syntax:- Data_type variable name[size]

ex:- int a[10];

2)Multi dimensional arrays: The array which is using more than one subscripts is known as 2 – dimensional
array

Syntax:- Data_type variable_name[rows][cols]

ex:- int a[2][2];

Initializing single dimensional arrays:

int n[10]={1,2,3,4,5,6,7,8,9,10};

char ch[15]={'a','b','c',....};

char st[15]="hyderabad";

Initializing multi dimensional arrays:

int n[3][3]={{1,2,3},

{4,5,6},

{7,8,9}};

char st[5][4]={"str1","str2","str3","str4","str5"};

int n[10]={1,2,3,4,5}; 0 will be assigned to remaining elements

char st[10]="cmtes"; inserts '\0' after the last character.


47
\0 : null character

Explanation:

1)An array is a derived datatype in c, which is constructed from fundamental datatype of c language.

2)An array is a collection of similar datatype value in a single variable

3)In implimentation when we required n number of variables of same data type then go for array.

4)when we are working with arrays always memory will created in continuous memory location.so randomly
we can access the data.

5)In arrays all elements will share same name with unique identification value called index.

6)always array index will starts with 0 and ends with size-1.

7)when we are working with array compiletime memory management will occur i.e static memory allocation.

syntax:

datatype arrayname[size];

always size of the array must be unsigned integer value which is greater then 0 only.

properties of Arrays

=====================

1)Always size of array must be an unsigned integer values which is gerater then 0

int a[5];

size --5

sizeof(a) ---10 bytes

2)int a[5];

size --5

it creates 5 integer variables, they are

a[0]

a[1]

a[2]

48
a[3]

a[4]

all are garbage values.

3)

int a[]; //error

In array declaration,size of the array must be required, if size is not mentioned then compiler will give
an error.

4) int a[0]; //error

5)int a[-1]; //error

6)int a[5]={10,20,30,40,50};

a[0]=10

a[1]=20

a[2]=30

a[3]=40

a[4]=50

7)int a[5]={10,20};

a[0]=10

a[1]=20

a[2],a[3],a[4]=0

in initialisation of the array if specific number of values are not initialised if then rest of all values will
be initialised with '0';

8)int a[2]={10,20,30}; error

in initialisation process we can't initialise more then array declaration.

9)in initialisation of the array mentioning the size is optional, in this case how many elements are initialise if
that many are variables are created.

10) int a[2]; //valid

49
a[0]=10;

a[1]=20;

a[2]=30;

a[3]=40;

In c and cpp there is no upper boundary checking process will occur ,that is why above syntax is valid.

whenever we are crossing the upper limit depends on security level of os anything can be happens.

11)int a[40000];

on tc 3.0 data segment size 64 kb.

40000 int variables (40000*2 bytes=80000 bytes)

array size is large.

on dos based compiler limit is 65535 bytes only will create.but in above styntax we required 80000 bytes.

12)long int a[20000]; error

long int capacity is 4bytes

20000*4 =80000 bytes

13) char a[40000]; valid

14)float a[12.3]; error

15)float a[12]; valid

size 12

sizeof(a)---48 bytes

16) int size=10;

int a[size]; //error

17)const int size=5;

int a[size]; //error

in declaration of array size must be constant type only. i.e variable or constant variables or not
allowed.

18)#define size 5

50
int a[size]; //valid

In declaration of array we can mention symbolic constant data because at the time of preprocessing
identifier will replace with replacement text.

19)int a[2+3]; valid int a[5];

20)int a[2<5]; valid int a[1];

21)int a[5>8]; error int a[0];

/*program to read 10 numbers and store it in array and display on the screen */

#include<stdio.h>

#include<conio.h>

void main()

int n[10],i;

clrscr();

printf("Enter 10 numbers\n");

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

scanf("%d",&n[i]);

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

printf("%d\t",n[i]);

getch();

Output:

/*program to read 10 numbers and store it in array and calculate the sum of numbers in the array*/

51
#include<stdio.h>

#include<conio.h>

void main()

int n[10],i,sum=0;

clrscr();

printf("Enter 10 numbers\n");

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

scanf("%d",&n[i]);

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

sum+=n[i]; //sum=sum+n[i];

printf("The sum of 10 numbers : %d\n",sum);

getch();

Output:

/*program to read a string and display it on the screen*/

#include<stdio.h>

#include<conio.h>

void main()

char st[10];

clrscr();

printf("Enter your name\n");

scanf("%s",&st);
52
printf("Hello : %s\n",st);

getch();

Output:

/*program to read 10 strings and display them on the screen*/

#include<stdio.h>

#include<conio.h>

void main()

char st[10][10];

int i;

clrscr();

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

printf("Enter name %d\n",i+1);

scanf("%s",&st[i]);

clrscr();

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

printf("\n%s\n",st[i]);

getch();

Output:

53
/* program to find the largest and smallest element in the array*/

#include<stdio.h>

#include<conio.h>

void main()

int n[10];

int large,small,i;

clrscr();

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

printf("Enter number%d\n",i+1);

scanf("%d",&n[i]);

large=small=n[0];

for(i=1;i<10;i++)

if(large<n[i])

large=n[i];

else if(small>n[i])

small=n[i];

printf("The largest number in the array: %d\n",large);

printf("The smallest number in the array: %d\n",small);

}
54
Output:

/*program to add 2 matrices*/

#include<stdio.h>

#include<conio.h>

void main()

int a[3][3],b[3][3],c[3][3];

int i,j;

clrscr();

printf("Enter elements of matrix A\n");

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

for(j=0;j<3;j++)

scanf("%d",&a[i][j]);

}printf("Enter elements of matrix B\n");

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

for(j=0;j<3;j++)

scanf("%d",&b[i][j]);

}
55
}

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

for(j=0;j<3;j++)

c[i][j]=a[i][j]+b[i][j];

printf("Resultant matrix :\n");

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

for(j=0;j<3;j++)

printf("%d\t",c[i][j]);

printf("\n");

getch();

Output:

/* matrix multiplication */

#include<stdio.h>

#include<conio.h>

void main()
56
{

int a[2][2],b[2][2],c[2][2]={0,0,0,0};

int i,j,k;

clrscr();

printf("Enter elements of first matrix\n");

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

for(j=0;j<2;j++)

scanf("%d",&a[i][j]);

printf("Enter elements of second matrix\n");

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

for(j=0;j<2;j++)

scanf("%d",&b[i][j]);

for(k=0;k<2;k++)

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

for(j=0;j<2;j++)
57
{

c[k][i]=c[k][i]+a[k][j]*b[j][i];

printf("Resultant matrix\n");

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

for(j=0;j<2;j++)

printf("%5d ",c[i][j]);

printf("\n");

getch();

/* transpose of a matrix */

#include<stdio.h>

#include<conio.h>

void main()

int a[3][3];

int i,j;

clrscr();
58
printf("Enter elements of the matrix\n");

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

for(j=0;j<3;j++)

scanf("%d",&a[i][j]);

printf("\nTranspose matrix:\n");

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

for(j=0;j<3;j++)

printf("%d",a[j][i]);

printf("\n");

getch();

Output:

100 500

010 050

001 005

/* program to find whether the given matrix is diagonal matrix or not */


59
#include<stdio.h>

#include<conio.h>

void main()

int i,j,a[3][3],de,oe,temp;

de=oe=0;

clrscr();

printf("Enter elements of Matrix A\n");

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

for(j=0;j<3;j++)

scanf("%d",&a[i][j]);

temp=a[0][0];

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

for(j=0;j<3;j++)

if(i==j)

if(a[i][j]==temp)

de++;

else

if(a[i][j]==0)

oe++;

}
60
}

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

for(j=0;j<3;j++)

printf("%d ",a[i][j]);

printf("\n");

if(oe==6 && de==3)

printf("Diagonal matrix\n");

else

printf("not a Diagonal matrix\n");

getch();

/* program to find whether the given matrix is diagonal matrix or not */

#include<stdio.h>

#include<conio.h>

void main()

int i,j,a[3][3],de,oe,temp;

de=oe=0;

clrscr();

printf("Enter elements of Matrix A\n");


61
for(i=0;i<3;i++)

for(j=0;j<3;j++)

scanf("%d",&a[i][j]);

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

for(j=0;j<3;j++)

if(i==j)

if(1==a[i][j])

de++;

else

if(a[i][j]==0)

oe++;

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

for(j=0;j<3;j++)

printf("%d ",a[i][j]);

printf("\n");

if(oe==6 && de==3)


62
printf("Unit matrix\n");

else

printf("not a Unit matrix\n");

getch();

Output:

Strings

1)Character array or collection of characters or group of

characters are called string.

2)In implementation when we required character array operations

then recomended to go for string.

3)within the single quotation any content is called character

constats

4)always character constant returns integer value.


63
5)within the double quoutes any content is called string constants

6)always string constnat returns base address of the string.

7)every string ends with null character '\0'

syntax:

char str[size];

properties

============

1)char a[5];

size=5

sizeof(a)= 5 bytes

2)char a[]; //error

3)char a[0]; //error

4)char a[-1]; //error

5)char a[5]={a,b,c,d,e};//error

6)char a[5]={'a','b','c','d','e'};//valid

7)char a[5]={'a','b','c','d','e','f'};//error

8)char a[5]={'5','t'} ; //valid

in initialisation of the string if specific number of


characters are not initialised if then rest of all characters will
be initialised with NULL.( '\0') character

9)char str[2]={'a','b','c'}
64
In initialization of the string we cant initialized more than size
of string elements.

10) char str[]={'a','b','c'}; valid

in initialisation of the string mentioning the size is


optional,in this case how many elements are initialised it,that
array element will created.

11)char a[5]={65,66,67,68,69};//valid

when we are working with string always recomended to initialised


the string content within the double quotes ("")

12)char a[10]="welcome";//valid

13)char a[7]="welcome"; valid , garbage value

14)char a[5]="hello ram"; //error

15)char str[]="hello";

size -6b

sizeof(str) --6b

16)char a[5]={'a','b','c','d','e'};

17)char a[5]="abcd";

when we are working with character array explicitely null('\0')


character doesnot occupies any physical memory at end of the
character array.

65
when we are working with string data at end of the string
null char will occupies physical memory.

String functions:

1) strlen():- This function is used to return the length of a string.

syntax:- strlen(string);

2) strcpy():- This function copies a string from one string variable to another
string variable.

syntax:- strcpy(target_string , source_string);

strcpy(s2,s1);

3) strcat(): (String concatenation)

This function adds a string at the end of another string

syntax:- strcat(string1,stirng2 );

4) strcmp(): (String comparison)

This compares one string with another string, if two strings are equal this
function returns 0, else it returns the numeric difference between the non-
matching characters.

Syntax:- strcmp(string1, string2);

66
5) stricmp(): This function is similar to strcmp, but this function ignores the case
sensitivity.

syntax:- stricmp(string1, string2);

6) strrev(): This function reverses the given string

Syntax:- strrev(string);

7) strupr(): This function converts the given string into upper case(capitals)

syntax:- strupr(string)

8) strlwr(): This function converts the given string into lower case.

syntax:- strlwr(string);

/* program to print ascii characters and their equivalent numbers */

#include<stdio.h>

#include<conio.h>

void main()

int i;

clrscr();

for(i=1;i<255;i++)

{
67
printf("%c => %d\n",i,i);

if(i%40==0)

getch();

getch();

/* program to find the length of a string using standard library functions */

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char st[20];

int len;

clrscr();

printf("Enter a string\n");

scanf("%s",&st);

len=strlen(st);

printf("The length of %s : %d\n",st,len);

getch();

68
}

// string copy

#include<stdio.h>

#include<conio.h>

void main()

char st[10],st1[10];

int i;

printf("Enter a string\n");

gets(st);

for(i=0;st[i]!='\0';i++)

st1[i]=st[i];

st1[i]='\0';

printf("st : %s\n st1: %s",st,st1);

getch();

69
/* program to reverse the contents of a string using string

function */

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char st[15];

clrscr();

printf("Enter a string\n");

scanf("%s",&st);

strrev(st);

printf("Reversed string : %s\n",st);

getch();

/* program to reverse the contents of a string without using string

function */

#include<stdio.h>
70
#include<conio.h>

#include<string.h>

void main()

int len,i;

char st[15],temp;

clrscr();

printf("Enter a string\n");

scanf("%s",&st);

for(len=0;st[len]!='\0';len++); // length of string

for(i=0;i<len/2;i++)

temp=st[i];

st[i]=st[len-1-i];

st[len-1-i]=temp;

printf("Reversed string : %s\n",st);

getch();

71
/* program to convert a string to uppercase and lowercase without

using string functions */

#include<stdio.h>

#include<conio.h>

void main()

int len,i;

char s1[15],s2[15],temp;

clrscr();

printf("Enter a string\n");

scanf("%s",&s1);

printf("Enter a string\n");

scanf("%s",&s2);

for(i=0;s1[i]!='\0';i++)

if(s1[i]>=97 && s1[i]<=122)

s1[i]=s1[i]-32;

printf("Uppercase : %s\n",s1);

for(i=0;s2[i]!='\0';i++)

{
72
if(s2[i]>=65 && s2[i]<=90)

s2[i]=s2[i]+32;

printf("Lowercase : %s\n",s2);

getch();

/*program to compare 2 strings using standard library functions*/

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char st1[15],st2[15];

clrscr();

printf("Enter 2 strings\n");

scanf("%s%s",&st1,&st2);

if(strcmp(st1,st2)==0)

printf("Two strings are equal\n");

else

printf ("Strings are not equal\n");

73
getch();

/*program to compare 2 strings without using standard library functions*/

#include<stdio.h>

#include<conio.h>

void main()

char st1[15],st2[15];

int l1,l2,i;

clrscr();

printf("Enter 2 strings\n");

scanf("%s%s",&st1,&st2);

for(l1=0;st1[l1]!='\0';l1++);

for(l2=0;st2[l2]!='\0';l2++);

if(l1==l2)

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

if(st1[i]!=st2[i])

break;

74
}

if(i==l1)

printf("Strings are equal\n");

else

printf("Strings are not equal\n");

getch();

/*program to concatenate 2 strings using standard library functions*/

#include<stdio.h>

#include<conio.h>

void main()

char st1[25],st2[15];

clrscr();

printf("Enter 2 strings\n");

scanf("%s%s",&st1,&st2);

strcat(st1,st2)

printf("st1: %s\n",st1);

printf ("st2: %s\n",st2);

75
getch();

/*program to concatenate 2 strings without using standard library functions*/

#include<stdio.h>

#include<conio.h>

void main()

char st1[25],st2[15];

int l1,l2,i;

clrscr();

printf("Enter 2 strings\n");

scanf("%s%s",&st1,&st2);

for(l1=0;st1[l1]!='\0';l1++);

for(l2=0;st2[l2]!='\0';l2++);

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

st1[l1+i]=st2[i];

printf("st1: %s\n",st1);

printf ("st2: %s\n",st2);

76
getch();

/* program to print numbers from 1 to 255 and their equivalent ascii characters
*/

#include<stdio.h>

#include<conio.h>

void main()

int i;

clrscr();

for(i=1;i<255;i++)

printf("%c ==> %d\n",i,i);

if(i%40==0)

getch();

getch();

\ /*program to search a string in main string */

#include<stdio.h>
77
#include<conio.h>

void main()

int i,j,found=0,len;

char st1[30],st2[10];

clrscr();

printf("Enter main string\n");

gets(st1);

printf("Enter search string\n");

gets(st2);

for(len=0;st2[len]!='\0';len++);

for(i=0;st1[i]!='\0';i++)

if(st1[i]==st2[0])

for(j=0;j<len;j++)

if(st1[i+j]!=st2[j])

break;

if(j==len)

78
{

found=1;

printf("string found at index : %d",i);

if(found==0)

printf("string not found\n");

getch();

4)

void main()

char str[5]="Welcome";

printf("%s",str);

getch();

output:error

too many initilizations

79
5)

void main()

char str[]="Welcome";

printf("\n %s",str);

printf("\n %s",str+3);

printf("\n %s",str+5);

getch();

output:

6)

void main()

char str[]="abcdxyz";

80
printf("\n %s",str);

printf("\n %s",str+3);

str[3]=0;

printf("\n %s",str);

str[3]='0';

str[4]=100;

printf("\n %s",str);

str[4]='\0';

printf("\n %s",str);

getch();

output:

7)

81
void main()

char str[10]="Welcome";

int i;

clrscr();

for(i=0;str[i]!='\0';i++)

puts(str+i);

getch();

output:

welcome

elcome

lcome

come

ome

82
me

8)

void abc(char *ptr)

puts(ptr);

if(*ptr);

abc(ptr+1);

void main()

char str[]="Hello";

clrscr();

abc(str);

getch();

83
output:

9)

void main()

char str="welcome";

clrscr();

l=strlen(str);

printf("\n %d",l); //7

printf("\n %d",sizeof(str)); //8

l=strlen(str+3);

printf("\n %d",l); //4

l=strlen(str+5);

84
printf("\n %d",l); //2

getch();

10)

void main()

char str="welcome";

clrscr();

strrev(str);

strrev(str+3);

strrev(str+5);

strrev(str+7);

getch();

85
11)

void main()

char s1[15]="Welcome";

char s2[10]="Hello";

clrscr();

puts(s1);

puts(s2);

strcat(s1," ");

strcat(s1,s2);

getch();

1)strcat(s1,s2+2)

86
2)strcat(s1+3,s2)

3)strcat(s1+3,s2+2)

note:

when we are working with strcat always appending will take place at the end of
the destination string.

void main()

char a[20]="welcome";

clrscr();

strupr(str);

strupr(str+3);

strupr(str+5);

getch();
87
}

examples

printf(2+"welcome"); lcome

printf("welcome"+3); come

printf(2+"welcome"+3);

Pointers

A pointer is a variable, which holds the address of the another


variable.

Advantages:

=========

By using pointers we can handle any kind of data structures


properly.

88
Dynamic memory allocation is possible using pointers only.

pointers can be increase the execution speed of the program.

function can return only one value at a time, using pointers we can

return more then one value from functions.

syntax:

datatype *ptrname;

& address of operator

* indirection or dereferencee or object at location or


value at address.

Address of operator always returns base address of the variable.

starting cell address of a variable is called base address.

int a=5;

int *ptr;

ptr=&a;

a is variable of type an integer ,

it is a value type which holds an integer value.

ptr is a variable of type an int *,

it is address type variable which holds an integer variable


address .

In implementation when we are printing the address then

89
recommended to go for %x ,%p,%lp will print the address in hexa
decimal format

and %u %lu will print in decimal format.

for printing the address of the variable doesnot require to use %d


format specifier because

1.address available in hexa decimal format from the range of 0X0000


to 0XFFFF (0-65535) so this range is not supported by %d

2.There is no any negativve data is available in hexa decimal


format but %d will print negative data also.

when we are working with pointers we will get following messages

i.e

1.suspecious pointers conversion

this warning msg will occuur when we are assigning address


of a variable into different type of pointer.

suspecious pointer conversions will be not allowed in c++;

void main()

Int x;

char *p;

p=&x; //warning

getch();

2.Non portable pointer conversion


90
this warning msg will occur when we are assigning value type data
to a pointer.

void main()

int a;

int *ptr;

a=10;

ptr=a;

It is a concept of placing a pointer address into another pointer


variable

pointer to pointer relations can be applied upto 12 stages

when we are increasing the pointer to pointer to pointer relations


then performance will decrease.

syntax:

pointer :datatype *ptr;

p2p :datatype **ptr;

p2p2p :datatype ***ptr;

p2p2p2p : datatype ****ptr;

void main()

91
{

int i;

int *ptr;

int **pptr;

int ***ppptr;

ptr=&i;

pptr=&ptr;

ppptr=&pptr;

i=10;

Arithmetic operations on pointers:

int i1,i2;

int *p1,*p2;

p1=&i1;

p2=&i2;

p1+p2;

p1*p2;

p1/p2;

p1%p2; Illegal Operations

p1*2;

92
p1/5;

p1%2;

p1+1 ==== next address

++p1 next address

p1++ nextaddress

p2-p1 no of elements

p2-1 pre adress

p2-- previous address

--p2 pre address

Pointer Properties

================

Pointer arithmetic

Rule 1:

======

address+number=address(next address)

address -number=address(pre address)

address++ =address (pre address)

++address=address(next address)

--address=address(pre address)

Rule 2:

93
=====

address-address=number(no of elements)

size diff/size of(datatype)

int *p1=(int *)100;

int *p2=(int *)200;

p2-p2=50;

200-100=100/sizeof(int); =100/2=50

note :

difference between two same pointers is 1.

int *p1,*p2;

p2-p1 value is 1.

Rule 3

=====

address+address=illegal

address*address=illegal

address/address=illegal

address %address=illegal

Rule 4

======

we can use relational operator and conditional operator between


two pointers.

(>,<,>=,<=,==,!=)
94
address>address=t/f

address>=address=t/f

Rule 5:

====

we cant perform bitwise operator between two pointers like

address & address =illegal

address | address=illegal

address ^ address=illegal

~address=illegal

Rule 6:

======

we can find size of a pointer using sizeof operator

wild pointer or bad pointer

=====================

Uninitialised pointer variable or which pointer is not initialised


with any variable address is called as wild pointer.

void main()

int a;

int *ptr; //wild pointer or bad pointer

95
when we are working with pointers always recommended to initialised with any
variable address or make it null.

Null pointer:

==========

which pointer variable initialised with null ,it is called null pointer.

By default null pointer willbe not points to any memory location


untill we are not assigning any address.

syntax:

=====

datatype *ptr=null;

int *ptr=null;

float *ptr=null;

without null create pointer

=====================

syntax

=====

datatype *ptr=(datatype *)0;

int *ptr=(int *)0;

char *ptr=(char *)0; type casting

float *ptr=(float *)0;

datatype *ptr=null; <stdio.h>


96
void pointer

=========

Generic pointer of c and c++ is called void pointer, generic


pointer means it can access and manipulate any kind of data
properly.

the size of void pointer is 2 bytes

when we are working with void pointer type specification will be


decided at time of execution only.

By using void pointer if we required to acces the data then must be


required to use type costing process or else it gives an error.

when we are working with void pointers arithmetci operations are

not allowed i.e incrementation and decrementation of void pointer


is restricted.

void main()

int i;

int *ptr=(int *)0;

float f;

float *fptr=(float *)0;

char ch;

97
char *cptr=(char *)0;

iptr=&i;

i=11;

printf("\n %d %d %d",i,*iptr);

fptr=&fp;

f=12.12;

printf("\n %d %d %d",f,*ptr);

cptr=&ch;

ch='A';

printf("\n %c %c",ch,*ptr);

getch();

In previous program in place of creating 3 different types

of pointers we can create single pointer variable which can manage


3 different types of variables, i.e void pointer is requierd.

void main()

int i;

char ch;
98
float f;

void *ptr=(void *)0;

ptr=&i;

i=11;

printf("\n %d %d",i,*(int *)ptr);

ptr=&ch;

ch='A';

printf("\n %c %c",ch,*(char *)ptr);

ptr=&f;

f=3.4;

printf("\n %f %f",f,*(float*)ptr);

getch();

Interview Questions(Home work & practice work)

1. What is the output of this C code?

99
#include <stdio.h>

int main()

int i = 10, j = 2;

printf("%d\n", printf("%d %d", i, j));

a) Compile time error

b) 10 2 4

c) 10 2 2

d) 10 2 6

Answer:b

2. What is the output of this C code?

#include <stdio.h>

int main()

int i = 10, j = 3;

printf("%d %d %d", i, j);

a) Compile time error

b) 10 3

c) 10 3 some garbage value

100
d) Undefined behaviour

Answer:c

3. What is the output of this C code?

#include <stdio.h>

int main()

int i = 10, j = 3, k = 3;

printf("%d %d ", i, j, k);

a) Compile time error

b) 10 3 3

c) 10 3

d) 10 3 somegarbage value

Answer:c

4. What is the output of this C code?

#include <stdio.h>

int main()

char *s = "myworld";

int i = 9;

printf("%*s", i, s);

101
}

a) myworld

b) myworld(note: spaces to the left of myworld)

c) myworld (note:followed by two spaces after myworld)

d) Undefined

Answer:b

5. What is the output of this C code?

#include <stdio.h>

int main(int argc, char** argv)

char *s = "myworld";

int i = 3;

printf("%10.%s", i, s);

a) myw

b) myworld(note:2 spaces before myworld)

c) myworld (note:2 spaces after myworld)

d) myw(note:6 spaces after myworld)

Answer:d

6. What is the difference between %e and %g?

a) %e output formatting depends on the argument and %g always formats in the


format [-]m.dddddd or [-]m.dddddE[+|-]xx where no.of ds are optional.
102
b) %e always formats in the format [-]m.dddddd or [-]m.dddddE[+|-]xx where
no.of ds are optional and output formatting depends on the argument.

c) No differences

d) Depends on the standard

7. Escape sequences are prefixed with.

a) %

b) /

c) ”

d) None of the mentioned

Answer:d

8. What is the purpose of sprintf?

a) It prints the data into stdout

b) It writes the formatted data into a string

c) It writes the formatted data into a file

d) Both a and c

Answer:b

9. The syntax to print a % using printf statement can be done by.

a) %

b) %

c) ‘%’

d) %%

Answer:d
103
10.What is the output of this C code?

#include <stdio.h>

void main()

double k = 0;

for (k = 0.0; k < 3.0; k++);

printf("%lf", k);

a) 2.000000

b) 4.000000

c) 3.000000

d) Run time error

ans :c

11. What is the output of this C code?

#include <stdio.h>

void main()

char *str = "";

do

printf("hello");

104
} while (str);

a) Nothing

b) Run time error

c) Varies

d) Hello is printed infinite times

Answer:d

2. What is the output of this C code?

#include <stdio.h>

void main()

int i = 0;

while (i < 10)

i++;

printf("hi\n");

while (i < 8)

i++;

105
printf("hello\n");

a) Hi is printed 8 times, hello 7 times and then hi 2 times

b) Hi is printed 10 times, hello 1 times

c) Hi is printed once, hello 7 times

d) Hi is printed once, hello 7 times and then hi 2 times

Answer:

13. Example of iteration in C.

a) for

b) while

c) do-while

d) All of the mentioned

Answer:d

14. Number of times while loop condition is tested is, i is initialized to 0 in both
case.

while (i < n)

i++;

-------------

do

i++;

}
106
while (i <= n);

a) n, n

b) n, n+1

c) n+1, n

d) n+1, n+1

Answer:d

15. What is the output of this C code?

#include <stdio.h>

int main()

int i = 0;

while (i = 0)

printf("True\n");

printf("False\n");

a) True (infinite time)

b) True (1 time) False

c) False

d) Compiler dependent

107
Answer:c

16. What is the output of this C code?

#include <stdio.h>

int main()

int i = 0, j = 0;

while (i < 5 , j < 10)

i++;

j++;

printf("%d, %d\n", i, j);

a) 5, 5

b) 5, 10

c) 10, 10

d) Syntax error

Answer:c

17. Which loop is most suitable to first perform the operation and then test the
condition?

a) for loop
108
b) while loop

c) do-while loop

d) None of the mentioned

Answer:c

18. What is the output of this C code?

#include <stdio.h>

void main()

int k;

for (k = -3; k < -5; k++)

printf("Hello");

a) Hello

b) Infinite hello

c) Run time error

d) Nothing

ans :d

19. What is the output of this C code?

#include <stdio.h>

int main()

109
int i = 0;

for (; ; ;)

printf("In for loop\n");

printf("After loop\n");

a) Compile time error

b) Infinite loop

c) After loop

d) Undefined behaviour

ans:c

20. What is the output of this C code?

#include <stdio.h>

int main()

int i = 0;

for (i++; i == 1; i = 2)

printf("In for loop ");

printf("After loop\n");

a) In for loop after loop

110
b) After loop

c) Compile time error

d) Undefined behaviour

ans:a

21. What is the output of this C code?

#include <stdio.h>

int main()

int i = 0;

for (foo(); i == 1; i = 2)

printf("In for loop\n");

printf("After loop\n");

int foo()

return 1;

a) After loop

b) In for loop after loop

c) Compile time error

d) Infinite loop

111
ans: a

22. What is the output of this C code?

#include <stdio.h>

int main()

int *p = NULL;

for (foo(); p; p = 0)

printf("In for loop\n");

printf("After loop\n");

a) In for loop after loop

b) Compile time error

c) Infinite loop

d) Depends on the value of NULL

ans:b

23. What is the output of this C code?

#include <stdio.h>

int main()

for (int i = 0;i < 1; i++)

printf("In for loop\n");

112
}

a) Compile time error

b) In for loop

c) Depends on the standard compiler implements

d) Depends on the compiler

ans : c

24)what will be the output

#include <stdio.h>

int main()

int a = 10, b = 5, c = 5;

int d;

d = b + c == a;

printf("%d", d);

output:1

25)

#include <stdio.h>

int main()

int a = 10, b = 5, c = 3;

113
b != !a;

c = !!a;

printf("%d\t%d", b, c);

output: 5 1

26)#include <stdio.h>

int main()

int a = 10;

if (a == a--)

printf("TRUE 1\t");

a = 10;

if (a == --a)

printf("TRUE 2\t");

output:

TRUE 1 TRUE 2

27)#include

int main()

int i = 0, j = 0;

114
if (i && (j = i + 10))

printf("\n %d",j);

Output:0

28)

#include

int main()

int i = 1;

if (i++ && (i == 1))

printf("Yes\n");

else

printf("No\n");

115
}

29)what will be the output?

#include<stdio.h>

int main()

printf("%d\n", -1<<1);

return 0;

output:

-2

30)#include<stdio.h>

int main()

unsigned int m = 32;

m=m-64;

printf("%d",m); //-32

printf("%u",m); //65502

return 0;

output :

-32 65502

116
31)

#include<stdio.h>

int main()

unsigned int m = 5;

printf("%d",~i);

return 0;

32. Which of the following statements are correct about the below C-program?

#include<stdio.h>

int main()

int x = 10, y = 100%90, i;

for(i=1; i<10; i++)

if(x != y);

printf("x = %d y = %d\n", x, y);

return 0;

117
}

1: The printf() function is called 10 times.

2: The program will produce the output x = 10 y = 10

3: The ; after the if(x!=y) will NOT produce an error.

4: The program will not produce output.

A. 1

B. 2, 3

C. 3, 4

D. 4

Answer: Option B

33.What will be the output of the program?

#include<stdio.h>

int main()

int k, num=30;

k = (num>5 ? (num <=10 ? 100 : 200): 500);

printf("%d\n", num);

return 0;

A. 200

118
B. 30

C. 100

D. 500

Answer: Option B

34. The keyword used to transfer control from a function back to the calling
function is

A. switch

B. goto

C. go back

D. return

Answer: Option D

35.Which of the following statements are correct about the function?

long fun(int num)

int i;

long f=1;

for(i=1; i<=num; i++)

f = f * i;

return f;

A. The function calculates the value of 1 raised to power num.

B. The function calculates the square root of an integer


119
C. The function calculates the factorial value of an integer

D. None of above

Answer: Option C

36.Which of the statements is correct about the program?

#include<stdio.h>

int main()

float a=3.14;

char *j;

j = (char*)&a;

printf("%d\n", *j);

return 0;

A. It prints ASCII value of the binary number present in the first byte of a float
variable a.

B. It prints character equivalent of the binary number present in the first byte
of a float variable a.

C. It will print 3

D. It will print a garbage value

Answer: Option A

37.Will the program compile in Turbo C?

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

int a=10, *j;

void *k;

j=k=&a;

j++;

k++;

printf("%u %u\n", j, k);

return 0;

A. Yes

B. No

Answer: Option B

38. Which of the following statements are correct about an array?

1: The array int num[26]; can store 26 elements.

2: The expression num[1] designates the very first element in the array.

3: It is necessary to initialize the array at the time of declaration.

4: The declaration num[SIZE] is allowed if SIZE is a macro.

A. 1

121
B. 1,4

C. 2,3

D. 2,4

Answer: Option B

39.The library function used to find the last occurrence of a character in a string
is

A. strnstr()

B. laststr()

C. strrchr()

D. strstr()

Answer: Option C

40.what will be the output of the program?

#include <string.h>

#include <stdio.h>

int main(void)

char text[] = "I love my india";

char *ptr, c = 'i';

ptr = strrchr(text, c);

if (ptr)
122
printf("The position of '%c' is: %d\n", c, ptr-text);

else

printf("The character was not found\n");

return 0;

41.If char=1, int=4, and float=4 bytes size, What will be the output of the
program ?

#include<stdio.h>

int main()

char ch = 'A';

printf("%d, %d, %d", sizeof(ch), sizeof('A'), sizeof(3.14f));

return 0;

A. 1, 2, 4

B. 1, 4, 4

C. 2, 2, 4

D. 2, 4, 8

Answer: Option B

42.What will be the output of the program ?

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

char str[] = "Nagpur";

str[0]='K';

printf("%s, ", str);

str = "Kanpur";

printf("%s", str+1);

return 0;

A. Kagpur, Kanpur

B. Nagpur, Kanpur

C. Kagpur, anpur

D. Error

Answer: Option D

124

You might also like