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

Jayanth C Language

The document discusses C language and its features. It defines C as a middle-level language developed in 1972 by Dennis Ritchie at Bell Labs. Some key features of C include its ability to be compiled faster than high-level languages, support for various data types and functions, and use in both system and application software like Unix. The document also covers basic concepts like variables, constants, data types in C and how programs are compiled in C.

Uploaded by

Sumanth 7899
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
269 views

Jayanth C Language

The document discusses C language and its features. It defines C as a middle-level language developed in 1972 by Dennis Ritchie at Bell Labs. Some key features of C include its ability to be compiled faster than high-level languages, support for various data types and functions, and use in both system and application software like Unix. The document also covers basic concepts like variables, constants, data types in C and how programs are compiled in C.

Uploaded by

Sumanth 7899
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 233

C Language

Language

The media of communication between the user and the system is known as Language. It
is classified into three types. They are.

a) Machine language: This language is also known as binary language or first


generation language or low level language. It consists of binary digits or bits
(0-pulse off,1-pulse on).

b) Assembly language: It is also known as middle level language or second


generation language. Its process is faster than high level language and easy to
understand when compared to machine language.
Ex: c, c++

c) High level language: This is the user language. It consists of codes which is
very easy to understand as the code is similar to English language.
Ex: BASIC, COBOL, FORTRAN, JAVA, C#

Operating system: It is an interface between user and the computer. It is used to


perform the required operations in the system. It is classified into two types. They are

1) single user operating system: it supports only one user at a time. These are
micro computers
Ex: DOS
2) Multi user operating system: it supports more than one user at a time. These
are mini, main-frame and super computers.
Ex: Windows NT, UNIX, XENIX etc.,

Booting: The process of loading an operating system into the computer internal memory
is known as Booting. It is classified into two types. They are

1) Cold booting: when the power is switched on then the process of loading
operating system into the computer memory is known as cold booting

2) warm booting: when there is a problem with the computer then the process of
rebooting is known as warm booting. Warm booting is done using warm keys
or control keys (alt+del+ctrl) or Reset button in CPU.

History of c-language:
COBOL :COmmon Business Oriented Language : Business
BASIC : Beginners All purpose Symbolic Instruction Code : Beginners
FORTRAN: FORmula TRANslation : Scientific and Engineering purpose
Dbase : Data base -do-
ALGOL : AlGOrithmic Language : Some requirements.
CPL : Combined Programming Language : More requirement, difficult.

1
C Language

BCPL : Basic Combined Programming Language: More requirement, easy


B : New concepts (different from BCPL).
C : BCPL + B + some more features( data types)

Advantages or features of c-language

1) C-language is designed in assembly language because its compilation will be faster


and also easy to understand
2) C-language is used for scientific purpose, engineering purpose, business purpose and
general purpose.
3) C-language is used to design and application software and system software.
Ex: Unix
4) C-language supports the storage classes such as static, external, register and
automatic
5) In C-language a large program is divided into number of functions so that the size of
the program can be reduced as well as program becomes simple.
6) C-language is very easy to understand and use.
7) C-language supports pre-defined functions, user-defined functions and recursive
functions.
8) It is flexible. The same program can be designed in required format with different
logics.
9) Data structures can be build in c-language.
10) Memory can be allocated at run-time using Dynamic Memory Locations.
11) The user can create Derived data types and User-defined data type using the Primary
data types.
12) The arguments can be passed from the command prompt using command line
arguments and can perform required operations.

C-language: It is a middle level language and is known as structured programming


language or function oriented programming language. It is designed and developed by
Dennis Ritchie at AT & T (American Telegraph and Telephone) bell laboratory in USA
in the year 1972. It could satisfy all the user requirements.

Hardware: The set of physical components of the computer is known as hardware

Software : The set of programs (language, package, operating system, files, folders etc)
is known as software.

Firmware: The set of standard routine tasks is known as Firmware

Lineware: The Computer Personnel is known as Lineware

Program: The set of instruction is known as program

Instruction: The set of commands to perform a particular task is known as instruction.

2
C Language

A=5 instruction
B=6 program
C=A+B
DISPLAY C

Source code: The code, which is written by the user is known as source code

Object code : The system understandable code is called object code. The source code is
converted into ASCII code or EBCDIC code for the system identification based on the
operating system.

ASCII : American Standard Coded for Information Interchange. It uses 8 bits to


represent a character. It belongs to Microsoft
user ASCII
Ex: A=65, a=97, 0 =48 ,

BCD: Binary coded decimal. It uses 6 bits to represent a character


(IBM=International Business Machine)

EBCDIC: Extended Binary Coded Decimal Interchange Code. It uses 8 bits to


represent a character.

Compiler and interpreter: These are used to convert source code into object code.
Compiler converts the entire program at a time where as interpreter converts the
program in line wise.

0,1 = 1bit
8 bits = 1 byte
1024 bytes = 1 KB ( Kilo Byte)
1024 KB = 1MB (Mega Byte)
1024 MB = 1GB (Giga Bytes)
1024 GB = 1TB (Tera Byte)

Variable: The value, which changes during the execution of a program, is known as
variable. It is used to store the contents in a memory cell.
a

65536 6

a : variable
65536 : address of cell
6 : value in the cell

3
C Language

Rules for writing a variable name

1) Every variable name should be started with an alphabet.


2) The length of the variable should not exceed more than 8 characters. Some
compilers may support upto 40 characters.
3) Spaces should not be provided in a variable name.
4) Reserved words should not be used as a variable name.
5) Except underscore, other symbols should not be used as a variable name.
6) A variable can store the value of particular data type only.
Ex: s_no, s1, snumber, a

Constants: The value, which does not change during the execution of the program is
known as constant.

Numericals: the numbers should not contain quotations. These values could be
used for calculations.
Ex: 56, 77.788
Characters: The single character should be enclosed within single quotation. A
character may be numbers, special symbols, space, alphabets
Ex: ‘7’, ‘A’, ‘u’, ‘$’,’ ‘

Strings: the set of characters is known as a string and should be enclosed within
double quotation.
Ex: “ravi”, “123”, ”it is c-language”

Datatypes
it is used to define the type of the data used for a variable so that the contents can be
stored in a variable based on the data type.

1) Primary data types: it is also known as fundamental data types or basic data types.
These data types are generally of 4 types.

a) integer: it is used to accept numeric values, which are used for calculations.It
occupies 2 bytes and it is represented with "int". It is again classified into 3 types.They
are int, short int, long int.

b) Float: it is used to accept numeric values as well as decimal values. it occupies


4 bytes.it is classified into 3 types. Thay are float, double, long double.

c) Character: It is used to accept a single character into a variable. It occupies 1


byte. It is represented with "char".
The collection of characters is referred as string and it is defined
with arrays
ex: char s[4]="ravi"

4
C Language

d) Void: it occupies 0 bytes and it will not return any value.

Type formatted Length Range


string
char %c 1 byte -128 to 127
unsigned char %c 1 byte 0 to 255
enum -- 2 bytes -32,768 to 32,767
short int %hd 1 bytes -128 to +127
int %d 2 bytes -32,768 to +32,767
long int %ld 4 bytes -2,147,483,648 to 2,147,483,647
unsigned short int %hu 2 bytes 0 to 255
unsigned int %u 2 bytes 0 to 65,535
unsigned long int %lu 4 bytes 0 to 4,294,967,295
float %f 4 bytes 3.4 * e-38 to 3.4 * e+38
double %lf 8 bytes 1.7 * e- 308 to 1.7 *e+308
long double %Lf 10 bytes 3.4*e-4932 to 1.1*e+4932

2) User-defined data types: By using the all the primary data types, user-defined data
types will be created, i.e., using more than one primary data types a new data type is
created.
ex: struct, class, enum (enumerated data types)
struct student
{
int sno, c, cpp, java;
char sname[500; float avg, total;
}stud;

3) Derived data types: By using a single primary data type a new data type is created, it
is known as Derived data types.
ex: arrays, functions, pointers

clrscr(): This statement is used to clear the screen at run-time.

Rules for writing C Program

1) The header files should be declared at the starting of the program in each line.
ex: # include "stdio.h" (input and output streams)
#include <stdio.h>

If header file is included within quotations then the file will be searched or path
of the file can be specified which may be located in any directory but if the header file is
included within <> then the file will be searched only in the include directory.

5
C Language

2) Every program should contain "main" statement with return-type void. By default it
takes "int" as the return-type. It is the main function where the compiler starts executing
the program.
3) The block of statements should be enclosed within '{' and '}'
4) Every statement should be terminated with semicolon (;)
5) The variable should be declared at the starting of the statement.
6) C is a case sensitive so the program should be written in lower case letters except some
keywords, class name etc.,

Shortcuts

f2- save the program file


alt + f9 : Compile the program
ctrl+f9: Run the program
alt +f5 : To display the result
alt + f : File menu
alt + red character in menu bar : to display the options of the corresponding menu.
alt + x : Exit for c++ editor (turbo editor)

Formatted input and output statement

1) scanf(): it is used to accept the contents into the variable until it founds enter
(return) key or space symbol.

Syntax: scanf(“formatted string”,&var1,&var2….);


Example: scanf(“%d”,&a);
scanf(“%d%d%d”,&a,&b,&c);
scanf(“%c”,&ch);

2) printf(): it is used to display the string or to display the contents in the output
screen
Syntax: printf(“string /formatted string”,var1,var2..);
Example: printf(“it is c-language”);
printf(“the value is: %d”,a);

6
C Language

Escape characters
\n - new line
\t - tab space
\a - alert ( bell)
\f - form feed
\b - backspace
\\ - slash symbol
\’ - single quote symbol
\” - double quotation
\r - carriage return
‘\0’ - NULL character

Operators

c-language is rich in operators because it support many number of operators. If true it


returns is 1 otherwise value is 0 for any operator.

ex: c=a+b+10
=, +  operator c,a,b,10 operands (variables, constants)

1) Assignment operator: it is used to assign or store a value into the variable.


The operator is =

Syntax: variable=expression;

Ex: c=6 (c  6)
c=(a+b)-(d+e)/f

2) Arithmetic operator: it is used to perform the arithmetical operations. These


operators are also known as basic operators. The operators are +, -, *, \,
%(modulus).

Ex: c=5+7 (c=12)


C=5%2 c=1 (remainder)

3) Relational operators or Comparison operators: These operators are used to


provide relation between the variables. The operators are >,<, >= ,<= , = =

4) Logical operators: These operators are used to provide more than one
condition, as the relational operators can provide only one condition. The
operators are && (and) , || (or), ! (not)

7
C Language

(&&)
Condition1 Condition2 Result
True True True
True False False
False True False
False False False

(||)
Condition1 Condition2 Result
True True True
True False True
False True True
False False False

(!)
Condition1 Result
True False
False True

5) Bitwise operators: These operators are used to perform the arithmetical


operations in terms of bits or binary digits. It is classified into 6 types.

6) Ternary operators: This opertor is also known as conditional operator. It is


used to specify the condition using ? and : operator. These operators are
combinely known as Ternary operator.
Ex: max=(a>b)?a:b;
7) Casting Operators: It is used to change the data type of the variable and the
content is stored in the other variable.
Ex: k=(int)f; (where k is int and f is float)
K=(char) ch; (where ch is a character containing integer
value)

8) Comma Operator: It is used to separate the contents or variable. It is


indicated with ,
Ex: int a,b,c;

9) Unary operators:

a) Address operator: it is represented with &. It is used to specify the address


of a variable.

b) Increment operator: it is indicated with ++. It is used to increase the value of


the variable. It is classified into two types. They are

8
C Language

Pre increment: it is used to increase the value of the variable of the


variable in the present statement. Here the operator is preceded by the
variable
Post increment: it is used to increase the value of the variable of the
variable in the next statement. Here the variable is preceded by the operator.

c) Decrement operator: it is indicated with - -. It is used to decrease the value


of the variable. It is classified into two types. They are
Pre decrement: it is used to decrease the value of the variable of the
variable in the present statement. Here the operator is preceded by the
variable
Post decrement: it is used to decrease the value of the variable of the
variable in the next statement. Here the variable is preceded by the operator.

d) Pointer operator: it is indicated with * . It is used to specify the value in a


pointer variable.
Ex: int *p;

e) typedef operator : it is used to specify the alternative name for a data type so
that this altenative name can be used instead of original data type name
Ex: typedef int integer ;
Integer a,b,c ;

f) sizeof operator : It is used to specify the number of bytes occupied by a


variable.
Ex: printf(« the number of byte of integer var is :%d »,sizeof(int)) ;

10) Other operators: in addition to these operators c++ supports many number of
operators which are used for the special purpose such as - >, .( ) , [] , ,, { } etc.,

Summary of Operators and Precedence

The highest priority operators are listed first.

Operator Operation Evaluated.

() parentheses left to right


[] square brackets left to right

++ increment right to left


-- decrement right to left
(type) cast operator right to left
* the contents of right to left
& the address of right to left
- unary minus right to left

9
C Language

~ one's complement right to left


! logical NOT right to left

* multiply left to right


/ divide left to right
% remainder (MOD) left to right

+ add left to right


- subtract left to right

>> shift right left to right


<< shift left left to right

> is greater than left to right


>= greater than or equal to left to right
<= less than or equal to left to right
< less than left to right

== is equal to left to right


!= is not equal to left to right

& bitwise AND left to right


^ bitwise exclusive OR left to right
| bitwise inclusive OR left to right
&& logical AND left to right
|| logical OR left to right

= assign right to left


+= add assign right to left
-= subtract assign right to left
*= multiply assign right to left
/= divide assign right to left
%= remainder assign right to left
>>= right shift assign right to left
<<= left shift assign right to left
&= AND assign right to left
^= exclusive OR assign right to left
|= inclusive OR assign right to left

Comments

10
C Language

Comments are a way of inserting remarks and reminders into a program without affecting
its content. Comments do not have a fixed place in a program: the compiler treats them as
though they were white space or blank characters and they are consequently ignored.
Programs can contain any number of comments without losing speed. This is because
comments are stripped out of a source program by the compiler when it converts the
source program into machine code.

Comments are marked out or delimited by the following pairs of characters:

/* ...... comment ......*/

Because a comment is skipped over as though it were a single space, it can be placed
anywhere where spaces are valid characters, even in the middle of a statement, though
this is not to be encouraged. You should try to minimize the use of comments in a
program while trying to maximize the readability of the program. If there are too many
comments you obscure your code and it is the code which is the main message in a
program.

Example 1

main () /* The almost trivial program */

/* This little line has no effect */


/* This little line has none */
/* This little line went all the way down
to the next line */
/* And so on ... */

Example 2

#include <stdio.h> /* header file */

#define NOTFINISHED 0

/**********************************************/

11
C Language

/* A bar like the one above can be used to */


/* separate functions visibly in a program */

main ()

{ int i; /* declarations */

do

{
/* Nothing !!! */
}

while (NOTFINISHED);

Question

1. What happens if a comment is not ended? That is if the programmer types /* .. to


start but forgets the ..*/ to close?

Program to display information on the output screen


#include<stdio.h>
void main()
{
clrscr();
printf("welcome to c world");
}

WAP to display your address


#include <stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\n Name : GRK");
printf("\n D.No. : 19-168");
printf("\n Street : GPT");
printf("\n City : VSP");
getch();
}

12
C Language

Program for demo on “\n” (new line)


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\nhello");
printf("\nhai");
printf("\nthis is ravi");
getch();
}

Program for demo on “\t” (tab space)


#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf("\nWelcome \t to \t c-language");
}

Program to find sum of two numbers


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter two numbers");
scanf("%d%d",&a,&b);
c=a+b;
printf("sum of two nos:%d",c);
getch();
}

WAP to accept address and display the address


#include <stdio.h>
#include<conio.h>
main()
{
char name[20],st[20],city[20],dno[20];
clrscr();
printf(" Enter Name :");
scanf("%s",name);
printf(" Enter D.No. :");
scanf("%s",dno);

13
C Language

printf(" Enter Street :");


scanf("%s",st);
printf(" Enter City :");
scanf("%s",city);
printf("\n Name : %s",name);
printf("\n Door no:%s",dno);
printf("\n street :%s",st);
printf("\n city :%s",city);
getch();
}

Write a program to read a character from keyboard and print its ASCII value.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("enter a character");
scanf("%c",&ch);
printf("The Equivalent ASCII value for the given characters is :%d",ch);
getch();
}

Write a program to read length and breadth or a rectangle and find its area and
perimeter.
#include<stdio.h>
#include<conio.h>
void main()
{
int l,b,area,peri;
clrscr();
printf("enter length of rectangle:");
scanf("%d",&l);
printf("enter breadth of rectangle:");
scanf("%d",&b);
area=l*b;
peri=
printf("The area of the rectangle:%d",area);
printf("The perimeter of the rectangle:%d",perm);
getch();
}

WAP to convert the given number is ASCII character


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

14
C Language

void main()
{
int n;
clrscr();
printf("Enter a value:");
scanf("%d",&n); /* char ch; ch=n;*/
printf("\n The ASCII charcter is:%c",n);
getch();
}

Write a program to read radius of a circle and find area and circumference.
#include<stdio.h>
#include<conio.h>
void main()
{
int r,area,cir;
clrscr();
printf("enter radius of the circle:");
scanf("%d",&r);
area=(3.14*r*r); cir=(2*3.14*r);
printf("The area of the circle:%d",area);
printf("The circumference of the circle:%d",cir);
getch();
}

Program to find addition, subtraction, multiplication, division and modulus of two


numbers
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,e,g;
float f;
clrscr();
printf("enter two numbers");
scanf("%d%d",&a,&b);
c=a+b;
d=a-b;
e=a*b;
f=a/b;
g=(float)a%b;
printf("\n sum of two numbers:%d",c);
printf("\n sub of two numbers:%d",d);
printf("\n multiplication of two numbers:%d",e);
printf("\n division of two numbers:%d",f);
printf("\n modulus of two numbers:%d",g);

15
C Language

getch();
}

Program to convert centigrade to Fahrenheit


# include <stdio.h>
# include <conio.h>
void main()
{
int c,f;
clrscr();
printf("enter the value of centigrade");
scanf("%d",&c);
f=(9*c/5)+32;
printf(" the value in Fahrenheit is %d",f);
getch();
}

program to swap two numbers using intermediate variable


#include <stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter two number”);
scanf(“%d%d”,&a,&b);
c=a;
a=b;
b=c;
printf(“After swapping the values are :%d %d”,a,b);
getch();
}

program to swap two numbers without using intermediate variable


#include <stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter two number”);
scanf(“%d%d”,&a,&b);
a=a+b;
b=a-b;
a=a-b;
printf(“After swapping the values are :%d %d”,a,b);

16
C Language

getch();
}

program to find the biggest of 2 numbers using conditional operator


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,max;
clrscr();
printf("enter first value");
scanf("%d",&a);
printf("enter second value");
scanf("%d",&b);
max=(a>b)?a:b;
printf("max value :%d",max);
getch();
}

program to find the biggest of 3 numbers using conditional operator


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,x,y;
clrscr();
printf("enter three values");
scanf("%d%d%d",&a,&b,&c);
x=(a>b)?a:b;
y=(x>c)?x:c;
printf("max value:%d",y);
getch();
}

WAP to find the smallest of 5 numbers using ternary operator (or) conditional
operator
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,d,e,x,y,z,p;
clrscr();
printf("Enter five values");
scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
x=(a<b)?a:b;
y=(c<d)?c:d;

17
C Language

z=(x<y)?x:y;
p=(z<e)?z:e;
printf("\n The smallest value is :%d",p);
getch();
}

WAP to accept customer number, customer name, previous month reading, current
month reading and find total number of units and net payment at the cost of 5.65
Rs. per unit.
#include <stdio.h>
#include <conio.h>
void main()
{
int cno,pmr,cmr,units;
char cname[50];
float netpay;
clrscr();
printf("Enter customer number:");
scanf("%d",&cno);
printf(" Enter customer name:");
scanf("%s",cname);
printf(" Enter Current Month Reading");
scanf("%d",&cmr);
printf("Enter previous month reading");
scanf("%d",&pmr);
units=cmr-pmr;
netpay=5.65*units;
printf("\n Total units :%d",units);
printf("\n Net Payment:%0.2f",netpay);
getch();
}

program for the demo on increment operator


#include<stdio.h>
#include<conio.h>
void main()
{
int i=65,j=57,a;
clrscr();
a=++i;
printf("\n the value after pre increment :%d",a);
a=j++;
printf ("\n the value after post increment:%d",a);
a=j;
printf("\n the value after post increment in next statement:%d",a);
getch();

18
C Language

output: the value after pre increment : 66


the value after post increment:57
the value after post increment in next statement: 58

Control statements
It is used to execute the block of statement as per the user requirement. It is classified into
four types. They are
1) Conditional statements
2) Un conditional statements
3) Decision making statements
4) Looping statements

1) conditional statements: The if-statement is known as conditional statement as it


executes the statements based on the condition in if-statement.

a) if-statement: if the given condition in if-statement is true then the


statements following if-statement will be executed. Otherwise it will not
execute the statements
syntax: if (condition)
{
statement(s);
}

b) if-else statement: it is similar to the if-statement, the only difference is


that if the condition in if-statement is false then the statements following
else-statement will be executed.
syntax: if (condition)
{
statement(s);
}
else
{
statement(s);
}

c) Nested-if statement: The main purpose of using this statement is to


provide more conditions in the if-statements so that the user can execute
the required statements.
syntax: if (condition 1)
{
statement(s);

19
C Language

}
else if (condition 2)
{
statement(s);
}
- - - - - - -
else
{
statement(s);
}

2) Unconditional statement: Generally it should not be supported because it makes


the user confuse about the program because it moves the control to the another
location. They should be used only within the control statements otherwise the
user may not get perfect requirement. It is classified into three types. They are

a) goto statement: It moves the control to the required statement based on


label name. Same label name should not be used twice and number of goto
statements should not used otherwise the programmer may confuse. Label
name can be used before or after the goto statement.
Syntax: goto <label-name>;
- - - ----
<label-name>:

b) Continue statement: The block of statements will be executed


continuously with out breaking the loop.
Syntax: continue;

c) break statement: it is used to move the control outside of the control


statements.
Syntax: break;

3) Decision Making Statement: It is also known as Multi-way Branching


Statement. It consists of an expression in switch case and the constant values in
case statements. A Decision Making Statement can have number of case-
statements based on the bytes occupied by a variable.

If the expression in switch statement matches with the constant value in


the case statement, then the statement after case statement will be executed. It
consists of default statement, which is used to execute the statements if all the
constant values in case-statement does not match with the switch expression. To
execute the statements only in a single case-statement then break statement should

20
C Language

be used so that after executing the statements in the control terminates from the
Decision Making Statement.

Syntax: switch (expression)


{
case constant-1:
statement(s);
case constant-2:
statement(s);
- - - -
case constant-n:
statement(s);
default :
statement(s);
}

4. looping statements: It is used to execute the block of statements continuously as


long as the condition is true. It is classified into three types. They are
a) for loop
b) while loop
c) do-while loop

a) For loop: The for loop contains initial/final value, condition and
increment/decrement value. Basing on them the statements within the for
loop will be executed. Expressions can be ignored by using the semicolons.
Syntax: for(<expression1>;<expression2>;<expression3>
{
statement(s);
}
expression-1: it consists of initial value or final value
expression-2: It consists of condition
expression-3: It consists of increment/decrement value

It also allows Nested for-loop. A for-loop within another for-loop


is known as nested for-loop. It includes more expressions.
Syntax:
for(<exp-1a>,<exp-1b>;<exp-2a>,<exp-2b>;<exp-3a>,<exp-3b>)
{
statement(s);
}

b) While loop: It contains only the expression (condition). The loop will be
executed as long as the condition is true. Nested while-loop is also allowed.
Syntax: while(condition)
{
statement(s);

21
C Language

c) Do-while loop: After executing the statements for the first time then it will
check the condition. It will execute the statements as long as the condition is
true. The main purpose of using do-while loop is to execute the block of
statements at least once even though the condition is false.
Syntax: do
{
statement(s);
}
while(condition);

Program to check whether the given number is equal or not


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter three numbers");
scanf("%d%d%d",&a,&b,&c);
if(a==b&&b==c)
printf("the values are equal");
else
printf("the values are not equal");
getch();
}

Program to check whether the given number is even or odd


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a value: ");
scanf("%d",&n);
if (n%2==0)
printf("It is even");
else
printf("It is odd");

}
getch();
}

22
C Language

Program to find the biggest of 3 numbers


#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
printf("enter three numbers");
scanf("%d%d%d",&a,&b,&c);
if (a>b && a>c)
{
printf("the biggest number is:%d",a);
}
else if(b>a && b>c)
{
printf(" the biggest number is:%d",b);
}
else
{
printf(" the biggest number is:%d",c);
}
getch();
}

program to find whether the given number is positive, negative or zero


#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf ("enter one number");
scanf("%d",&n);
if (n>0)
{
printf("the no is positive:%d",n);
}
else
if (n<0)
{
printf ("the no is negative:%d",n);
}
else
{

23
C Language

printf ("the no is equal to zero:%d",n);


}
getch();
}

Program to accept gender and find whether he/she is eligible for voting or not
#include<stdio.h>
#include<conio.h>
void main()
{
char gender;
clrscr();
printf("enter gender");
scanf("%c",&gender);
if(gender=='m')
printf("the eligible age is 21");
else if(gender=='f')
printf("the eligible age is 18");
else
printf("check your gender");
getch();
}

Program to accept gender and age and find whether he/she is eligible for voting or
not
#include<stdio.h>
#include<conio.h>
void main()
{
char gender;
int age;
clrscr();
printf("enter gender");
scanf("%c",&gender);
printf("Enter Age");
scanf("%d",&age);
if(gender=='m' || gender=='M')
{ if(age>=21)
printf("He is Eligible for voting");
else
prinf("He is Not eligible for voting");
}
else if(gender=='f' || gender=='F')
{ if(age>=18)
printf("She is Eligible for voting");
else

24
C Language

prinf("She is Not eligible for voting");


}
else
{
printf("Wrong input");
}
getch();
}

the above program using switch-case


/* switch(n%2)
{
case 0: printf("It is even");
case 1: printf("It is odd");

WAP to find Quadratic Roots


#include<stdio.h>
#include<conio.h>
#include <math.h>
void main()
{
int a,b,c,d;
float x1,x2;
clrscr();
printf("Enter values for a,b,c");
scanf("%d%d%d",&a,&b,&c);
d=(b*b)-(4*a*c);
if (d==0)
{
printf("\n Roots are real & equal");
x1=x2=-b/(2*a);
printf("\n The two roots are:%f\t%f" ,x1,x2);
}
else if (d>0)
{
printf("\n Roots are real & unequal");
x1=(-b+sqrt(d) )/(2*a);
x2=(-b-sqrt(d) )/(2*a);
printf("\n The two roots are:%f\t%f",x1,x2);
}
else
{
printf("\n Roots are imaginary");
x1=-b/(2*a);
x2=sqrt(d)/(2*a);
printf("\n First root: %f+i(%f)",x1,x2);

25
C Language

printf("\n Second root: %f-i(%f)",x1,x2);


}
getch();
}

Program to accept employ number, employ name, basic salary and calculate ta,da,
hra, pf, it, net salary, gross salary (if-statement)
#include<stdio.h>
#include<conio.h>
void main()
{
char ename[10];
int eno;
float ta,da,hra,pf,it,nsal,gsal,basic;
clrscr();
printf("Enter employ number");
scanf("%d",&eno);
printf("Enter Employ Name");
scanf("%s",ename);
printf("Enter Basic salary");
scanf("%f",&basic);
if (basic<=5000)
{
ta=(6.8*basic)/100;
da=(5.8*basic)/100;
hra=(6.9*basic)/100;
pf=(12.5*basic)/100;
it=(10*basic)/100;
}
else if (basic>5000 && basic<=10000)
{
ta=(8.9*basic)/100;
da=(12.8*basic)/100;
hra=(9.9*basic)/100;
pf=(11.5*basic)/100;
it=(12*basic)/100;
}
else if (basic>10000 && basic<=20000)
{
ta=(12.8*basic)/100;
da=(15.8*basic)/100;
hra=(16.9*basic)/100;
pf=(17.5*basic)/100;
it=(15.9*basic)/100;
}
else if (basic>20000)

26
C Language

{
ta=(15.8*basic)/100;
da=(16.8*basic)/100;
hra=(19.8*basic)/100;
pf=(19.5*basic)/100;
it=(18.99*basic)/100;
}
gsal=basic+ta+da+hra;
nsal=gsal-it-pf;
clrscr();
printf("\n The employ number:%d",eno);
printf("\n The employ name:%s",ename);
printf("\n The Basic Salary:%0.2f",basic);
printf("\n The Travelling allowance:%0.2f",ta);
printf("\n The Dearness allowance:%0.2f",da);
printf("\n The Provident fund:%0.2f",pf);
printf("\n The Income Tax:%0.2f",it);
printf("\n The House Rent Alowance:%0.2f",hra);
printf("\n The Gross Salary:%0.2f",gsal);
printf("\n The Net Salary:%0.2f",nsal);
getch();
}

write a program to accept 3 sides and check whether it is right angled triangle,
obtuse angled triangle, acute angled triangle, scalene triangle, equivaleteral triangle
or isosceles triangle
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,max,x,y;
clrscr();
printf("Enter values for three sides"):
scanf("%d%d%d",&a,&b,&c);
if (a>b && a>c)
{
max=a;
x=b;
y=c;
}
else if (b>a && b>c)
{
max=b;
x=a;
y=c;
}

27
C Language

else
{
max=c;
x=a;
y=b;
}
if (max<(a+b))
{
if ( (max*max)=(x*x)+(y*y) )
printf("\n It is Right angled triangle");
else if ( (max*max)>(x*x)+(y*y) )
printf("\n It is Obtuse angled triangle");
else
printf("\n It is Acute angled triangle");
if(a==b==c)
printf("\n It is Equilateral triangle");
else if(a==b || b==c || c==a)
printf("\n It is Isosceles triangle");
else
printf("\n It is Scalene triangle");
}
else
{
printf(“It is not a triangle”);
}
getch();
}

Program to display the equivalent day for the given value(1-7) (switch-case)
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number(1-7)");
scanf("%d",&n);
switch(n)
{
case 1: printf("\n Sunday");break;
case 2: printf("\n Monday");break;
case 3: printf("\n Tuesday");break;
case 4: printf("\n Wednesday");break;
case 5: printf("\n Thursday");break;
case 6: printf("\n Friday");break;
case 7: printf("\n Saturday");break;

28
C Language

default: printf("Wrong input");


}
getch();
}

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter a number(1-7)");
scanf("%d",&n);
switch(n)
{
case 1: printf("\n Sunday");
case 2: printf("\n Monday");
case 3: printf("\n Tuesday");
case 4: printf("\n Wednesday");
case 5: printf("\n Thursday");
case 6: printf("\n Friday");
case 7: printf("\n Saturday");break;
default: printf("Wrong input");
}
getch();
}

WAP to check whether the given character is vowel or consonant


#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter a character");
scanf("%c",&ch);
switch(ch)
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
printf("It is vowel");break;
default: printf("It is consonant");break;
}

29
C Language

getch();
}

Program to display the day for the given date in august 2002 (switch-case)
#include<stdio.h>
#include<conio.h>
void main()
{
int date;
clrscr();
printf("Enter date in August 2002(1-31)");
scanf("%d",&date);
if (date>=1 && date<=31)
{
switch(date%7)
{
case 1: printf("\n Thursday");break;
case 2: printf("\n Friday");break;
case 3: printf("\n Saturday");break;
case 4: printf("\n Sunday");break;
case 5: printf("\n Monday");break;
case 6: printf("\n Tuesday");break;
case 0: printf("\n Wednesday");break;
}
}
else
{
printf("Wrong input ! Try again");
}
getch();
}

WAP to print the natural numbers (goto-statement)


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i=1;
clrscr();
printf("Enter the final value");
scanf("%d",&n);
printf("The natural numbers are \n");
natural:
if(i<=n)
{
printf("%5d",i); i++;

30
C Language

goto natural;
}
getch();
}

WAP to find the factorial of the given number (for-loop)


// 5!=120 (1*2*3*4*5)
#include <stdio.h>
#include<conio.h>
void main()
{
long int n,i,f=1;
clrscr();
printf("Enter a value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("\n The factorial of given no: %ld",f);
getch();
}

WAP to find the sum and count of even, odd and natural numbers for the given
number
#include <stdio.h>
#include<conio.h>
void main()
{
int n,i,esum,osum,nsum,ecount,ocount,ncount;
clrscr();
esum=osum=nsum=ecount=ocount=ncount=0;
printf("Enter the final value");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
{
ecount=ecount+1;
esum=esum+i;
}
else
{
ocount=ocount+1;
osum=osum+i;
}

31
C Language

}
nsum=esum+osum;
ncount=ecount+ocount;
printf("\n sum of even nos: %d",esum);
printf("\n sum of odd nos: %d",osum);
printf("\n sum of natural nos: %d",nsum);
printf("\n count of even nos: %d",ecount);
printf("\n count of odd nos: %d",ocount);
printf("\n count of natural nos: %d",ncount);
getch();
}

WAP to find whether the given number is prime or not


#include <stdio.h>
#include<conio.h>
void main()
{
int i,n,c=0;
clrscr();
printf("Enter a number");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
c=c+1;
}
if(c= =2)
printf("it is prime no");
else
printf("it is composite no");
getch();
}

WAP to the multiplication table of the given number


#include <stdio.h>
#include<conio.h>
void main()
{
int n,i;
clrscr();
printf("Enter a value");
scanf("%d",&n);
for(i=1;i<=20;i++)
{
printf("\n %5d*%5d=%5d",n,i,n*i);
}

32
C Language

getch();
}

WAP to print 20 multiplication tables upto 12 values


#include <stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=20;i++)
{
for(j=1;j<=12;j++)
{
printf("\n %5d*%5d=%5d",i,j,i*j);
}
printf("\n\n\n\n\n Press any key to continue");
getch();
clrscr();
}
}

program to find simple interest and compound interest


#include<stdio.h>
#include<conio.h>
void main()
{
float p,r,s,c;
int n,i=1;
clrscr();
printf("\n Enter the principle amount.");
scanf("%f",&p);
printf("\n Enter the rate of interest in %.");
scanf("%f",&r);
printf("\n Enter the time in years.");
scanf("%d",&n);
s=(p*n*r)/100;
printf("\n Rs.%f is the simple interest.",s);
while(i<=n)
{ c=p*(1+(r/100));
p=c;
i++;
}
printf("\nRs.%f is the compound interest.",c);
getch();
}

33
C Language

WAP to check whether the given number is armstrong or not


def: if the given number is equal to the sum of the cubes of individual digits then it is
known as armstrong
ex: 407,153=13 + 53 + 33 = 1 + 125 + 27 = 153
#include<stdio.h>
#include<conio.h>
void main()
{
int r,s=0,n,m;
clrscr();
printf("Enter a number");
scanf("%d",&n);
m=n;
while(n>0)
{
r=n%10;
n=n/10;
s=s+(r*r*r);
}
if (m==s)
printf("The number is Armstrong");
else
printf("The number is not a Armstrong");
getch();
}

WAP to print the following series


12345
12345
12345
12345
12345
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<5;j++)
{
printf("%5d",i);
}
printf("\n");

34
C Language

}
getch();
}

WAP to print the following series


11111
22222
33333
44444
55555
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
printf("%5d",i);
}
printf("\n");
}
getch();
}

WAP to find the value of the following series for the given value 1!+2!+3!+..............
#include<conio.h>
void main()
{
long int i,j,n,f,sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
f=1;
for(j=1;j<=i;j++)
{
f=f*j;
}
sum=sum+f;
}
printf("The value for the series is :%`ld",sum);
getch();

35
C Language

WAP to find the value of the following series


-12+22 -32 +4 2 –52 .........

#include<stdio.h>
#include<conio.h>
void main()
{
long int i,j,n,f,sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
if (i%2==0)
sum=sum+(i*i) ;
else
sum=sum-(i*i);
}
printf("The value for the series is :%ld",sum);
getch();
}

1/2 +2/3+3/4+4/5+...........
#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n;
float sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
sum=sum+(float) ( i/ (i+1) );
}
printf("The value for the series is :%f",sum);
getch();
}

-1/2 + 3/4 - 5/6 + 7/8 ...........


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

36
C Language

{
long int i,n;
float sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i+=2)
{
if((i+1)%4= =0)
sum=sum+(float)( i/ (i+1) );
else
sum=sum-(float) ( i/ (i+1) );
}
printf("The value for the series is :%f",sum);
getch();
}

-1 + 2 - 3 + 4 - 5 + 6 .......
#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n,sum=0;
clrscr();
printf("Enter the final value");
scanf("%ld",&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
sum=sum+ i;
else
sum=sum- i;
}
printf("The value for the series is :%d",sum);
getch();
}

WAP to find the value of the following series


1/3-2/4+3/5-4/6............
#include<stdio.h>
#include<conio.h>
void main()
{
long int i,n;
float sum=0;
clrscr();

37
C Language

printf("Enter the final value");


scanf("%ld",&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
sum=sum-(float)( i/ (i+2) );
else
sum=sum+(float) ( i/ (i+2) );
}
printf("The value for the series is :%f",sum);
getch();
}

1+2+4+7+11+…………
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,i,n,k=0;
clrscr();
printf("Enter a value");
scanf("%d",&n);
for(i=1;i<=n;i=i+k)
{
k++;
printf("%5d",i);
sum=sum+i;

}
printf("\n The value is:%d",sum);
getch();
}

WAP to print the following series


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)

38
C Language

{
for(j=1;j<=i;j++)
{
printf("%5d",j);
}
printf("\n");
}
getch();
}

WAP to print the following series


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%5d",i);
}
printf("\n");
}
getch();
}

WAP to print the following series


ravi
ravi ravi
ravi ravi ravi
ravi ravi ravi ravi
ravi ravi ravi ravi ravi

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();

39
C Language

for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("ravi \t");
}
printf("\n");
}
getch();
}

WAP to print the following series



☺☺
☺☺☺
☺☺☺☺
☺☺☺☺☺
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%c\t",2);
}
printf("\n");
}
getch();
}

WAP to print the following series


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

#include<conio.h>
void main()
{
int i,j,k=1;
clrscr();

40
C Language

for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t",k++);
}
printf("\n");
}
getch();
}

WAP to print the following series


1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 24
26 27 28 29 30
#include<conio.h>
void main()
{
int i,j,k=1;
clrscr();
for(i=1;i<=6;i++)
{
for(j=1;j<=5;j++)
{
printf("%d\t",k++);
}
printf("\n");
}
getch();
}

WAP to print the following series


1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
#include<conio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)

41
C Language

{
for(j=1;j<=i;j++)
{
printf("%d\t",j);
}
printf("\n");
}
getch();
}

WAP to print the following series


1
2 2
3 3 3
4 4 4 4
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,n,p=40;
clrscr();
printf("ENTER THE VALUES OF N:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for (j=1;j<=p;j++)
{
printf(" ");
}
for(j=1;j<=i;j++)
{
printf("%d ",i);
}
p-=2;
printf("\n");
}
getch();
}

WAP to print the following series


ravi
rav
ra
r
#include”conio.h”
#include"stdio.h"

42
C Language

void main()
{
int i,j,l;
char n[15];
clrscr();
printf("\n Enter the string.");
scanf("%s",&n);
for(i=0;n[i]!='\0';i++);
l=i;
for(i=l;i>=0;i--)
{
for(j=i;j>=0;j--)
{
printf("%c",n[j]);
}
printf("\n");
}
getch();
}

WAP to print the following series


ivar
iva
iv
i
#include"stdio.h"
void main()
{
int i,j,k,l=0;
char n[30];
clrscr();
printf("\n Enter the string.");
scanf("%s",&n);
strrev(n);
for(i=0;n[i]!='\0';i++)
l=i;
for(i=0;i<l;i++)
{
for(j=i;j>=0;j--)
{
printf("%c",n[j]);
}
printf("\n");
}
getch();
}

43
C Language

WAP to print the following series


i
vi
avi
ravi
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,l=0;
char n[30];
clrscr();
printf("enter a string\n");
scanf("%s",n);
strrev(n);
for(i=0;n[i]!='\0';i++)
{
l++;
}
for(i=l;i>=0;i--)
{
for(j=0;j<i;j++)
{
printf("%c",n[j]);
}
printf("\n");
}
getch();
}

WAP to print the following series


ivar
iva
iv
i
#include"stdio.h"

44
C Language

void main()
{
int i,j;
char n[30];
clrscr();
printf("\n Enter the string.");
scanf("%s",&n);
for (i=0;n[i]!='\0';i++)
for(j=0;j<=i;j++)
{
printf("\n %c %s",n[j],n);
}
getch();
}

Arrays
An Array is a collection of values in same datatype. Arrays are mainly two type there are

1.single dimensional arrays


2.multi dimensional arrays

Arrays are a convenient way of grouping a lot of variables under a single variable name.
Arrays are like pigeon holes or chessboards, with each compartment or square acting as a
storage place; they can be one dimensional, two dimensional or more dimensional! An
array is defined using square brackets []. For example: an array of three integers called
"triplet" would be declared like this:

int triplet[3];

Notice that there is no space between the square bracket [ and the name of the array. This
statement would cause space for three integers type variables to be created in memory
next to each other as in the diagram below.

------------------------------------
int triplet: | | | |
------------------------------------

45
C Language

The number in the square brackets of the declaration is referred to as the `index' (plural:
indicies) or `subscript' of the array and it must be an integer number between 0 and (in
this case) 2. The three integers are called elements of the array and they are referred to in
a program by writing:

triplet[0]
triplet[1]
triplet[2]

Note that the indicies start at zero and run up to one less than the number which is placed
in the declaration (which is called the dimension of the array.) The reason for this will
become clear later. Also notice that every element in an array is of the same type as every
other. It is not (at this stage) possible to have arrays which contain many different data
types. When arrays are declared inside a function, storage is allocated for them, but that
storage space is not initialized: that is, the memory space contains garbage (random
values). It is usually necessary, therefore, to initialize the array before the program truly
begins, to prepare it for use. This usually means that all the elements in the array will be
set to zero.

Why use arrays?


Arrays are most useful when they have a large number of elements: that is, in cases
where it would be completely impractical to have a different name for every storage
space in the memory. It is then highly beneficial to move over to arrays for storing
information for two reasons:

 The storage spaces in arrays have indicies. These numbers can often be related to
variables in a problem and so there is a logical connection to be made between an
array an a program.
 In C, arrays can be initialized very easily indeed. It is far easier to initialize an
array than it is to initialize twenty or so variables.

The first of these reasons is probably the most important one, as far as C is concerned,
since information can be stored in other ways with equally simple initialization facilities
in C. One example of the use of an array might be in taking a census of the types of car
passing on a road. By defining macros for the names of the different cars, they could
easily be linked to the elements in an array.

Example Programs

1.write a c program to print five array values.

#include<stdio.h>

#include<conio.h>

46
C Language

Void main()

int a[5],i;

clrscr();

printf(“enter the 5 array elements”);

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

scanf(“%d”,&a[i]);

printf(“array values is \n”);

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

printf(“%d \n”,a[i]);

getch();

2.write a c progam to print the given array values reverse order.

#include<stdio.h>

#include<conio.h>

Void main()

int a[55],i,n;

clrscr();

47
C Language

printf(“enter the n range”);

scanf(“%d”,&n);

printf(“enter the %d array elements”,n);

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

scanf(“%d”,&a[i]);

printf(“array values reverse order is \n”);

for(i=n-1; i>=0; i--)

printf(“%d \n”,a[i]);

getch();

3.write a c program to print sum of the given array values.

#include<stdio.h>

#include<conio.h>

void main()

int a[56],i,sum=0;

clrscr();

printf(“enter the n value”);

scanf(“%d”,&n);

48
C Language

printf(“enter the %d array values”,n);

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

scanf(“%d”,&a[i]);

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

sum=sum+a[i];

printf(“sum of array values is %d”,sum);

getch();

searching techniques

program for linear search


# include<iostream.h>
# include<conio.h>
void main()
{
int flag = 1,i,a[100],k;
clrscr();
printf(“Enter how many elements”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“Enter the element to be searched”);
scanf(“%d”,&k);

49
C Language

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


{
if(a[i] == k)
{
printf("\n Search is successful \n");
printf(“\n Element %d Found at Location : ",k,(i+1));
flag = 0 ;
}
}
if (flag)
printf( "\n Search is unsuccessful");
getch();
}

Program for binary search


Searching an element in the list of elements, which are in ascending order is the process
of binary search
# include<stdio.h>
# include<conio.h>
void main()
{
int flag=1,k,low=0,high,mid,n, a[200],i;
clrscr();
printf(“How many elements you want?”);
scanf(“%d”,&n);
high=n-1;
printf("\nEnter elements in Ascending order:\n ");
for(i=0;i<n;i++)
{
printf(“Enter the element:”);
scanf(“%d,&a[i]);
}
printf(“Enter element to be searched”);
scanf(“%d”,&k);
while(low <= high)
{
mid = (low + high)/2;
if( k < a[mid]) /* element in lower half*/
high = mid - 1 ;
else if(k > a[mid]) /* element in upper half*/
low = mid + 1 ;
else if(k == a[mid])
{
printf(“\n Search is successful \n)";
printf("\n Element %d Found at Location : ",k,(mid+1));
flag = 0 ;

50
C Language

break ;
}
}
if (flag)
printf( "\n Search is unsuccessful");
getch();
}
sorting techniques
The process of arranging the data either in ascending order or descending order is known
as sorting . sorting of data is done using 7 techniques
1) Bubble sort
2) Insertion sort
3) Selection sort
4) Merge sort
5) Quick sort
6) Radix sort
7) Heap sort

51
C Language

Unformatted input and output statements

1) input statements

a) gets(): it is used to accept a string until it founds return key (ente). the last
character is treated as NULL character and is indicated with NULL or '\0'
Syntax: gets(variable);
Example: gets(s);

b) getchar(): it is used to accept a single character into the variable.


Syntax: variable =getchar();
Ex: ch=getchar();

c) getch(): it is used to accept a single character into a variable which will not be
appeared on the screen.
Syntax: getch(variable);
Ex: getch(ch);

d) getche(): it is also used to accept a single character as similar to getchar(). The


main difference is that getche() is a macro where as getch() or getchar() are functions.
Syntax: getche(variable);
Ex: getche(ch);

2) output statements

a) puts(): it is used to display the string in the new line until it found enter key.
Syntax: puts(variable);
ex: puts(ch);

b) putchar(): it is used to display a single character.


Syntax: variable=putchar()
Ex: ch=putchar();

c) putche(), putch(): it is used to display a single character where putche() is a macro


and putch() is a function.
Syntax: putche(variable);
Syntax: putch(variable);
Ex: putch(s);

52
C Language

String Functions

The C Standard Library commonly provides a number of very useful functions which
handle strings. Here is a short list of some common ones which are immediately relevant
(more are listed in the following chapter). Chances are, a good compiler will support a lot
more than those listed below, but, again, it really depends upon the compiler.

string functions

the header file is #include "string.h". it is used to accept a string and returns either string
or numeric value.
1) strlen(): to find the length of the string
EX: strlen("it is c"); 7
2) strrev(): to reverse the given string
ex: strrev("ravali"); ilavar
3) strcpy(): it is used to copy the string into a variable
ex: strcpy(result,"pass");
4) strupr(): converts the lower case characters in a string into upper case characters.
ex: strupr('Ravi'); RAVI
5) strlwr(): converts the upper case characters in a string into lower case characters.
ex: strlwr('Ravi'); ravi
6) strcmp(): compare the given two strings.
syntax: strcmp(string1,string2)
if string1=string2 then it returns 0
if string1>string2 then it returns positive
if string1<string2 then it returns negative
ex: strcmp("ravi","srinu") -1
7) stricmp() : ignores case

strlen()
This function returns a type int value, which gives the length or number of
characters in a string, not including the NULL byte end marker. An example is:
int len;
char *string;
len = strlen (string);

strcpy()
This function copies a string from one place to another. Use this function in
preference to custom routines: it is set up to handle any peculiarities in the way
data are stored. An example is
char *to,*from;

to = strcpy (to,from);

53
C Language

Where to is a pointer to the place to which the string is to be copied and from is the
place where the string is to be copied from.

strcmp()
This function compares two strings and returns a value which indicates how they
compared. An example:
int value;
char *s1,*s2;

value = strcmp(s1,s2);

The value returned is 0 if the two strings were identical. If the strings were not the
same, this function indicates the (ASCII) alphabetical order of the two. s1 > s2,
alphabetically, then the value is > 0. If s1 < s2 then the value is < 0. Note that
numbers come before letters in the ASCII code sequence and also that upper case
comes before lower case.

strstr()
Tests whether a substring is present in a larger string
int n;
char *s1,*s2;

if (n = strstr(s1,s2))
{
printf("s2 is a substring of s1, starting at %d",n);
}

strncpy()
This function is like strcpy, but limits the copy to no more than n characters.
strncmp()
This function is like strcmp, but limits the comparison to no more than n
characters.

More string functions are described in the next section along with a host of Standard
Library Functions.

String Input/Output

54
C Language

Because strings are recognized to be special objects in C, some special library functions
for reading and writing are provided for them. These make it easier to deal with strings,
without the need for special user-routines. There are four of these functions:

gets()
puts()
sprintf()
sscanf()

 gets():
 puts():
 sprintf():
 sscanf():

gets()

This function fetches a string from the standard input file stdin and places it into some
buffer which the programmer must provide.

#define SIZE 255

char *sptr, buffer[SIZE];

strptr = gets(buffer);

If the routine is successful in getting a string, it returns the value buffer to the string
pointer strptr. Otherwise it returns NULL (==0). The advantage of gets() over scanf("%s"..) is
that it will read spaces in strings, whereas scanf() usually will not. gets() quits reading when
it finds a newline character: that is, when the user presses RETURN.

NOTE: there are valid concerns about using this function. Often it is implemented as a
macro with poor bounds checking and can be exploited to produce memory corruption by
system attackers. In order to write more secure code, use fgets() instead.

puts()

puts() sends a string to the output file stdout, until it finds a NULL end of string marker.
The NULL byte is not written to stdout, instead a newline character is written.

char *string;
int returncode;

returncode = puts(string);

55
C Language

puts() returns an integer value, whose value is only guaranteed if there is an error.
returncode == EOF if an end of file was encountered or there was an error.

sprintf()

This is an interesting function which works in almost the same way as printf(), the
exception being that it prints to a string! In other words it treats a string as though it were
an output file. This is useful for creating formatted strings in the memory. On most
systems it works in the following way:

int n;
char *sp;

n = sprintf (sp, "control string", parameters, values);

n is an integer which is the number of characters printed. sp is a pointer to the destination


string or the string which is to be written to. Note carefully that this function does not
perform any check on the output string to make sure that it is long enough to contain the
formatted output. If the string is not large enough, then a crash could be in store! This can
also be considered a potential security problem, since buffer overflows can be used to
capture control of important programs. Note that on system V Unix systems the sprintf
functionr returns a pointer to the start of the printed string, breaking the pattern of the
other printf functions. To make such an implementation compatible with the usual form
you would have to write:

n = strlen(sprintf(parameters......));
sscanf()

This function is the complement of sprintf(). It reads its input from a string, as though it
were an input file.

int n;
char *sp;

n = sscanf (sp,"control string", pointers...);

sp is a pointer to the string which is to be read from. The string must be NULL terminated
(it must have a zero-byte end marker '\0'). sscanf() returns an integer value which holds the
number of items successfully matched or EOF if an end of file marker was read or an error
occurred. The conversion specifiers are identical to those for scanf().

56
C Language

program to accept a name and find the length


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

{
char s[50];
int i,l=0;
clrscr();
puts("enter a name");
gets(s);
for(i=0;s[i]!='\0';i++)
{
l++;
}
printf("the length of the string:%d",l);
getch();
}

WAP to check whether the given string is palendrome or not


#include <stdio.h>
#include <conio.h>
void main()
{
char s[50],s1[50];
int f=1,i,l=0,j=0;
clrscr();
puts("enter a string");
gets(s);
for(i=0;s[i]!='\0';i++)
l++;
for(i=l-1;i>=0;i--)
{ s1[j++]=s[i];
}
s1[j]='\0';
for(i=0;s[i]!='\0';i++)
{
if (s[i]!=s1[i])
{
f=0;
}
}
if (f==0)
puts("it is not a palendrome");
else

57
C Language

puts("it is a palendrome");
getch();
}

58
C Language

Functions
Functions break large computing tasks into smaller ones, and enable people to build on
what others have done instead of starting over from scratch. Appropriate functions hide
details of operation from parts of the program that don't need to know about them, thus
clarifying thewhole, and easing the pain of making changes.

C has been designed to make functions efficient and easy to use; C programs generally
consist of many small functions rather than a few big ones. A program may reside in one
or more source files. Source files may be compiled separately and loaded together, along
with previously compiled functions from libraries. We will not go into that process here,
however, since the details vary from system to system.

A function is a module or block of program code which deals with a particular task.
Making functions is a way of isolating one block of code from other independent blocks
of code. Functions serve two purposes. They allow a programmer to say: `this piece of
code does a specific job which stands by itself and should not be mixed up with anyting
else', and they make a block of code reusable since a function can be reused in many
different contexts without repeating parts of the program text.

Functions help us to organize a program in a simple way; in Kernighan & Ritchie C they
are always written in the following form:

identifier (parameter1,parameter2,..)

types of parameters

{ variable declarations

statements..
......
....

In other languages and in mathematics a function is understood to be something which


produces a value or a number. That is, the whole function is thought of as having a value.
In C it is possible to choose whether or not a function will have a value. It is possible to
make a function hand back a value to the place at which it was called. Take the following
example:

bill = CalculateBill(data...);

59
C Language

The variable bill is assigned to a function CalculateBill() and data are some data
which are passed to the function. This statement makes it look as though
CalculateBill() is a number. When this statement is executed in a program, control
will be passed to the function CalculateBill() and, when it is done, this function will
then hand control back. The value of the function is assigned to "bill" and the program
continues. Functions which work in this way are said to return a value.

In C, returning a value is a simple matter. Consider the function CalculateBill() from the
statement above:

CalculateBill(starter,main,dessert) /* Adds up values */

int starter,main,dessert;

{ int total;

total = starter + main + dessert;


return (total);
}

As soon as the return statement is met CalculateBill() stops executing and assigns
the value total to the function. If there were no return statement the program could not
know which value it should associate with the name CalculateBill and so it would not
be meaningful to speak of the function as having one value. Forgetting a return
statement can ruin a program. For instance if CalculateBill had just been:

CalculateBill (starter,main,dessert) /* WRONG! */

int starter,main,dessert;

{ int total;

total = starter + main + dessert;


}

then the value bill would just be garbage (no predictable value), presuming that the
compiler allowed this to be written at all. On the other hand if the first version were used
(the one which did use the return(total) statement) and furthermore no assignment
were made:

main ()

{
CalculateBill (1,2,3);
}

60
C Language

then the value of the function would just be discarded, quite legitimately. This is usually
what is done with the input output functions printf() and scanf() which actually
return values. So a function in C can return a value but it does not have to be used; on the
other hand, a value which has not been returned cannot be used safely.

NOTE : Functions do not have to return integers: you can decide whether they
should return a different data type, or even no value at all. (See next chapter)

Character Identification

Some or all of the following functions/macros will be available for identifying and
classifying single characters. The programmer ought to beware that it would be natural
for many of these facilities to exist as macros rather than functions, so the usual remarks
about macro parameters apply, See Preprocessor. An example of their use is given above.
Assume that `true' has any non-zero, integer value and that `false' has the integer value
zero. ch stands for some character, or char type variable.

isalpha(ch)
This returns true if ch is alphabetic and false otherwise. Alphabetic means a..z or
A..Z.
isupper(ch)
Returns true if the character was upper case. If ch was not an alphabetic character,
this returns false.
islower(ch)
Returns true if the character was lower case. If ch was not an alphabetic character,
this returns false.
isdigit(ch)
Returns true if the character was a digit in the range 0..9.
isxdigit(ch)
Returns true if the character was a valid hexadecimal digit: that is, a number from
0..9 or a letter a..f or A..F.
isspace(ch)
Returns true if the character was a white space character, that is: a space, a TAB
character or a newline.
ispunct(ch)
Returns true if ch is a punctuation character.
isalnum(ch)
Returns true if a character is alphanumeric: that is, alphabetic or digit.
isprint(ch)
Returns true if the character is printable: that is, the character is not a control
character.
isgraph(ch)
Returns true if the character is graphic. i.e. if the character is printable (excluding
the space)
iscntrl(ch)

61
C Language

Returns true if the character is a control character. i.e. ASCII values 0 to 31 and
127.
isascii(ch)
Returns true if the character is a valid ASCII character: that is, it has a code in the
range 0..127.
iscsym(ch)
Returns true if the character was a character which could be used in a C identifier.
toupper(ch)
This converts the character ch into its upper case counterpart. This does not affect
characters which are already upper case, or characters which do not have a
particular case, such as digits.
tolower(ch)
This converts a character into its lower case counterpart. It does not affect
characters which are already lower case.
toascii(ch)
This strips off bit 7 of a character so that it is in the range 0..127: that is, a valid
ASCII character.

/********************************************************/
/* */
/* Demonstration of character utility functions */
/* */
/********************************************************/

/* prints out all the ASCII characters which give */


/* the value "true" for the listed character fns */

#include <stdio.h>
#include <ctype.h> /* contains character utilities */

#define ALLCHARS ch = 0; isascii(ch); ch++

/********************************************************/

main () /* A criminally long main program! */

{ char ch;

printf ("VALID CHARACTERS FROM isalpha()\n\n");

for (ALLCHARS)
{
if (isalpha(ch))
{
printf ("%c ",ch);
}

62
C Language

printf ("\n\nVALID CHARACTERS FROM isupper()\n\n");

for (ALLCHARS)
{
if (isupper(ch))
{
printf ("%c ",ch);
}
}

printf ("\n\nVALID CHARACTERS FROM islower()\n\n");

for (ALLCHARS)
{
if (islower(ch))
{
printf ("%c ",ch);
}
}

printf ("\n\nVALID CHARACTERS FROM isdigit()\n\n");

for (ALLCHARS)
{
if (isdigit(ch))
{
printf ("%c ",ch);
}
}

printf ("\n\nVALID CHARACTERS FROM isxdigit()\n\n");

for (ALLCHARS)
{
if (isxdigit(ch))
{
printf ("%c ",ch);
}
}

printf ("\n\nVALID CHARACTERS FROM ispunct()\n\n");

for (ALLCHARS)
{

63
C Language

if (ispunct(ch))
{
printf ("%c ",ch);
}
}

printf ("\n\nVALID CHARACTERS FROM isalnum()\n\n");

for (ALLCHARS)
{
if (isalnum(ch))
{
printf ("%c ",ch);
}
}

printf ("\n\nVALID CHARACTERS FROM iscsym()\n\n");

for (ALLCHARS)
{
if (iscsym(ch))
{
printf ("%c ",ch);
}
}
}
Program Output
VALID CHARACTERS FROM isalpha()

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij
klmnopqrstuvwxyz

VALID CHARACTERS FROM isupper()

ABCDEFGHIJKLMNOPQRSTUVWXYZ

VALID CHARACTERS FROM islower()

abcdefghijklmnopqrstuvwxyz

VALID CHARACTERS FROM isdigit()

0123456789

VALID CHARACTERS FROM isxdigit()

64
C Language

0123456789ABCDEFabcdef

VALID CHARACTERS FROM ispunct()

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

VALID CHARACTERS FROM isalnum()

0123456789ABCDEFGHIJKLMNOPQRSTUVW
XYZabcdefghijklmnopqrstuvwxyz

VALID CHARACTERS FROM iscsym()

0123456789ABCDEFGHIJKLMNOPQRSTUVW
XYZ_abcdefghijklmnopqrstuvwxyz

Mathematical Functions

C has a library of standard mathematical functions which can be accessed by #including


the appropriate header files (math.h etc.). It should be noted that all of these functions
work with double or long float type variables. All of C's mathematical capabilities are
written for long variable types. Here is a list of the functions which can be expected in the
standard library file. The variables used are all to be declared long

int i; /* long int */


double x,y,result; /* long float */

The functions themselves must be declared long float or double (which might be done
automatically in the mathematics library file, or in a separate file) and any constants must
be written in floating point form: for instance, write 7.0 instead of just 7.

ABS()
MACRO. Returns the unsigned value of the value in parentheses. See fabs() for a
function version.
fabs()
Find the absolute or unsigned value of the value in parentheses:
result = fabs(x);
ceil()
Find out what the ceiling integer is: that is, the integer which is just above the
value in parentheses. This is like rounding up.
i = ceil(x);

65
C Language

/* ceil (2.2) is 3 */

floor()
Find out what the floor integer is: that is, the integer which is just below the
floating point value in parentheses
i = floor(x);

/* floor(2.2) is 2 */

exp()
Find the exponential value.
result = exp(x);
result = exp(2.7);

log()
Find the natural (Naperian) logarithm. The value used in the parentheses must be
unsigned: that is, it must be greater than zero. It does not have to be declared
specifically as unsigned. e.g.
result = log(x);
result = log(2.71828);

log10()
Find the base 10 logarithm. The value used in the parentheses must be unsigned:
that is, it must be greater than zero. It does not have to be declared specifically as
unsigned.
result = log10(x);
result = log10(10000);

pow()
Raise a number to the power.
result = pow(x,y); /*raise x to the power y */
result = pow(x,2); /*find x-squared */

result = pow(2.0,3.2); /* find 2 to the power 3.2 ...*/

sqrt()
Find the square root of a number.
result = sqrt(x);
result = sqrt(2.0);

sin()
Find the sine of the angle in radians.

66
C Language

result = sin(x);
result = sin(3.14);
cos()
Find the cosine of the angle in radians.
result = cos(x);
result = cos(3.14);

tan()
Find the tangent of the angle in radians.
result = tan(x);
result = tan(3.14);

asin()
Find the arcsine or inverse sine of the value which must lie between +1.0 and -1.0.
result = asin(x);
result = asin(1.0);

acos()
Find the arccosine or inverse cosine of the value which must lie between +1.0 and
-1.0.
result = acos(x);
result = acos(1.0);

atan()
Find the arctangent or inverse tangent of the value.
result = atan(x);
result = atan(200.0);

atan2()
This is a special inverse tangent function for calculating the inverse tangent of x
divided by y. This function is set up to find this result more accurately than atan().
result = atan2(x,y);
result = atan2(x/3.14);

sinh()
Find the hyperbolic sine of the value. (Pronounced "shine" or "sinch")
result = sinh(x);
result = sinh(5.0);

cosh()
Find the hyperbolic cosine of the value.

67
C Language

result = cosh(x);
result = cosh(5.0);

tanh()
Find the hyperbolic tangent of the value.
result = tanh(x);
result = tanh(5.0);

Examples
/******************************************************/
/* */
/* Maths functions demo #1 */
/* */
/******************************************************/

/* use sin(x) to work out an animated model */

#include <stdio.h>
#include <math.h>
#include <limits.h>

#define TRUE 1
#define AMPLITUDE 30
#define INC 0.02

double pi; /* this may already be defined */


/* in the math file */

/******************************************************/
/* Level 0 */
/******************************************************/

main () /* The simple pendulum program */

{ pi = asin(1.0)*2; /* if PI is not defined */

printf ("\nTHE SIMPLE PENDULUM:\n\n\n");

Pendulum();
}

/*****************************************************/
/* Level 1 */
/*****************************************************/

68
C Language

Pendulum ()

{ double x, twopi = pi * 2;
int i,position;

while (true)
{
for (x = 0; x < twopi; x += INC)
{
position = (int)(AMPLITUDE * sin(x));

for (i = -AMPLITUDE; i <= AMPLITUDE; i++)


{
if (i == position)
{
putchar('*');
}
else
{
putchar(' ');
}
}
startofline();
}
}
}

/*****************************************************/
/* Toolkit */
/*****************************************************/

startofline()

{
putchar('\r');
}

Maths Errors
Mathematical functions can be delicate animals. There exist mathematical functions
which simply cannot produce sensible answers in all possible cases. Mathematical
functions are not "user friendly"! One example of an unfriendly function is the inverse
sine function asin(x) which only works for values of x in the range +1.0 to -1.0. The reason
for this is a mathematical one: namely that the sine function (of which asin() is the
opposite) only has values in this range. The statement

69
C Language

y = asin (25.3);

is nonsense and it cannot possibly produce a value for y, because none exists. Similarly,
there is no simple number which is the square root of a negative value, so an expression
such as:

x = sqrt(-2.0);

would also be nonsense. This doesn't stop the programmer from writing these statements
though and it doesn't stop a faulty program from straying out of bounds. What happens
then when an erroneous statement is executed? Some sort of error condition would
certainly have to result.

In many languages, errors, like the ones above, are terminal: they cause a program to stop
without any option to recover the damage. In C, as the reader might have come to expect,
this is not the case. It is possible (in principle) to recover from any error, whilst still
maintaining firm control of a program.

Errors like the ones above are called domain errors (the set of values which a function
can accept is called the domain of the function). There are other errors which can occur
too. For example, division by zero is illegal, because dividing by zero is "mathematical
nonsense" - it can be done, but the answer can be all the numbers which exist at the same
time! Obviously a program cannot work with any idea as vague as this. Finally, in
addition to these "pathological" cases, mathematical operations can fail just because the
numbers they deal with get too large for the computer to handle, or too small, as the case
may be.

Domain error
Illegal value put into function
Division by zero
Dividing by zero is nonsense.
Overflow
Number became too large
Underflow
Number became too small.
Loss of accuracy
No meaningful answer could be calculated

Errors are investigated by calling a function called matherr(). The mathematical


functions, listed above, call this function automatically when an error is detected. The
function responds by returning a value which gives information about the error. The exact
details will depend upon a given compiler. For instance a hypothetical example: if the
error could be recovered from, matherr() returns 0, otherwise it returns -1. matherr()

70
C Language

uses a "struct" type variable called an "exception" to diagnose faults in mathematical


functions, See Structures and Unions. This can be examined by programs which trap their
errors dutifully. Information about this structure must be found in a given compiler
manual.

Although it is not possible to generalize, the following remarks about the behaviour of
mathematical functions may help to avoid any surprises about their behaviour in error
conditions.

 A function which fails to produce a sensible answer, for any of the reasons above,
might simply return zero or it might return the maximum value of the computer.
Be careful to check this. (Division by zero and underflow probably return zero,
whereas overflow returns the maximum value which the computer can handle.)
 Some functions return the value NaN. Not a form of Indian unleavened bread, this
stands for `Not a Number', i.e. no sensible result could be calculated.
 Some method of signalling errors must clearly be used. This is the exception
structure (a special kind of C variable) which gives information about the last
error which occurred. Find out what it is and trap errors!

Obviously, wherever possible, the programmer should try to stop errors from occurring in
the first place.

71
C Language

Storage Classes
It specifies the scope of the variables while specifying the data type. It is classified into 4
types. They are
1) Automatic varibles.
2) Static variables.
3) Register variables.
4) External variables.

1) Automatic variables: The value of the automatic variable will have effect only in a
function. It is the default type of storage class. Its initial value is garbage. The keyword is
"auto".
ex: int a,b; (or) auto int a,b;

2) External Variables: The value of the external variable will have effect in the entire
program. These variables should be declared globally. The keyword is "extern" and its
initial value is 0.

3) Static Variables: The value of the static variable will have effect in a function. The
keyword is "static" and its initial value is 0. They should be declared in a function.

4) Register variables: The value of the register variable will have effect through out the
program. The keyword is "register" and its initial value is garbage value. The main
advantage of using register variables is to store the values of the variables in the registers
for faster accessibility.

WAP for the demo on automatic variable


#include<stdio.h>
#include<conio.h>
void main()
{
auto int a; /* int a; */
void display();
clrscr();
printf("\n The Initial value of automatic variable is :%d",a);
a=5;
printf("\n The Specified value of automatic variable is :%d",a);
display();
}
void display()
{
int a;
printf("\n The value of automatic variable in another function is :%d",a);
}

72
C Language

output:
The Initial value of automatic variable: 998
The Specified value of automatic variable: 5
The value of automatic variable in another function: 996

WAP for the demo on register variables


#include<stdio.h>
#include<conio.h>
void main()
{
void disp();
register int a;
clrscr();
printf("\n The Initial value of register variable is :%d",a);
a=5;
printf("\n The Specified value of register variable is :%d",a);
disp();
getch();
}
void disp()
{
register int a;
printf("\n The Specified value of register variable is :%d",a);
}
output:
The Initial value of register variable: 998
The Specified value of register variable: 5
The value of register variable in another function: 5

WAP for the demo on extern variables


#include<stdio.h>
#include<conio.h>
int a;
void main()
{
extern int a;
void display();
clrscr();
printf("\n The Initial value of external variable is :%d",a);
a=5;
printf("\n The Specified value of external variable is :%d",a);
display();
getch();
}
void display()
{

73
C Language

extern int a;
printf("\n The value of external variable in another function is :%d",a);
}

output:
The Initial value of external variable: 0
The Specified value of external variable: 5
The value of external variable in another function: 5

WAP for the demo on static storage class


#include<stdio.h>
#include<conio.h>
void main()
{
static int a;
clrscr();
printf("\n The Initial value of static variable is :%d",a);
a=5;
printf("\n The Specified value of static variable is :%d",a);
display();
getch();
}
void display()
{
static int a;
printf("\n The value of static variable in another function is :%d",a);
}

output:
The Initial value of static variable: 0
The Specified value of static variable: 5
The value of static variable in another function: 0

74
C Language

POINTERS
A pointer is a variable which hold the address of another variable. The pointer variable is
indicated with pointer operator (*).

Declaration of pointer variable:

The pointer variable will be declared using * opeator in the required data type.
Syntax: <data type> *<variable>;
Example: int *p, x;

Here p is called as pointer variable and x is a variable.

Assigning address to pointer variable:

After declaring the pointer variable. The address of another variable should be
specified to the pointer variable.

Syntax: <pointer>=&<variable>
Example: p=&x;
For a pointer variable address operator (&) should not be specified.

Storing value into a pointer variable:


To store a value into the pointer variable pointer operator followed to pointer
variable should be used

Syntax: *<pointer>=<variable>
Example: *p=x;

Pointer arithmetic:

The arithmetical operators or increment and decrement operators will be used for
pointer arithmetic. It is used to change the address of the pointer variable
Ex: p++;

if the address of pointer p is 65536 then the address after pointer arithmetic is 65538 (if
its return type is int)

Displaying the address of pointer variable


To display the address of the pointer variable, the formatted character %u should
be used.
Ex: printf("\n Address is :%u",p);

Pointer to arrays:
A pointer can also point to an arrays, which may be single dimensional array or
double dimensional array.

75
C Language

Pointer to Single dimensional array:


For specifying single dimensional array the pointer will be taken as following
Syntax: *(pointer + value)
example: int *p;

* (p+0) * (p+1) *(p+2) *(p+3) *(p+4)


5 6 7 9 8
65536 65538 65540 65542 65544

pointer to double dimensional array


For specifying double dimensional array the variable should be declared as
double dimensional array and it is taken as following

Syntax: *(*(pointer + row)+column)


example: int *a[2][3];
*(*(a+0)+1)

*(*(a+0)+0) *(*(a+0)+1) *(*(a+0)+2)


4 5 6

7 8 9

*(*(a+1)+0) *(*(a+1)+1) *(*(a+1)+2)

pointer to functions
The address of the variable can be send as an arguments to the functions. In the
function these arguments will be used as a pointer. The main purpose of using this
concept is to make use of an addresses of a variable in other functions. and can change
the values of a variable without using return values.

Instead of sending values as an arguments, the programmer will send the


addresses as an argument.

Pointer to strings
The first address of a string will be used by a pointer and using this reference the
other cells of a string will be located until it founds NULL character. Pointing to next
memory cells will be proceded through pointer arithmetic.

pointer to pointer
A pointer can also point the other pointer variable by using the reference or address of
other pointer variable.
ex: int *p,a,**q;
This concept can be extended to number of pointer but it makes the programmer
confuse.

76
C Language

WAP to swap two numbers using pointer to functions


#include"stdio.h"
#include"conio.h"
void main()
{
int a,b;
void swap(int *,int *);
clrscr();
printf("Enter two values");
scanf("%d%d",&a,&b);
printf("\n Before swapping the values are: %d\t%d",a,b);
swap(&a,&b);
printf("\n After swapping the values are : %d\t%d",a,b);
getch();
}
void swap(int *p,int *q)
{
int t;
t=*p;
*p=*q;
*q=t;
}

WAP to find the length of a string using pointers to functions


#include <stdio.h>
#include <conio.h>
void main()
{
char s[50];
void length(char *);
clrscr();
puts("enter a string");
gets(s);
length(&s);
getch();
}
void length(char *s)
{
int i,l=0;
for(i=0;*s!='\0';i++)
{
l++;s++;
}
printf("The length is:%d",l);
}

77
C Language

WAP to display the address of a pointer variable by passing function as


pointer(pointers to functions)
#include"stdio.h"
#include"conio.h"
void main()
{
int *demo(void);
int *r;
clrscr();
r=demo();
printf("value of the address%u is %d",r,*r);
}
int *demo()
{
int p;
p=10;
return(&p);
}

DYNAMIC MEMORY ALLOCATIONS

It consists of calloc and malloc which are used to allocate the memory. It is used to save
the memory. These are available in the "alloc.h"

calloc(): it is used to allocate the number of bytes for a pointer variable


syntax: (type)calloc(value,sizeof(datatype))
ex: k=(int *)calloc(5,sizeof(int)) 10 bytes of memory

free(): it is used to refresh the memory cells.

malloc: it allocates the memory for the variable


syntax: malloc(size)
ex: malloc(10)

Program for the demo on calloc


#include<stdio.h>
#include<alloc.h>
#include<string.h>
#include<conio.h>
void main()
{
char *str=NULL;
str=(char*)calloc(10,sizeof(char));
clrscr();
strcpy(str,"hello");

78
C Language

printf("string is %s\n",str);
free(str);
}

output: the string is hello

program for the demo on alloc


#include<stdio.h>
#include<alloc.h>
#include<conio.h>
main()
{
void *ptr;
ptr=malloc(4);
clrscr();
if(ptr==NULL)
{
printf("memory is not allocated");
}
else
{
printf("memory is allocated");
}
}

output: Memory is allocated

program for the demo on malloc

#include<stdio.h>
#include<string.h>
#include<alloc.h>
#include<process.h>
#include<conio.h>
main()
{
char *str;
//allocate memory for string
str=(char *)malloc(10);
clrscr();
if(str==NULL)
{
printf("no memory to allocate buffer\n");
exit(1);
}

79
C Language

strcpy(str,"hello");
printf("string is %s\n",str);
free(str);
}

STRUCTURES

The collection of heterogeneous elements is known as structure. It is used to store the


contents of different data type in a single variable.

syntax: struct <structure-name>


{
data type 1: variable(s);
data type 2: variable(s);
- -
data type n: variable(s);
};
ex:
struct stud
{
int sno,age;
char sname[50],course[30];
};
the structure can be created either in the main function or outside the main function. The
variables in a structure is called as fields.

calling a structure in a function: The structure can be called using the reference of
structure name and the complete structure will be stored in a structure variable
syntax: struct <structure-name> <structure-var>;
ex: struct stud s;

accessing fields in a function: Using dot operator the fields in a structure can be called
using the structure variable.
syntax: <structure-var>.field
ex: s.sno;

passing arguments to structures: The arguments can be passed to the structure variable
while calling in the main function.
syntax: <structure-var>{argument(s)};
ex: s{10,20,"ravi","adse"};

80
C Language

structure to arrays: The structure variable can be used as an array type


by specifing the size
ex: struct student s[50];
it can take maximum of 50 student details from 0-49

To access the fields from a structure into the funtion use the following syntax:
syntax: var[value].field
example: s[0].sno;

nested structure: A structure within another structure is known as nested structure. A


structure can be created within another structure or a structure can be called within
another structure. The fields in the derived structure(inside structure) can be called using
the structure variable name of the base structure and derived structure.

pointers to structures: The structure variable can be used as a pointer


variable by using pointer operator and its field will be accessed using
the operator -> or .( )
ex: s->sno;

WAP to accept employee details and display them using structures


#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
struct emp e;
clrscr();
printf("enter employ number");
scanf("%d",&e.eno);
printf("Enter employ name");
scanf("%s",e.ename);
printf("Enter Basic salary");
scanf("%d",&e.basic);

printf("The employ details is \n");


printf("\n employ number :%d",e.eno);
printf("\n employ name :%s",e.ename);
printf("\n Basic salary :%d",e.basic);
getch();
}

81
C Language

WAP to find the sum of two numbers using arguments in a structure


#include"stdio.h"
#include"conio.h"
struct add
{
int a,b,c;
};
void main()
{
struct add x={5,6};
clrscr();
x.c=x.a+x.b;
printf("Sum of the elements :%d",x.c);
getch();
}

WAP to accept number of employee details and search a employ detail(structure to


arrays)
//using structures to arrays
#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
int n,i,k,f=0;
struct emp e[20];
clrscr();
printf("How many Employ Details you want to accept :");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("enter employ number :");
scanf("%d",&e[i].eno);
printf("Enter employ name :");
scanf("%s",e[i].ename);
printf("Enter Basic salary :");
scanf("%d",&e[i].basic);
}
printf("Enter employ number to search :");
scanf("%d",&k);
for(i=0;i<n;i++)

82
C Language

{
if(e[i].eno==k)
{
printf("\n The employ details is \n");
printf("\n employ number :%d",e[i].eno);
printf("\n employ name :%s",e[i].ename);
printf("\n Basic salary :%d",e[i].basic);
f=1;
}
}
if(f==0)
printf("\n Employ Number not found");
getch();
}

WAP for the demo to pass structure variable as an argument (structure to


functions)
#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
struct emp e;
void disp(struct emp e);
clrscr();
printf("enter employ number");
scanf("%d",&e.eno);
printf("Enter employ name");
scanf("%s",e.ename);
printf("Enter Basic salary");
scanf("%d",&e.basic);
disp(e);
getch();
}
void disp(struct emp e)
{
printf("\n\n The employ details is \n");
printf("\n employ number :%d",e.eno);
printf("\n employ name :%s",e.ename);
printf("\n Basic salary :%d",e.basic);
}

83
C Language

WAP for the demo to pass pointer to structure as an argument.


#include <stdio.h>
#include<conio.h>
struct emp
{
int eno,basic;
char ename[20];
};
void main()
{
struct emp *e;
void disp(struct emp *);
clrscr();
printf("enter employ number");
scanf("%d",&e->eno);
printf("Enter employ name");
scanf("%s",e->ename);
printf("Enter Basic salary");
scanf("%d",&e->basic);
disp(e);
getch();
}
void disp(struct emp *e)
{
printf("\n\n The employ details is \n");
printf("\n employ number :%d",e->eno);
printf("\n employ name :%s",e->ename);
printf("\n Basic salary :%d",e->basic);
}

//WAP to create student details using nested structures


#include<stdio.h>
struct date
{
int dd,mm,yy;
};
struct stud
{
int sno;
char sname[10];
int age;
struct date d;
}s;
void main()
{
clrscr();

84
C Language

printf("Enter student number");


scanf("%d",&s.sno);
printf("Enter student name");
scanf("%s",s.sname);
printf("Enter student age");
scanf("%d",&s.age);
printf("Enter student date of birth(dd/mm/yy)");
scanf("%d%d%d",&s.d.dd,&s.d.mm,&s.d.yy);

printf("\n student number:%d",s.sno);


printf("\n student name :%s",s.sname);
printf("\n student age :%d",s.age);
printf("\n Date of birth :%d/%d/%d",s.d.dd,s.d.mm,s.d.yy);

getch();
}
Unions

A union is like a structure in which all the `members' are stored at the same address.
Clearly they cannot all be there at the same time. Only one member can be stored in such
an object at any one time, or it would be overwritten by another. Unions behave like
specially sized storage containers which can hold many different types of data. A union
can hold any one of its members but only at different times. The compiler arranges that a
union type variable is big enough to handle the job.

The real purpose of unions is to prevent memory fragmentation by arranging for a


standard size for data in the memory. By having a standard data size we can guarantee
that any hole left when dynamically allocated memory is freed will always be reusable by
another instance of the same type of union. This is a natural strategy in system
programming where many instances of different kinds of variables with a related purpose
and stored dynamically.

 Declaration of union:
 Using unions:

Declaration

A union is declared in the same way as a structure. It has a list of members, which are
used to mould the type of object concerned.

union IntOrFloat

{
int ordinal;
float continuous;

85
C Language

};

This declares a type template. Variables are then declared as:

union IntOrFloat x,y,z;

At different times the program is to treat x,y and z as being either integers or float types.
When the variables are referred to as

x.ordinal = 1;

the program sees x as being an integer type. At other times (when x is referred to as
x.continuous) it takes on another aspect: its alter ego, the float type. Notice that x by itself
does not have a value: only its members have values, x is just a box for the different
members to share.

Using unions

Unions are coded with the same constructions as structures. The dot . operator selects the
different members for variable and the arrow -> selects different values for pointers. The
form of such statements is:

union_variable.member;

union_pointer->member;

Unions are seldom very useful objects to have in programs, since a program has no
automatic way of knowing what type of member is currently stored in the union type.
One way to overcome this is to keep a variable which signals the type currently held in
the variable. This is done very easily with the aid of enumerated data. Consider the
following kind of union:
union WhichType
{
int ordinal;
float continuous;
char letter;
};

This could be accompanied by an enumerate declaration such as:

enum Types
{

86
C Language

INT,
FLOAT,
CHAR
};

Variables could then go in pairs:

union WhichType x;
enum Types x_status;

which would make union type-handling straightforward:

switch (x_status)
{
case INT : x.ordinal = 12;
break;
case FLOAT : x.continuous = 12.23;
break;
case CHAR : x.letter = '*';
}

These variables could even be grouped into a structure:

struct Union_Handler
{
union WhichType x;
enum Types x_status;
}
var;

which would then require statements such as:

var.x.ordinal = 2;

ptr->x.ordinal = 2;

var.x_status = CHAR;

and so on...

87
C Language

FILES
It is used to store the output data of a file into a data file using files concept.
1) Sequential files
2) Random files

Sequential files
it is used to access the records orderly.

Declaration: To access(store and retrieve) the contents of different data type the pointer
variable should be taken and it is declared using the following syntax
syntax: FILE *pointer;
example: FILE *fp;

Opening a data file: To open a data file in the required mode fopen() should be used
syntax: pointer=fopen("datafile","mode");
example: fp=fopen("rk.dat","w");

closing a file: To close the file fclose() statement should be used.


syntax: fclose(pointer);
example: fclose(fp);

mode to open a file

r - Read mode, to read the contents from a file


w - Write mode, to write the records into a file,It creates a file and store the contents
in that file eventhough the file is existed.
a - Append mode, it is used to add the records in the existed file. If the file does not
exist then it will creates a new file and stores the records in them.
r+ - Open an existing file for update (reading and writing)
w+ - Create a new file for update (reading and writing). If a file by that name already
exists, it will be overwritten.
a+ -Open for append; open for update at the end of the file, or create if the file does
not exist.

88
C Language

file input and output statements


fscanf(): it is used to read the data from an existed data file. It is used for read mode.
syntax: fscanf(pointer,"formatted string",&var1,&var2....);
example: fscanf(fp,"%d%s%d",&sno,name,&fees);

fprintf: it is used to store the data into the data file. It is used for write or append mode.
syntax: fprintf(pointer,"formatted string",var1,var2....);
example: fprintf(fp,"%d%s%d",sno,name,fees);

feof(): file-end-of-file. It returns true when there is no contents in a file


ex: !feof(fp);

EOF: EOF indicated End Of File. The expression will becomes true if end of the file is
reached.

Random access files


fseek(): This function is used to move the file pointer to any specified position in a file.
This function itself cannot do any I/O operations, it moves the pointer forward or
backward in a file
syntax: fseek(fp,n,p);
where p is the position in a file, n is the long integer(returns number of bytes),
if p is 0- beginning of the file, 1- Current position, 2- end of file

ftell(): it returns current position of file pointer as a byte number into a long integer
syntax: n=ftell(fp);

unformatted Input and output functions

input statements
1) fgetc(): it is used read a character from the file.
ex: ch=fgetc(fp);

2) fgets(): it is used to read a string from the file.


ex: fgets(s,n,fp);
where s is a string variable

3) fread(): It is used to read data from the the file and copies it into the structure variable
ex: fread(&e, sizeof(e),1,fp);
where e is a structure variable

output statements
1) fputc(): it is used write a character into the file.
ex: fputc(ch,fp);

2) fputs(): it is used to write a string into the file.

89
C Language

ex: fputs(s,fp);
where s is a string variable

3) fwrite(): It is used to write data into the the file from the structure variable
ex: fread(e, sizeof(e),1,fp);
where e is a structure variable

Detecting errors
ferror(): It is a library function which is used to detect whether the contents is read
successful or not. It returns zero if the data in a file is successful found.
ex: if (ferror(fp)
{
printf("Data is not read successfully");
break;
}

Program to store student details in a file using write mode(sequential file)


#include<stdio.h>
#include<conio.h>
void main()
{
int i,roll;
char name[10];
int n;
FILE *fp;
fp=fopen("d.dat","w");
clrscr();
puts("for how many?");
scanf("%d",&n);
puts("enter student details");
for(i=0;i<n;i++)
{
scanf("%d%s",&roll,name);
fprintf(fp,"%d%5s",roll,name);
fprintf(fp,"\n");
}
fclose(fp);
getch();
}

program to write the data in a given file(sequential file)


# include "stdio.h"
# include "conio.h"
void main()
{
int cno,smr,emr;
char cname[30];

90
C Language

char fname[50];
FILE *fp;
clrscr();
printf("Enter file name");
gets(fname);
fp = fopen(fname,"w");
printf("Enter custno");
scanf("%d",&cno);
fflush(stdin);
while(cno != 0)
{
printf("Enter name : " );
gets(cname);
fflush(stdin);
printf("Enter smr");
scanf("%d",&smr);
fflush(stdin);
printf("Enter emr");
scanf("%d",&emr);
fflush(stdin);
fprintf(fp,"%3d %30s %3d %3d\n",cno,cname,smr,emr);
printf("Enter custno");
scanf("%d",&cno);
fflush(stdin);
}
fclose(fp);
}

program to read the data from a file(sequential file)


# include "stdio.h"
# include "conio.h"
void main()
{
int cno,smr,emr;
char cname[30];
FILE *fp;
clrscr();
fp = fopen("xyz.dat","r");
while(! feof(fp))
{
fscanf(fp,"%d %s %d %d\n",&cno,cname,&smr,&emr);
printf("%d %s %d %d\n",cno,cname,smr,emr);
}
fclose(fp);
getch();
}

91
C Language

WAP to accept student number, student name and age and store it in a file
using append mode(sequential file).
# include "stdio.h"
# include "conio.h"
void main()
{
int sno,age;
char sname[30],ch;
FILE *fp;
clrscr();
fp = fopen("ravi.dat","a");
do
{
printf("Enter Student number :");
scanf("%d",&sno);
fflush(stdin); // refresh the memory
printf("Enter Student name : " );
gets(sname);
printf("Enter age of the student:");
scanf("%d",&age);
fprintf(fp,"%d%s%d",sno,sname,age);
fflush(stdin);
printf("Do u want to continue (y/n):");
scanf("%c",&ch);
}
while(ch=='y' || ch =='Y');
fclose(fp);
getch();
}

WAP to read student number, student name and age from a file(sequential file)
# include "stdio.h"
# include "conio.h"
void main()
{
int sno,age;
char sname[30];
FILE *fp;
clrscr();
fp = fopen("ravi.dat","r");
while(!feof(fp)) //while file end of file is reached
{
fscanf(fp,"%d%s%d",&sno,sname,&age);
printf("\n Student number : %d",sno);
printf("\n Student name : %s",sname);

92
C Language

printf("\n Age of the student: %d",age);


}
fclose(fp);
getch();
}

program for storing data into a file using random files


#include <stdio.h>
#include <conio.h>
struct stud
{
int htno,age;
char name[30];
};
void main()
{
FILE *fp;
struct stud s;
char fname[30];
clrscr();
puts("Enter file name");
fflush(stdin);
gets(fname);
fp=fopen(fname,"w");
while(1)
{
printf("Enter Roll no (0-exit):");
scanf("%d",&s.htno);
if(s.htno==0) break;
printf("Enter Student Name:");
fflush(stdin);
gets(s.name);
printf("Enter Age of the Student:");
scanf("%d",&s.age);
fwrite(&s,sizeof(s),1,fp);
}
fclose(fp);
getch();
}

program for displaying records from a file


#include <stdio.h>
#include <conio.h>
struct stud
{
int htno,age;

93
C Language

char name[30];
};
void main()
{
FILE *fp;
struct stud s;
char fname[30];
clrscr();
puts("Enter file name");
fflush(stdin);
gets(fname);
fp=fopen(fname,"r");
while(fread(&s,sizeof(s),1,fp)==1)
{
printf("%d\t%s\t%d\n",s.htno,s.name,s.age);
}
fclose(fp);
getch();
}

94
C Language

COMMAND LINE ARGUMENTS

Passing arguments to the main function from the command prompt is known as command
line argument
ex: main(int argc[],char *argv[])
argc = argument count is used to count the number of arguments in the command
prompt.
argv = argument variables, to refer an argument in the command prompt
atoi = ascii to integer

c:\>cla 50 60
[0] [1] [2]

WAP to print natural numbers for the given number


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main(int argc,char *argv[])
{
int i;
clrscr();
for(i=0;i<=atoi(argv[1]);i++)
{
printf("%5d",i);
}
getch();
}

program to compare whether the given two strings are equal or not
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc[],char *argv[])
{
int i;
clrscr();
printf("\n %s",argv[1]);
printf("\n %s",argv[2]);
if(strcmp(argv[1],argv[2]) == 0)
printf("\n Both are equal");
else
printf("\n not equal");
getch();
}

program to display the given arguments with position

95
C Language

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
main(int argc,char *argv[])
{
int i;
clrscr();
printf("no of arguments are%d",argc-1);
for(i=1;i<argc;i++)
printf("\narg[%d]=%d",i,atoi(argv[i]));
getch();
}
C-GRAPHICS

gotoxy(): it is used to move the cursor to the required column and row
position
gotoxy(x,y); x=columns,y=rows
gotoxy(50,10);

delay: it is used to specify the speed of the execution of some instructions. Its header file
is #include<dos.h>

delay(milliseconds);
delay(200);

program to move the text from left to right


#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
int i;
clrscr();
for(i=0;i<=70;i++)
{
gotoxy(i,10);printf(" Aptech ");
delay(50);
}
}

#include<graphics.h> is used to support the graphics keywords in the program

cleardevice() : To clear the graphics screen

96
C Language

initgraph() : It is used to initialize the graphics


syntax: initgraph(&graph_drivers,&graph_mode,"path");

graphics_drivers : to use the adapters such as MGA, CGA, EGA, MCGA,


VGA, SVGA, DETECT (get colors)

graphics_mode : To set the number of pixels for filling color or


graphics
text -24*80
graphics-480*640

example: initgraph(&gd,&gm,"c:\\tc\\bgi");

text=24*80 pixel=480*640

sound: It is used to set sound in milliseconds. Its header file is #include<dos.h>. It is


necessary to used nosound() so that the sound can be stopped.

syntax: sound(milliseconds);

settextstyle(): it is used to set the text style, fonts and direction


syntax: settextstyle(font,direction,size);

outtextxy(): it is used to display the string in the specified row and column.
syntax: outtextxy(column,row,"string");
(or)
outtextxy(x,y,"string");

putpixel: it is fill a specified pixel with color


syntax: putpixel(x,y,color);

random: it is used to pick a value automatically basing on the specified final value. its
header file is #include<stdlib.h>
Syntax: random(value);

setfillstyle: it is used to fill the pixel with specified style(0-12).


Syntax: setfillstyle(style,color)

pieslice: it is used to draw a pie


Syntax: pieslice(x,y,sangle,eangle,radius)
sangle-starting angle
eangle-ending angle

circle: it is used to draw a circle in the required location with the specified radius.
Syntax: circle(x,y,radius);

97
C Language

Ex: circle(320,240,10);
(320,240) gives the location of center point of circle.

rectangle: it is used to draw a rectangle


Syntax: rectangle(x,y,x1,y1);
Ex: rectangle(20,20,300,300);
(x,y) - starting position
(x1,y1)-ending position

ellipse: it is used to draw ellipse.


Syntax: ellipse(x,y,sangle,eangle,xradius,yradius)
sangle- starting angle
eangle-ending angle

kbhit(): key board hit. It is used to run the graphics until any key is pressed in
keyboard.
program to move the text from left to right with graphics
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void main()
{
int gd=DETECT,gm=0,i;
clrscr();
initgraph(&gd,&gm,"c:\\tc\\bin");
setbkcolor(RED); //Setting background color
setcolor(WHITE); //Setting foreground color
for(i=0;i<=70;i++)
{
gotoxy(i,10);printf(" Aptech ");
delay(50);
}
}

Program for the demo on graphics


# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0;
initgraph(&gd,&gm,"c:\\tc\\bgi");// path to bgi files
cleardevice();
setbkcolor(BLUE); //setting background color of screen
setcolor(YELLOW); //setting foreground color

98
C Language

printf("\t x = %d",getmaxx());//displaying maximum pixels in x-axis(columns)


printf("\t y = %d",getmaxy());//displaying maximum pixels in y-axis(rows)

line(320,0,320,480); //displaying line(x,y,x1,y1)


line(0,240,640,240);

circle(320,240,10); //circle(x,y,radius)
arc(320,240,0,360,50); //arc(x,y,x1,y1,radius)
arc(320,240,180,360,100);
setfillstyle(6,YELLOW); //text style

pieslice(490,100,90,270,70);
rectangle(50,50,150,80); //rectangle(x,y,x1,y1);
rectangle(220,140,420,340);

setfillstyle(5,GREEN);
bar(500,150,550,200);
setfillstyle(1,BROWN);
bar(500,400,550,450);
bar3d(50,100,100,150,15,1);
bar3d(100,400,150,450,30,1);

getch();
closegraph();
cleardevice();
}
Program for name with different styles
# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0,i,r=20;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
for(i=0;i<=10;i++)
{
settextstyle(i,0,5);
outtextxy(0,r,"Aptech");
r = r + 30;
}
getch();
}

Program for displaying address with different styles


# include "stdio.h"

99
C Language

# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();

settextstyle(7,0,4); outtextxy(0,50,"GRK"); //0- HORIZ_DIR ,1-VERT_DIR


settextstyle(3,0,7);outtextxy(0,75,"19-168");
settextstyle(0,0,6);outtextxy(0,170,"GPT");
settextstyle(1,0,6);outtextxy(0,225,"VSP");
getch();
cleardevice();
closegraph();
}

Program for sound


# include "stdio.h"
# include "dos.h"
# include "conio.h"
void main()
{
int i,j;
clrscr();
printf("\t\t\t pl. wait..");
for(j=0;j<10;j++)
for(i=500;i<3000;i= i + 50)
{
sound(i);
delay(5);
nosound(); // to stop the current frequency
}
}

Program for displaying home


# include "stdio.h"
# include "conio.h"
# include "graphics.h"
void main()
{
int gd,gm;
gm=0;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");

100
C Language

cleardevice();
line(200,200,200,300);
moveto(200,300);
lineto(400,300);
lineto(400,200);
lineto(200,200);
lineto(300,100);
lineto(400,200);
moveto(220,200);
rectangle(220,225,270,300);
moveto(300,200);
rectangle(320,220,350,250);
moveto(330,220);
lineto(330,250);
moveto(340,220);
lineto(340,250);
gotoxy(33,11);
printf("Happy Home");
getch();
}

program to move a ball from left to right


# include "stdio.h"
# include "conio.h"
# include "graphics.h"

void main()
{
int gd,gm,i;
int a[100][100];
gd=gm=0;
gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
setcolor(YELLOW);
setbkcolor(BLUE);
setfillstyle(1,YELLOW);
pieslice(400,100,0,360,30);
getimage(360,60,440,140,a);
cleardevice();
putimage(1,300,a,0);

for(i=1;i<640;i+=2)
{
putimage(i,300,a,0);
putimage(i+2,300,a,0);

101
C Language

}
getch();
closegraph();
cleardevice();
}

Example Programms

1. Write a program to print the total and average marks of a given student?

#include<stdio.h>
#include<conio.h>
void main()
{
int m1,m2,m3,total;
clrscr();
printf("enter three subjects marks");
scanf("%d%d%d",&m1,&m2,&m3);
total=m1+m2+m3;
printf("first subject marks is %d\n",m1);
printf("second subject marks is %d\n",m2);
printf("third subject marks is %d\n",m3);
printf("total marks is %d\n",total);
getch();
}
2. Write a program to print the grade of a student based on some conditions
a. <210 then print fail
b. >=210 and <=250 print d grade
c. >250 and <=300 print c grade
d. >300 and <=350 print c+ grade
e. >350 and <=400 print b- grade
f. >400 and <=450 print b grade
g. >450 and <=500 print b+ grade
h. >500 and <=550 print a- grade
i. >550 and <600 print a grade
Equal to 600 print state first and also print a+ grade

#include<stdio.h>
#include<conio.h>
void main()
{
char *stnm;
int m1,m2,m3,m4,m5,m6,total;
clrscr();
puts("enter any name ");
gets(stnm);

102
C Language

printf("enter six subjects marks");


scanf("%d%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5,&m6);
total=m1+m2+m3+m4+m5+m6;
printf("name of a student is %s \n",stnm);
printf("first subject marks is %d\n",m1);
printf("second subject marks is %d\n",m2);
printf("third subject marks is %d\n",m3);
printf("fourth subject marks is %d\n",m4);
printf("fifth subject marks is %d\n",m5);
printf("sixth subject marks is %d\n",m6);
printf("total marks is %d\n",total);
textcolor(GREEN+BLINK);
if(m1>=35&&m2>=35&&m3>=35&&m4>=35&&m5>=35&&m6>=35)
{
if(total<210)
printf("FAIL");
else if(total>=210 && total<=250)
printf("D GRADE");
else if(total>250 && total<=300)
printf("C GRADE");
else if(total>300 && total<=350)
printf("C+ GRADE");
else if(total>350 && total<=400)
printf("B- GRADE");
else if(total>400 && total<=450)
printf("B GRADE");
else if(total>450 && total<=500)
printf("B+ GRADE");
else if(total>500 && total<=550)
printf("A- GRADE");
else if(total>550 && total<600)
printf("A GRADE");
else if(total==600)
{
gotoxy(27,24);
cprintf("A+ GRADE with STATE FIRST RANKER");
}
}
else
printf("FAIL");
getch();
}
3. Write a program to the season based on the given conditions
a. 4,5,6 summer
b. 7,8,9 rainy
c. 10,11,12 winter

103
C Language

d. 1,2,3 spring

#include<stdio.h>
#include<conio.h>
void main()
{
int month;
clrscr();
printf("enter a month");
scanf("%d",&month);
switch(month)
{
case 4:
case 5:
case 6:printf("SUMMER SEASON");break;
case 7:
case 8:
case 9:printf("RAINY SEASON");break;
case 10:
case 11:
case 12:printf("WINTER SEASON");break;
case 1:
case 2:
case 3:printf("SPRING SEASON");break;
}
getch();
}

4. Write a program to print the cost of the product based on the given conditions
a. If cost is >30000 discount is 20%
b. If cost is <=30000 and >25000 discount is 15%
c. If cost is <=25000 and >20000 discount is 10%
d. If cost is <=20000 and >15000 discount is 5%
e. If cost is <15000 discount is 2%

#include<stdio.h>
#include<conio.h>
void main()
{
char *pnm;
float cost,disc,totamt;
clrscr();
puts("enter the product name ");
gets(pnm);
printf("enter the actual price");
scanf("%f",&cost);

104
C Language

if(cost>30000)
disc=cost*20/100;
else if(cost<=30000 && cost>25000)
disc=cost*15/100;
else if(cost<=25000 && cost>20000)
disc=cost*10/100;
else if(cost<=20000 && cost>15000)
disc=cost*5/100;
else
disc=cost*2/100;
totamt=cost-disc;
clrscr();
printf("the product name is %s\n",pnm);
printf("actual amount to pay is %f",totamt);
getch();
}

5. Write a program to print the net salary of a given person based on given
conditions
a. If salary is <10000 no hra, ta, da, pf, it
b. If salary is >=10000 and <15000 hra=5% , da=2% , ta=3% , pf=8% , it=5%
c. If salary is >=15000 and <20000 hra=9% , da=3% , ta=5% , pf=6% ,it=6%
d. If salary is >=20000 and <25000 hra=12%, da=9% , ta=7% , pf=6% ,it=7%
e. If salary is >=25000 and <30000 hra=2% , da=9% , ta=7% , pf=6% ,it=9%
f. If salary is >30000 hra=3% , da=2% , ta=4% , pf=7% ,it=10%
i. Net salary=hra+da+ta+pf-it

#include<stdio.h>
#include<conio.h>
void main()
{
char *enm;
float basic,hra=0,ta=0,da=0,pf=0,it=0,netsalary;
clrscr();
puts("enter an employee name ");
gets(enm);
printf("enter the basic salary");
scanf("%f",&basic);
if(basic>=10000 && basic<15000)
{
hra=basic*5/100;
da=basic*2/100;
ta=basic*3/100;
pf=basic*8/100;
it=basic*5/100;

105
C Language

}
else if(basic>=15000 && basic<20000)
{
hra=basic*9/100;
da=basic*3/100;
ta=basic*5/100;
pf=basic*6/100;
it=basic*6/100;
}
else if(basic>=20000 && basic<25000)
{
hra=basic*12/100;
da=basic*9/100;
ta=basic*7/100;
pf=basic*6/100;
it=basic*7/100;
}
else if(basic>=25000 && basic<30000)
{
hra=basic*2/100;
da=basic*9/100;
ta=basic*7/100;
pf=basic*6/100;
it=basic*9/100;
}
else if(basic>30000)
{
hra=basic*3/100;
da=basic*2/100;
ta=basic*4/100;
pf=basic*7/100;
it=basic*10/100;
}
netsalary=basic+hra+da+ta+pf-it;
printf("employee name is %s\n",enm);
printf("basic , hra , da , ta , pf , it are %.2f , %.2f , %.2f , %.2f , %.2f ,
%.2f\n",basic,hra,da,ta,pf,it);
printf("net salary is %f",netsalary);
getch();
}

6. Write a program to print 5 students’ details using simple printf statements?

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

106
C Language

{
clrscr();
printf("STUDENTNAME NUMBER TELUGU ENGLISH \n");
printf("___________ ______ ______ ________\n\n");
printf(" Murthy 101 89 97\n");
printf(" Chaitanya 102 79 86\n");
printf(" Sharma 103 87 98\n");
printf(" Jyothi 104 89 93\n");
printf("Pravallika 105 96 95\n");
getch();
}

7. Write a program to print the area of triangle?

#include<stdio.h>
#include<conio.h>
void main()
{
float b,h,area;
clrscr();
printf("enter breadth and height");
scanf("%f%f",&b,&h);
area=(b*h)/2;
printf("area of triangle is %f ",area);
getch();
}

8. Write a program to print the area of circle?

#include<stdio.h>
#include<conio.h>
void main()
{
float area,r;
clrscr();
printf("enter radius of the circle ");
scanf("%f",&r);
area=3.145*r*r;
printf("area of circle is %f",area);
getch();
}

9. Write a program to print the area of rectangle?

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

107
C Language

void main()
{
float l,b,area;
clrscr();
printf("enter length and breadth");
scanf("%f%f",&l,&b);
area=l*b;
printf("area of rectangle is %f",area);
getch();
}

10. Write a program to print the area of square?

#include<stdio.h>
#include<conio.h>
void main()
{
float a,area;
clrscr();
printf("enter a value");
scanf("%f",&a);
area=a*a;
printf("area of square is %f",area);
getch();
}

11. Write a program to print the area of ellipse?

#include<stdio.h>
#include<conio.h>
#define pi 3.145
void main()
{
float a,b,area;
clrscr();
printf("enter values to a,b ");
scanf("%f%f",&a,&b);
area=pi*a*b;
printf("area of ellipse is %f ",area);
getch();
}

12. Write a program to print the area of rhombus?

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

108
C Language

#include<math.h>
void main()
{
float a,l,area;
clrscr();
printf("enter values to a,l ");
scanf("%f%f",&a,&l);
area=a*a*sin(l);
printf("area of rhombus is %f ",area);
getch();
}
13. Write a program to print the area of cube?
#include<stdio.h>
#include<conio.h>
void main()
{
float a,area;
clrscr();
printf("enter values to a ");
scanf("%f",&a);
area=6*a*a;
printf("area of cube is %f ",area);
getch();
}

14. Write a program to print the area of parallelogram?


#include<stdio.h>
#include<conio.h>
void main()
{
float b,h,area;
clrscr();
printf("enter values to b,h ");
scanf("%f%f",&b,&h);
area=b*h;
printf("area of parallelogram is %f ",area);
getch();
}

15. Write a program to print the area of trapezoid?


#include<stdio.h>
#include<conio.h>
void main()
{
float b1,b2,h,area;
clrscr();

109
C Language

printf("enter values to h,b1,b2 ");


scanf("%f%f%f",&h,&b1,&b2);
area=(h*(b1+b2))/2;
printf("area of trapezoid is %f ",area);
getch();
}
16. Write a program to print the area of regular polygon?
#include<stdio.h>
#include<conio.h>
void main()
{
float n,a,area;
clrscr();
printf("enter values to n,a ");
scanf("%f%f",&n,&a);
area=(n*(a*a)*sin(360/n))/2;
printf("area of regular polygon is %f ",area);
getch();
}

17. Write a program to print the area of equilateral triangle?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,area;
clrscr();
printf("enter values to a ");
scanf("%f",&a);
area=(sqrt(3)*(a*a))/4;
printf("area of equilateral triangle is %f ",area);
getch();
}

18. Write a program to print the perimeter of rectangle?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,area;
clrscr();
printf("enter values to a,b ");
scanf("%f%f",&a,&b);
area=((2*a)+(2*b));
printf("perimeter of rectangle is %f ",area);
getch();

110
C Language

19. Write a program to print the perimeter of triangle?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,peri;
clrscr();
printf("enter values to a,b,c ");
scanf("%f%f%f",&a,&b,&c);
peri=a+b+c;
printf("perimeter of triangle is %f ",peri);
getch();
}

20. Write a program to print the perimeter of rhombus?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,peri;
clrscr();
printf("enter values to a ");
scanf("%f",&a);
peri=4*a;
printf("perimeter of rhombus is %f ",peri);
getch();
}

21. Write a program to print the perimeter of ellipse?


#include<stdio.h>
#include<conio.h>
#include<math.h>
#define pi 3.145
void main()
{
float a,b,peri;
clrscr();
printf("enter values to a,b ");
scanf("%f%f",&a,&b);
peri=2*pi*sqrt(((a*a)+(b*b))/2);
printf("perimeter of ellipse is %f ",peri);
getch();
}

111
C Language

22. Write a program to print the perimeter of parallelogram?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,peri;
clrscr();
printf("enter values to a,b ");
scanf("%f%f",&a,&b);
peri=(2*a)+(2*b);
printf("perimeter of parallelogram is %f ",peri);
getch();
}

23. Write a program to print the perimeter of trapezoid?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,d,peri;
clrscr();
printf("enter values to a,b,c,d ");
scanf("%f%f%f%f",&a,&b,&c,&d);
peri=a+b+c+d;
printf("perimeter of trapezoid is %f ",peri);
getch();
}

24. Write a program to print the perimeter of regular n-gon?


#include<stdio.h>
#include<conio.h>
void main()
{
float n,s,peri;
clrscr();
printf("enter values to n,s ");
scanf("%f%f",&n,&s);
peri=n*s;
printf("perimeter of regular N-Gon is %f ",peri);
getch();
}
25. Write a program to print the perimeter of the square?
#include<stdio.h>
#include<conio.h>
void main()
{

112
C Language

float a,area;
clrscr();
printf("enter values to a ");
scanf("%f",&a);
area=4*a;
printf("perimeter of square is %f ",area);
getch();
}

26. Write a program to print the perimeter of the circle?


#include<stdio.h>
#include<conio.h>
#define pi 3.145
void main()
{
float r,peri;
clrscr();
printf("enter values to r ");
scanf("%f",&r);
peri=2*pi*r;
printf("perimeter of Circle is %f ",peri);
getch();
}

27. Write a program to print the volume of sphere?


#include<stdio.h>
#include<conio.h>
#define pi 3.145
void main()
{
float r,peri;
clrscr();
printf("enter values to r ");
scanf("%f",&r);
peri=(4*pi*(r*r*r))/3;
printf("volume of sphere is %f ",peri);
getch();
}

28. Write a program to print the volume of cube?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,vol;
clrscr();

113
C Language

printf("enter values to a ");


scanf("%f",&a);
vol=a*a*a;
printf("volume of cube is %f ",vol);
getch();
}
29. Write a program to print the volume of cuboids?
#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,vol;
clrscr();
printf("enter values to a,b,c ");
scanf("%f%f%f",&a,&b,&c);
vol=a*b*c;
printf("volume of cuboid is %f ",vol);
getch();
}

30. Write a program to print the volume of rectangular prism?


#include<stdio.h>
#include<conio.h>
void main()
{
float a,b,c,vol;
clrscr();
printf("enter values to a,b,c ");
scanf("%f%f%f",&a,&b,&c);
vol=a*b*c;
printf("volume of rectangular prism is %f ",vol);
getch();
}

31. Write a program to print the volume of cone?


#include<stdio.h>
#include<conio.h>
#define pi 3.145
void main()
{
float r,h,vol;
clrscr();
printf("enter values to r,h ");
scanf("%f%f",&r,&h);
vol=(pi*(r*r)*h)/3;
printf("volume of cone is %f ",vol);

114
C Language

getch();
}

32. Write a program to print the volume of cylinder?


#include<stdio.h>
#include<conio.h>
#define pi 3.145
void main()
{
float r,h,vol;
clrscr();
printf("enter values to r,h ");
scanf("%f%f",&r,&h);
vol=(pi*(r*r)*h);
printf("volume of cylinder is %f ",vol);
getch();
}

33. Write a program to print ASCII codes for each and every alphabets both in the
case of upper and lower.

#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf("ASCII codes to A to Z \n ");
for(a='A';a<='Z';a++)
printf("%d ",a);
printf("\n\nASCII codes to a to z \n ");
for(a='a';a<='z';a++)
printf("%d ",a);
getch();
}

34. Write a program to print ASCII codes for each and every digit in the decimal
system
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf("ASCII codes to 1 to 9 \n ");
for(a='0';a<='9';a++)

115
C Language

printf("%d ",a);
getch();
}

35. Write a program to print the given number in binary digit format?

#include<stdio.h>
#include<conio.h>
void main()
{
int n,a[10],i;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
i=0;
while(n>0)
{
a[i]=n%2;
i++;
n=n/2;
}
printf("given decimal number in binary digit format is ");
for(i=i-1;i>=0;i--)
printf("%d ",a[i]);
getch();
}

36. Write a program to print the given binary digit number in decimal digit format?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,dec=0,k,j;
clrscr();
printf("enter binary number");
scanf("%d",&n);
j=0;
while(n>0)
{
k=n%10;
dec+=(k*pow(2,j));
j++;
n=n/10;
}
printf("the decimal number is %d ",dec);

116
C Language

getch();
}

37. Write a program to print the given number in octal format?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,oct,a[10],i=0;
clrscr();
printf("enter a decimal number ");
scanf("%d",&n);
while(n>0)
{
a[i]=n%8;
i++;
n=n/8;
}
printf("given decimal number in octal format is ");
for(i=i-1;i>=0;i--)
printf("%d ",a[i]);
getch();
}

38. Write a program to print the given octal number in decimal format?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,dec=0,k,j;
clrscr();
printf("enter an octal number");
scanf("%d",&n);
j=0;
while(n>0)
{
k=n%10;
dec+=(k*pow(8,j));
j++;
n=n/10;
}
printf("the decimal number is %d ",dec);
getch();
}

117
C Language

39. Write a program to print the given octal number in binary format?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,dec=0,k,j,a[10];
clrscr();
printf("enter an octal number");
scanf("%d",&n);
j=0;
while(n>0)
{
k=n%10;
dec+=(k*pow(8,j));
j++;
n=n/10;
}
j=0;
while(dec>0)
{
a[j]=dec%2;
j++;
dec=dec/2;
}
printf("given octal number in binary format is ");
for(j=j-1;j>=0;j--)
printf("%d ",a[j]);
getch();
}

40. Write a program to print whether a given number is even (or) odd?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
if(n%2==0)
printf("given number is even ");
else

118
C Language

printf("given number is odd ");


getch();
}

41. Write a program to print whether a given number is positive (or) negative?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
if(n>0)
printf("given number is positive ");
else
if(n<0)
printf("given number is negative ");
else
printf("given number is equals to zero");
getch();
}

42. Write a program to print the multiplication table of given number?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
printf("multiplication table for %d is \n\n",n);
for(i=1;i<=20;i++)
printf("%d * %d = %d \n",n,i,n*i);
getch();
}

43. Write a program to print the biggest among twenty numbers without using twenty
variables and also arrays?

#include<stdio.h>

119
C Language

#include<conio.h>
#include<math.h>
void main()
{
int n,big,i;
clrscr();
printf("enter twenty numbers ");
scanf("%d",&n);
big=n;
for(i=1;i<20;i++)
{
scanf("%d",&n);
if(n>big)
big=n;
}
printf("biggest number among twenty is %d ",big);
getch();
}

44. Write a program to print whether a given number is palindrome (or) not?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,m,k,rev=0;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
m=n;
while(n>0)
{
k=n%10;
rev=rev*10+k;
n=n/10;
}
if(rev==m)
printf("given number is palindrome");
else
printf("given number is not a palindrome");
getch();
}

45. Write a program to print whether a given number is Armstrong (or) not?

120
C Language

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,m,k,sum=0;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
m=n;
while(n>0)
{
k=n%10;
sum=sum+(k*k*k);
n=n/10;
}
if(sum==m)
printf("given number is an armstrong");
else
printf("given number is not an armstrong");
getch();
}

46. Write a program to print whether a given number is perfect (or) not?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,i;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
for(i=1;i<n;i++)
if(n%i==0)
sum+=i;
if(sum==n)
printf("given number is perfect");
else
printf("given number is not a perfect");
getch();
}

47. Write a program to print whether a given number is strong (or) not?
#include<stdio.h>

121
C Language

#include<conio.h>
#include<math.h>
void main()
{
int n,m,k,sum=0,f;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
m=n;
while(n>0)
{
k=n%10;
f=1;
while(k>0)
{
f=f*k;
k--;
}
sum+=f;
n=n/10;
}
if(sum==m)
printf("given number is a strong");
else
printf("given number is not a strong");
getch();
}

48. Write a program to print whether a given number is prime (or) not?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,count=0,i;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
for(i=2;i<n;i++)
if(n%i==0)
count++;
if(count==0)
printf("given number is a prime");
else
printf("given number is not a prime");

122
C Language

getch();
}

49. Write a program to print whether a given number is unique (or) not?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,m,rev=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
m=n*9;
while(n>0)
{
k=n%10;
rev=rev*10+k;
n=n/10;
}
if(rev==m)
printf("given number is an unique");
else
printf("given number is not an unique");
getch();
}

50. Write a program to print the reverse of the given number?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,rev=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
rev=rev*10+k;
n=n/10;
}
printf("reverse of the given number is %d",rev);
getch();

123
C Language

51. Write a program to print the sum of digits of the given number?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
sum=sum+k;
n=n/10;
}
printf("sum of digits of the given number is %d",sum);
getch();
}

52. Write a program to print the number of digits of the given number?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
sum=sum+1;
n=n/10;
}
printf("count of digits of the given number is %d",sum);
getch();
}

53. Write a program to print the number of even digits in a given number?

124
C Language

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
if(k%2==0)
sum++;
n=n/10;
}
printf("number of even digits of the given number is %d",sum);
getch();
}

54. Write a program to print the number of odd digits in a given number?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
if(k%2!=0)
sum++;
n=n/10;
}
printf("number of odd digits of the given number is %d",sum);
getch();
}

55. Write a program to print the sum of squares of digits in a given number?

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

125
C Language

#include<math.h>
void main()
{
int n,sum=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
sum=sum+(k*k);
n=n/10;
}
printf("sum of squares of digits of the given number is %d",sum)
;
getch();
}

56. Write a program to print the sum of factorials of digits in a given number?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,k,f;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
f=1;
while(k>0)
{
f=f*k;
k--;
}
sum=sum+f;
n=n/10;
}
printf("sum of factorials of digits of the given number is %d",sum)
;
getch();
}

57. Write a program to print the sum of cubes of digits in a given number?

126
C Language

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
sum=sum+(k*k*k);
n=n/10;
}
printf("sum of cubes of digits of the given number is %d",sum)
;
getch();
}

58. Write a program to print the sum of odd places digits and sum of even places
digits in a given odd digited number?
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],k,sum=0,l,i,count=0,n;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
i=0;
while(n>0)
{
k=n%10;
a[i]=k;
i++;
n=n/10;
}
l=i-1;
for(i=0;i<=l;i++)
if(i%2==0)
sum=sum+a[i];
else
count=count+a[i];
printf("sum of odd places digits in a given odd digited number is %d \n",sum);

127
C Language

printf("sum of even places digits in a given odd digited number is %d ",count);


getch();
}

59. Write a program to print the sum of even places digits and sum of odd places
digits in a given even digited number?
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],k,sum=0,l,i,count=0,n;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
i=0;
while(n>0)
{
k=n%10;
a[i]=k;
i++;
n=n/10;
}
l=i-1;
for(i=0;i<=l;i++)
if(i%2!=0)
sum=sum+a[i];
else
count=count+a[i];
printf("sum of odd places digits in a given even digited number is %d \n",sum);
printf("sum of even places digits in a given even digited number is %d ",count);
getch();
}

60. Write a program to print whether a given digit is found in a number?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,s,f=0,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
printf("enter any search digit");
scanf("%d",&s);
while(n>0)

128
C Language

{
k=n%10;
if(k==s)
f=1;
n=n/10;
}
if(f==1)
printf("given digit found");
else
printf("given digit not found");
getch();
}

61. Write a program to print the factors for each digit in a given number?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i,k;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
while(n>0)
{
k=n%10;
printf("factors for digit %d is ",k);
for(i=1;i<=k;i++)
if(k%i==0)
printf("%d ",i);
printf("\n");
n=n/10;
}
getch();
}

62. Write a program to print the count of factors for each digit in a given number?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i,k,count;
clrscr();
printf("enter any number to n ");

129
C Language

scanf("%d",&n);
while(n>0)
{
k=n%10;
count=0;
printf("count of factors for digit %d is ",k);
for(i=1;i<=k;i++)
if(k%i==0)
count++;
printf("%d\n",count);
n=n/10;
}
getch();
}

63. Write a program to print the febonacci series?

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,a,b,sum=0;
clrscr();
printf("enter maximum value to stop the series ");
scanf("%d",&n);
printf("febonacci series upto %d numbers\n",n);
for(a=0,b=1;a<=n;)
{
sum=0;
printf("%d ",a);
sum=a+b;
a=b;
b=sum;
}
getch();
}

64. Write a program to print the rumour series?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i,j,sum,s=0;
clrscr();

130
C Language

printf("enter number of persons");


scanf("%d",&n);
printf("enter number of cycles");
scanf("%d",&j);
for(i=0;i<=j;i++)
{
sum=0;
sum+=pow(n,i);
printf("%d + ",sum);
s+=sum;
}
printf("\b : ");
printf("\nthe result is %d ",s);
getch();
}
65. Write a program to count the number of occurrences of a given digit in a given
number?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,s,occ=0,k;
clrscr();
printf("enter any number ");
scanf("%d",&n);
printf("enter search digit");
scanf("%d",&s);
while(n>0)
{
k=n%10;
if(k==s)
occ++;
n=n/10;
}
if(occ==0)
printf("the given digit not found in a given number ");
else
printf("number of occurences of the given number is %d",occ);
getch();
}

66. Write a program to print the perfect numbers between 1 to n?

#include<stdio.h>

131
C Language

#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,i,j;
clrscr();
printf("enter end of perfect numbers ");
scanf("%d",&n);
printf("perfect numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
sum=0;
for(j=1;j<i;j++)
if(i%j==0)
sum+=j;
if(sum==i)
printf("%d ",i);
}
getch();
}

67. Write a program to print the palindrome numbers between 1 to n?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,i,k,m;
clrscr();
printf("enter end of palindrome numbers ");
scanf("%d",&n);
printf("palindrome numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
m=i;
sum=0;
while(m>0)
{
k=m%10;
sum=sum*10+k;
m=m/10;
}
if(i==sum)
printf("%d ",i);
}
getch();

132
C Language

68. Write a program to print the Armstrong numbers between 1 to n?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,i,k,m;
clrscr();
printf("enter end of armstrong numbers ");
scanf("%d",&n);
printf("armstrong numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
m=i;
sum=0;
while(m>0)
{
k=m%10;
sum=sum+(k*k*k);
m=m/10;
}
if(i==sum)
printf("%d ",i);
}
getch();
}

69. Write a program to print the strong numbers between 1 to n?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,i,k,m,f;
clrscr();
printf("enter end of strong numbers ");
scanf("%d",&n);
printf("strong numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
m=i;
sum=0;
while(m>0)
{

133
C Language

f=1;
k=m%10;
while(k>0)
{
f=f*k;
k--;
}
sum=sum+f;
m=m/10;
}
if(i==sum)
printf("%d ",i);
}
getch();
}

70. Write a program to print the unique numbers between 1 to n?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,sum=0,i,k,m;
clrscr();
printf("enter end of unique numbers ");
scanf("%d",&n);
printf("unique numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
m=i;
sum=0;
while(m>0)
{
k=m%10;
sum=sum*10+k;
m=m/10;
}
if(i*9==sum)
printf("%d ",i);
}
getch();
}

71. Write a program to print the prime numbers between 1 to n?


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

134
C Language

#include<math.h>
void main()
{
int n,i,j,sum=0;
clrscr();
printf("enter end of prime numbers ");
scanf("%d",&n);
printf("prime numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
sum=0;
for(j=2;j<i;j++)
if(i%j==0)
sum++;
if(sum==0)
printf("%d ",i);
}
getch();
}

72. Write a program to print the even numbers between 1 to n?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i;
clrscr();
printf("enter end of even numbers ");
scanf("%d",&n);
printf("even numbers upto %d are ",n);
for(i=1;i<=n;i++)
{
if(i%2==0)
printf("%d ",i);
}
getch();
}

73. Write a program to print the multiplication tables between 1 to n?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i,j;

135
C Language

clrscr();
printf("enter end of multiplication tables ");
scanf("%d",&n);
printf("multiplication tables upto %d are ",n);
for(i=1;i<=n;i++)
{
clrscr();
for(j=1;j<=20;j++)
printf("%d * %d = %d \n",i,j,i*j);
getch();
}
getch();
}

74. Write a program to print the following series


a. 1 11 21 31 41 51
2 12 22 32 42 52
3 13 23 33 43 53
4 14 24 34 44 54
5 15 25 35 45 55
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=i;j<=55;j+=10)
printf("%d ",j);
printf("\n");
}
getch();
}

75. Write a program to execute following series


a. *
**
***
****
*****
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()

136
C Language

{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("* ");
printf("\n");
}
getch();
}

76. Write a program to execute the following series


a.
*****
****
***
**
*
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
printf("* ");
printf("\n");
}
getch();
}

77. Write a program to execute the following series


a. 1
12
123
1234
12345
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{

137
C Language

int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
getch();
}

78. Write a program to execute the following series

a. 12345
1234
123
12
1
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
getch();
}

79. Write a program to execute the following series


a. 55555
4444
333
22
1
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{

138
C Language

int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
printf("%d ",i);
printf("\n");
}
getch();
}

80. Write a program to execute the following series


a. 11111
2222
333
44
5
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
printf("%d ",i);
printf("\n");
}
getch();
}

81. a program to execute the following series


a. 12345
2345
345
45
5
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
clrscr();

139
C Language

for(i=1;i<=5;i++)
{
for(j=1;j<i;j++)
printf(" ");
for(j=i;j<=5;j++)
printf("%d ",j);
printf("\n");
}
getch();
}

82. Write a program to execute the following series


a. 54321
4321
321
21
1
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=5;j>i;j--)
printf(" ");
for(j=i;j>=1;j--)
printf("%d ",j);
printf("\n");
}
getch();
}

83. Write a program to execute the following series


a. 1
21
321
4321
54321

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

140
C Language

{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
printf(" ");
for(j=i;j>=1;j--)
printf("%d ",j);
printf("\n");
}
getch();
}

84. Write a program to execute the following series


a. 1
12
123
1234
12345

#include<conio.h>
#include<stdio.h>
void main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=5;j>i;j--)
printf(" ");
for(j=1;j<=i;j++)
printf("%d ",j);
printf("\n");
}
getch();
}

85. W rite a program to execute the following series


a. 12345
234
3
#include<conio.h>
#include<stdio.h>
void main()

141
C Language

{
int i,j,k=5;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<i;j++)
printf(" ");
for(j=i;j<=k;j++)
printf("%d ",j);
k--;
printf("\n");
}
getch();
}

86. Write a program to execute the following series


a. 1 2 3 4 5 6 7 8 9 10
23456789
345678
4567
56
5
#include<conio.h>
#include<stdio.h>
void main()
{
int i,j,k=10;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<i;j++)
printf(" ");
for(j=i;j<=k;j++)
printf("%d ",j);
k--;
printf("\n");
}
getch();
}

87. Write a program to execute the following series


a. * * * * *
* * * *
* * *
* *
*

142
C Language

#include<conio.h>
#include<stdio.h>
void main()
{
int i,j;
clrscr();
for(i=5;i>=1;i--)
{
for(j=5;j>i;j--)
printf(" ");
for(j=1;j<=i;j++)
printf("* ");
printf("\n");
}
getch();
}

88. Write a program to delete an element from an already existed array?


#include<conio.h>
#include<stdio.h>
void main()
{
int a[10],i;
clrscr();
printf("enter any 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("the given array of elements are \n");
for(i=0;i<10;i++)
printf("%d ",a[i]);
getch();
}

89. Write a program to print the sum of the array elements?


#include<conio.h>
#include<stdio.h>
void main()
{
int a[10],i,sum=0;
clrscr();
printf("enter any 10 array elements ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
sum+=a[i];

143
C Language

}
printf("the given array of elements are \n");
for(i=0;i<10;i++)
printf("%d ",a[i]);
printf("\nthe sum of array elements is %d ",sum);
getch();
}

90. Write a program to print whether a given number is found in an array (or) not?
#include<conio.h>
#include<stdio.h>
void main()
{
int a[10],i,s;
clrscr();
printf("enter any 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("enter any search element ");
scanf("%d",&s);
for(i=0;i<10;i++)
if(a[i]==s)
{
printf("given search number found at %d location",i+1);
getch();
exit(0);
}
printf("given search number was not found ");
getch();
}

91. Write a program to print the sum of even numbers in a given array?

#include<conio.h>
#include<stdio.h>
void main()
{
int a[10],i,sum=0;
clrscr();
printf("enter any 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
if(a[i]%2==0)
sum+=a[i];
printf("sum of even numbers in an array is %d ",sum);

144
C Language

getch();
}

92. Write a program to print the sum of odd numbers in a given array?

#include<conio.h>
#include<stdio.h>
void main()
{
int a[10],i,sum=0;
clrscr();
printf("enter any 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10;i++)
if(a[i]%2!=0)
sum+=a[i];
printf("sum of odd numbers in an array is %d ",sum);
getch();
}

93. write a program to insert an element into an already existed array?

#include<stdio.h>
#include<conio.h>
void main()
{
int k[6];
int loc,s,i;
clrscr();
for(i=0;i<5;i++)
{
printf("enter k[%d] values ",i);
scanf("%d",&k[i]);
}
printf("enter element to be inserted ");
scanf("%d",&s);
printf("enter location");
scanf("%d",&loc);
for(i=5;i>=loc;i--)
k[i]=k[i-1];
k[i]=s;
printf("After insertion \n");
for(i=0;i<6;i++)
printf("%d ",k[i]);

145
C Language

getch();
}

94. write a program to delete an element from an existed array?

#include<stdio.h>
#include<conio.h>
void main()
{
int k[6];
int loc,i;
clrscr();
for(i=0;i<6;i++)
{
printf("enter k[%d] values ",i);
scanf("%d",&k[i]);
}
printf("enter location");
scanf("%d",&loc);
for(i=loc-1;i<6;i++)
k[i]=k[i+1];
printf("After deletion \n");
for(i=0;i<5;i++)
printf("%d ",k[i]);
getch();
}

95. Write a program to read the squares of each number in an array into another
array?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[10],b[10],i;
clrscr();
printf("enter ten array elements ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
b[i]=a[i]*a[i];
}
printf("squares array elements are \n");
for(i=0;i<10;i++)
printf("%d * %d = %d \n",a[i],a[i],b[i]);
getch();

146
C Language

96. Write a program to print the sum of odd placed numbers in a given array?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[10],i,sum=0;
clrscr();
printf("enter ten array elements ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
if(i%2==0)
sum+=a[i];
printf("sum of odd places in an array is %d ",sum);
getch();
}

97. Write a program to print the sum of even placed numbers in a given array?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[10],i,sum=0;
clrscr();
printf("enter ten array elements ");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
if(i%2!=0)
sum+=a[i];
printf("sum of even places in an array is %d ",sum);
getch();
}

98. write a program to deleting duplicates in an array?

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

147
C Language

void main()
{
int i,j,k,n,num,flag=0;
float a[50];
clrscr();
printf("Size of array ? ");
scanf("%d",&n);
printf("%d\n",n);
num=n;
printf("\n|Vector elements ? \n");
for(i=0;i<n;i++)
scanf("%f",&a[i]);
for(i=0;i<n;i++)
printf("%6.2f",a[i]);
printf("\n");
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
n=n-1;
for(k=j;k<n;k++)
a[k]=a[k+1];
flag=1;
j=j-1;
}
}
if(flag==0)
printf("\n No duplicates found in vector\n");
else
{
printf("\nVector has %d duplicates \n\n",num-n);
printf("Vector after deleting duplicates : \n");
for(i=0;i<n;i++)
printf("%6.2f",a[i]);
printf("\n");
}
getch();
}

99. Write a program to read and print the array elements in the matrix form?
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{

148
C Language

int a[3][3],i,j;
clrscr();
printf("enter 9 elements ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("elements in a matrix form is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",a[i][j]);
printf("\n");
}
getch();
}

100. Write a program to find the diagonals sum in a 3x3 matrix?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[3][3],i,j,sum=0;
clrscr();
printf("enter 9 elements ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("elements in a matrix form is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d ",a[i][j]);
if(i==j)
sum+=a[i][j];
}
printf("\n");
}
printf("\n diagonals sum is %d ",sum);
getch();
}

101. Write a program to print the transpose of a given matrix?


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

149
C Language

#include<math.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("enter 9 elements ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("transpose of a given matrix is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",a[j][i]);
printf("\n");
}
getch();
}

102. write a program to print the matrix addition?

#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf("enter first 3x3 matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("enter second 3x3 matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
printf("sum of two matrices are \n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",c[i][j]);
printf("\n");
}

150
C Language

getch();
}

103. Write a program to print the lower triangle in a given matrix?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("enter 9 elements ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("transpose of a given matrix is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
if(i>=j)
printf("%d ",a[i][j]);
printf("\n");
}
getch();
}

104. Write a program to print the upper triangle in a given matrix?


#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("enter 9 elements ");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("transpose of a given matrix is \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i>j)
printf(" ");
if(i<=j)

151
C Language

printf("%d ",a[i][j]);
}
printf("\n");
}
getch();
}

105. Write a program to print the sum of the corresponding rows and columns?

#include<stdio.h>
#include<conio.h>
void main()
{
int a[4][4];
int i,j,csum=0,rsum=0;
clrscr();
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{

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


scanf("%d",&a[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
printf("\n");
for(i=0;i<3;i++)
{
csum=0;
rsum=0;
for(j=0;j<3;j++)
{
csum+=a[i][j];
rsum+=a[j][i];
}
a[i][j]=csum;
a[j][i]=rsum;
}
a[3][3]=0;
for(i=0;i<4;i++)
{

152
C Language

for(j=0;j<4;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
getch();
}

106. Write a program to print how many Armstrong numbers present in a given array?

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,k,sum,m;
clrscr();
printf("enter 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("armstrong numbers are \n");
for(i=0;i<10;i++)
{
m=a[i];
sum=0;
while(m>0)
{
k=m%10;
sum=sum+(k*k*k);
m=m/10;
}
if(sum==a[i])
printf("%d ",a[i]);
}
getch();
}

107. Write a program to print how many palindrome numbers present in a given array?

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,k,sum,m;
clrscr();
printf("enter 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);

153
C Language

printf("palindrome numbers are \n");


for(i=0;i<10;i++)
{
m=a[i];
sum=0;
while(m>0)
{
k=m%10;
sum=sum*10+k;
m=m/10;
}
if(sum==a[i])
printf("%d ",a[i]);
}
getch();
}

108. W rite a program to print how many perfect numbers present in a given array?
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,k,sum,m,j;
clrscr();
printf("enter 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("perfect numbers are \n");
for(i=0;i<10;i++)
{
sum=0;
for(j=1;j<a[i];j++)
if(a[i]%j==0)
sum+=j;
if(sum==j)
printf("%d ",a[i]);
}
getch();
}

109. Write a program to print how many prime numbers present in a given array?

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

154
C Language

int a[10],i,count,j;
clrscr();
printf("enter 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("prime numbers are \n");
for(i=0;i<10;i++)
{
count=0;
for(j=2;j<a[i];j++)
if(a[i]%j==0)
count+=1;
if(count==0)
printf("%d ",a[i]);
}
getch();
}

110. Write a program to print how many strong numbers present in a given array?
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,sum,f,k,m;
clrscr();
printf("enter 10 array elements ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("strong numbers are \n");
for(i=0;i<10;i++)
{
m=a[i];
sum=0;
while(m>0)
{
f=1;
k=m%10;
while(k>0)
{
f=f*k;
k--;
}
sum+=f;
m=m/10;
}
if(a[i]==sum)

155
C Language

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

111. Write a program to print the reverse of the given string without using string
functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1;
int i,j,l=0;
clrscr();
puts("enter any string ");
gets(s);
l=strlen(s);
j=0;
for(i=l-1;i>=0;i--)
{
s1[j]=s[i];
j++;
}
s1[j]='\0';
printf("reverse of the given string is ");
puts(s1);
getch();
}

112. Write a program to print the length of the given string without using string
functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s;
int i,l=0;
clrscr();
puts("enter any string ");
gets(s);
for(i=0;s[i]!='\0';i++)
l++;
printf("length of the given string is %d ",l);
getch();
}

156
C Language

113. Write a program to print whether a given string is palindrome (or) not without
using string functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1;
int i,j,l=0;
clrscr();
puts("enter any string ");
gets(s);
l=strlen(s);
j=0;
for(i=l-1;i>=0;i--)
{
s1[j]=s[i];
j++;
}
s1[j]='\0';
if(strcmp(s,s1)==0)
printf("the given string is palindrome ");
else
printf("the given string is not a palindrome");
getch();
}

114. Write a program to copy a string to another without using string functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1;
int i;
clrscr();
puts("enter any string ");
gets(s);
for(i=0;s[i]!='\0';i++)
s1[i]=s[i];
s1[i]='\0';
printf("the given string is ");
puts(s);
printf("the copied string is ");
puts(s1);
getch();
}

157
C Language

115. Write a program to print whether the two strings are equal (or) not without using
strings functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1;
int i,l,count=0;
clrscr();
puts("enter any string ");
gets(s);
puts("enter another string ");
gets(s1);
if(strlen(s)==strlen(s1))
{
for(i=0;s[i]!='\0';i++)
{
if(s1[i]==s[i])
count=0;
else
count=1;
}
if(count==0)
printf("two strings are equal ");
else
printf("two strings are not equal ");
}
else
printf("two strings are not equal ");
getch();
}

116. Write a program to concatenate two strings with out using string functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1,*t;
int i,l,j;
clrscr();
puts("enter any string ");
gets(s);
puts("enter another string ");
gets(s1);
l=strlen(s);
j=0;

158
C Language

for(i=0;i<=l-1;i++)
{
t[j]=s[i];
j++;
}
l=strlen(s1);
for(i=0;i<=l-1;i++)
{
t[j]=s[i];
j++;
}
t[j]='\0';
printf("the conatenation string is ");
puts(t);
getch();
}

117. Write a program to whether a given word is found in a given string or not using
string functions?
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1,*t;
int i,j,count=0;
clrscr();
puts("enter main string ");
gets(s);
puts("enter a sub string ");
gets(s1);
i=0;
while(s[i]!='\0')
{
j=0;
while(s[i]!=' ' && s[i]!='\0')
t[j++]=s[i++];
t[j]='\0';
i++;
if(strcmp(s1,t)==0)
count++;
}
if(count>0)
printf("given string was found ");
else
printf("given string was not found ");
getch();

159
C Language

118. Write programs using some string functions


a. Strlen
b. Strrev
c. Strcat
d. Strcpy
e. Strcmp etc…
#include<stdio.h>
#include<conio.h>
void main()
{
char *s,*s1,*t;
int count=0;
clrscr();
puts("enter main string ");
gets(s);
puts("enter a sub string ");
gets(s1);
count=strlen(s);
if(strcmp(s1,s)==0)
printf("two strings are equal");
else
printf("two strings are not equal ");
printf("\n length of the given first string is %d \n reverse of the given first string is
",count);
strrev(s);
puts(s);
strcat(s,s1);
puts(s);
strcpy(t,s);
puts(s);
getch();
}

119. Write a program to print how many symbols present in a given array?
#include<stdio.h>
#include<conio.h>
void main()
{
char *st;
int i,count=0,j;
clrscr();
puts("enter any string ");
gets(st);

160
C Language

i=0;
while(st[i]!='\0')
{
for(j=1;j<=47;j++)
if(st[i]==j)
count++;
for(j=91;j<=96;j++)
if(st[i]==j)
count++;
for(j=123;j<=200;j++)
if(st[i]==j)
count++;
i++;
}
if(count>0)
printf("the number of symbols are %d ",count);
else
printf("there are no symbols ");
getch();
}

120. Write a program to print the ASCII codes for symbols?


#include<stdio.h>
#include<conio.h>
void main()
{
int j;
clrscr();
for(j=1;j<=47;j++)
printf("%d = %c\t ",j,j);
for(j=91;j<=96;j++)
printf("%d = %c\t ",j,j);
for(j=123;j<=200;j++)
printf("%d = %c\t ",j,j);
getch();
}

121. Write a user defined function to accept a number from main function and print
that in user’s function?
#include<stdio.h>
#include<conio.h>
void print(int);
void main()
{
int n;
clrscr();

161
C Language

printf("enter any number to n ");


scanf("%d",&n);
print(n);
getch();
}
void print(int n)
{
printf("given number is %d ",n);
}

122. Write a user defined function to accept a number from main function and find out
whether it is between 0 to 9 or not and print that result in main?
#include<stdio.h>
#include<conio.h>
int print(int);
void main()
{
int n,r;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
r=print(n);
if(r==0)
printf("the given number is inbetween 0 to 9");
else
printf("the given number is not in between 0 to 9 ");
getch();
}
int print(int n)
{
if((n>=0) && (n<=9))
return 0;
else
return 1;
}

123. Write a user defined function to accept a number from main function and find out
whether it is an integer number or not and print that value in another function?
#include<stdio.h>
#include<conio.h>
void send(int);
void check(long int);
void main()
{
long int n;
clrscr();

162
C Language

printf("enter any number to n ");


scanf("%d",&n);
check(n);
getch();
}
void check(long int a)
{
if(a>-32767 && a<=32768)
send(1);
else
send(0);
}
void send(int t)
{
if(t==1)
printf("the given number is an integer");
else
printf("the given number is not an integer");
}

124. Write a user defined function to accept an array of names and print them in an
ascending order?
#include<stdio.h>
#include<conio.h>
void ascending();
void main()
{
clrscr();
ascending();
getch();
}
void ascending()
{
char *st[10],i,j,*t;
clrscr();
puts("enter 10 names ");
for(i=0;i<10;i++)
gets(st[i]);
for(i=0;i<10-1;i++)
for(j=0;j<10-i-1;j++)
if(strcmp(st[j],st[j+1])>0)
{
strcpy(t,st[j]);
strcpy(st[j],st[j+1]);
strcpy(st[j+1],t);
}

163
C Language

printf("names in ascending order is \n");


for(i=0;i<10;i++)
puts(st[i]);
}

125. Write a user defined function to accept an array of numbers and print them in an
ascending order?
#include<stdio.h>
#include<conio.h>
void ascending();
void main()
{
clrscr();
ascending();
getch();
}
void ascending()
{
int a[10],i,j,t;
clrscr();
puts("enter 10 numbers ");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
for(i=0;i<10-1;i++)
for(j=0;j<10-i-1;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
printf("numbers in an ascending order is \n");
for(i=0;i<10;i++)
printf("%d ",a[i]);
}

126. Write 5 user defined functions in those read and print whether a given number is
Armstrong (or) not, strong (or) not, prime (or) not, perfect (or) not, palindrome (or) not
by taking that number from main function.

#include<stdio.h>
#include<conio.h>
void palindrome(int n);
void armstrong(int n);
void perfect(int n);
void prime(int n);

164
C Language

void strong(int n);


void unique(int n);
void main()
{
int n;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
palindrome(n);
armstrong(n);
perfect(n);
prime(n);
strong(n);
unique(n);
}
void palindrome(int n)
{
int m,k,rev=0;
clrscr();
m=n;
while(n>0)
{
k=n%10;
rev=rev*10+k;
n=n/10;
}
if(rev==m)
printf("given number is palindrome");
else
printf("given number is not a palindrome");
getch();
}
void armstrong(int n)
{
int m,k,sum=0;
clrscr();
m=n;
while(n>0)
{
k=n%10;
sum=sum+(k*k*k);
n=n/10;
}
if(sum==m)
printf("given number is an armstrong");
else

165
C Language

printf("given number is not an armstrong");


getch();
}
void perfect(int n)
{
int sum=0,i;
clrscr();
for(i=1;i<n;i++)
if(n%i==0)
sum+=i;
if(sum==n)
printf("given number is perfect");
else
printf("given number is not a perfect");
getch();
}
void strong(int n)
{
int m,k,sum=0,f;
clrscr();
m=n;
while(n>0)
{
k=n%10;
f=1;
while(k>0)
{
f=f*k;
k--;
}
sum+=f;
n=n/10;
}
if(sum==m)
printf("given number is a strong");
else
printf("given number is not a strong");
getch();
}
void prime(int n)
{
int count=0,i;
clrscr();
for(i=2;i<n;i++)
if(n%i==0)
count++;

166
C Language

if(count==0)
printf("given number is a prime");
else
printf("given number is not a prime");
getch();
}
void unique(int n)
{
int m,rev=0,k;
clrscr();
m=n*9;
while(n>0)
{
k=n%10;
rev=rev*10+k;
n=n/10;
}
if(rev==m)
printf("given number is an unique");
else
printf("given number is not an unique");
getch();
}

127. Create a structure with different student contents. Then read and print the details
in main?
#include<stdio.h>
#include<conio.h>
struct student
{
int stno;
char *stnm;
int m1,m2,m3;
};
void main()
{
struct student s;
clrscr();
printf("enter student name ");
scanf("%s",s.stnm);
printf("\nenter student number ");
scanf("%d",&s.stno);
printf("\nenter student marks ");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
clrscr();
printf("student details are \n");

167
C Language

printf("name is %s \n",s.stnm);
printf("number is %d \n",s.stno);
printf("student marks are %d %d %d \n",s.m1,s.m2,s.m3);
printf("total is %d ",s.m1+s.m2+s.m3);
getch();
}

128. Create a structure with different employee details. Then read and print the details
in main?
#include<stdio.h>
#include<conio.h>
struct employee
{
int emno;
char *emnm;
int sal;
};
void main()
{
struct employee e;
clrscr();
printf("enter employee name ");
scanf("%s",e.emnm);
printf("\nenter employee number ");
scanf("%d",&e.emno);
printf("\nenter employee salary ");
scanf("%d",&e.sal);
clrscr();
printf("employee details are \n");
printf("name is %s \n",e.emnm);
printf("number is %d \n",e.emno);
printf("employee salary is %d \n",e.sal);
getch();
}

129. Create a structure with different data types related to student then read and print n
student details in the main?

#include<stdio.h>
#include<conio.h>
struct student
{
int sno;
char stnm[25];
int m1,m2,m3,total;
};

168
C Language

void main()
{
struct student s[100];
int n,i;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);
printf("enter %d students name , number , 3 subjects marks ",n);
for(i=0;i<n;i++)
{
scanf("%s",s[i].stnm);
scanf("%d",&s[i].sno);
scanf("%d%d%d",&s[i].m1,&s[i].m2,&s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
}
printf(" THE STUDENT DETAILS ARE \n\n\n");
printf("name number m1 m2 m3 total\n");
printf("---- ------ -- -- -- -----\n");
for(i=0;i<n;i++)
{
printf("%s\t",s[i].stnm);
printf("%d\t",s[i].sno);
printf("%d %d %d ",s[i].m1,s[i].m2,s[i].m3);
printf("%d \n",s[i].total);
}
getch();
}

130. Create a structure with different data types related to an employee then read and
print n employee details in the main?

#include<stdio.h>
#include<conio.h>
struct employee
{
int eno;
char enm[25];
int esal;
};
void main()
{
struct employee e[100];
int n,i;
clrscr();
printf("enter any number to n ");
scanf("%d",&n);

169
C Language

printf("enter %d employees name , number , salary ",n);


for(i=0;i<n;i++)
{
scanf("%s",e[i].enm);
scanf("%d",&e[i].eno);
scanf("%d",&e[i].esal);
}
printf(" THE EMPLOYEE DETAILS ARE \n\n\n");
printf("name number salary\n");
printf("---- ------ ------\n");
for(i=0;i<n;i++)
{
printf("%s\t",e[i].enm);
printf("%d\t",e[i].eno);
printf("%d\n",e[i].esal);
}
getch();
}

131. write a program to print the scrolling banner?

#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<process.h>
void main()
{
char *st;
int i,j,l;
clrscr();
puts("enter a name ");
gets(st);
l=80-strlen(st);
for(i=l;i>=0;i--)
{
if(i>0)
{
for(i=l;i>0;i--)
{
clrscr();
if(kbhit())
exit(0);
textcolor(BLUE+BLINK);
gotoxy(i,24);
cputs(st);
delay(100);

170
C Language

}
}
if(i==0)
{
for(i=0;i<l;i++)
{
clrscr();
if(kbhit())
exit(0);
textcolor(RED+BLINK);
gotoxy(i,24);
cputs(st);
delay(100);
}
}
}
getch();
}

132. write a program to run digital clock?

#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<process.h>
void main()
{
int i,j,k,m,n,o;
clrscr();
printf("enter an hour,minute,second ");
scanf("%d%d%d",&m,&n,&o);
i=m;
j=n;
k=o;
for(;i<=m+2;i++)
{
for(;j<60;j++)
{
for(;k<60;k++)
{
if(kbhit())
exit(0);
clrscr();
printf("%d : %d : %d ",i,j,k);
delay(1000);
}

171
C Language

k=0;
}
if(i==23)
i=-1;
}
getch();
}

133. write a program to generate pascal triangle?

#include<stdio.h>
#include<conio.h>
void main()
{
int binom,p,q,r,x;
clrscr();
binom=1;
q=0;
printf("input the number os rows : ");
scanf("%d",&p);
printf("%d\n",p);
printf("Pascals triangle : \n");
while(q<p)
{
for(r=40-3*q;r>0;r--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0 || q==0)
binom=1;
else
binom=(binom*(q-x+1))/x;
printf("%6d",binom);
}
printf("\n");
q++;
}
getch();
}

134. write a program to print roots of quadratic equation?

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

172
C Language

{
float a,b,c,real,num,imag,root1,root2,disc;
int k;
clrscr();
printf("Input a b c : ");
scanf("%f%f%f",&a,&b,&c);
printf("%6.2f%6.2f%6.2f\n",a,b,c);
if(a!=0)
{
disc=b*b-4*a*c;
printf("Discriminant = %5.2f\n",disc);
if(disc<0)
k=1;
if(disc==0)
k=2;
if(disc>0)
k=3;
switch(k)
{
case 1:
printf("Roots are Imaginary\n");
real=-b/(2*a);
disc=-disc;
num=pow((double)disc,(double)0.5);
imag=num/(2*a);
printf("Root1=%5.2f+j%5.2f\n",real,imag);
printf("Root2=%5.2f-j%5.2f\n",real,imag);
break;
case 2:
printf("Roots are real and equal\n");
root1=-b/(2*a);
printf("Root1=Root2=%7.2f\n",root1);
break;
case 3:
printf("Roots are real and unequal \n");
root1=(-b+sqrt((double)disc))/(2*a);
root2=(-b-sqrt((double)disc))/(2*a);
printf("Root1=%7.2f Root2=%7.2f\n",root1,root2);
break;
default:
break;
}
}
else
printf("Equation is linear\n");
getch();

173
C Language

135. write a program to construct pyramid of digits?

#include<stdio.h>
#include<conio.h>
void main()
{
int p,m,q,n;
clrscr();
printf("Enter the number of lines : ");
scanf("%d",&n);
printf("%d\n\n",n);
for(p=1;p<=n;p++)
{
for(q=1;q<=n-p;q++)
printf(" ");//4 spaces
m=p;
for(q=1;q<=p;q++)
printf("%4d",m++);
m=m-2;
for(q=1;q<p;q++)
printf("%4d",m--);
printf("\n\n");
}
printf("\n");
getch();
}

136. write a program to print reversed pyramid?

#include<stdio.h>
#include<conio.h>
void main()
{
int p,q,r,t,s;
clrscr();
printf("Enter the number of lines in the pyramid : ");
scanf("%d",&t);
printf("%d\n\n",t);
printf("Reversed pyramid of digits\n\n");
for(p=t;p>1;p--)
{
printf(" ");//33 spaces
for(r=0;r<=p*4;r++)
printf("\b");

174
C Language

for(q=p;q<=(2*p)-1;q++)
printf("%4d",q);
for(s=(2*p)-2;s>=p;s--)
printf("%4d",s);
printf("\n");
}
printf(" %d\n",p);//31 spaces
getch();
}

C Interview Questions
Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,

Predict the output or error(s) for the following:


1. void main()
{
int const * p=5;
printf("%d",++(*p));
}

Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the
value of the "constant integer".

2. main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}

Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the
same idea. Generally array name is the base address for that array. Here s is
the base address. i is the index number/displacement from the base address. So,
indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C
it is same as s[i].

3. main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");

175
C Language

else
printf("I hate U");
}
Answer:
I hate

Explanation:

For floating point numbers (float, double, long double) the values
cannot be predicted exactly. Depending on the number of bytes, the precession
with of the value represented varies. Float takes 4 bytes and long double takes
10 bytes. So float stores 0.9 with less precision than long double.
Rule of Thumb:

Never compare or at-least be cautious when using floating point


numbers with relational operators (== , >, <, <=, >=,!= ) .

4. main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}

Answer:
54321
Explanation:
When static storage class is given, it is initialized once. The change
in the value of a static variable is retained even between the function calls. Main
is also treated like any other ordinary function, which can be called recursively.

5. main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}

Answer:
2222223465
Explanation:
Initially pointer c is assigned to both p and q. In the first loop,
since only q is incremented and not c , the value 2 will be printed 5 times. In
second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.

6. main()
{
extern int i;
i=20;

176
C Language

printf("%d",i);
}

Answer:
Linker Error : Undefined symbol '_i'
Explanation:
extern storage class in the following declaration,

extern int i;

specifies to the compiler that the memory for i is allocated in some other
program and that address will be given to the current program at the time of
linking. But linker finds that no other variable of name i is available in any other
program with memory space allocated for it. Hence a linker error has occurred .

7. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
Answer:
00131

Explanation :

Logical operations always give a result of 1 or 0 . And also the


logical AND (&&) operator has higher priority over the logical OR (||) operator. So
the expression ‘i++ && j++ && k++’ is executed first. The result of this
expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which
evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’
combination- for which it gives 0). So the value of m is 1. The values of other
variables are also incremented by 1.

8. main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}

Answer:
12
Explanation:
The sizeof() operator gives the number of bytes taken by its
operand. P is a character pointer, which needs one byte for storing its value (a
character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store
the address of the character pointer sizeof(p) gives 2.
9. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");

177
C Language

break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Answer :
three

Explanation :
The default case can be placed anywhere inside the loop. It is
executed only when all other cases doesn't match.

10. main()
{
printf("%x",-1<<4);
}

Answer:
fff0

Explanation :

-1 is internally represented as all 1's. When left shifted four times


the least significant 4 bits are filled with 0's.The %x format specifier specifies that
the integer value be printed as a hexadecimal value.

11. main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}

Answer:
Compiler Error : Type mismatch in redeclaration of function display

Explanation :
In third line, when the function display is encountered, the
compiler doesn't know anything about the function display. It assumes the
arguments and return types to be integers, (which is the default type). When it
sees the actual function display, the arguments and type contradicts with what it
has assumed previously. Hence a compile time error occurs.

12. main()
{
int c=- -2;
printf("c=%d",c);
}

Answer:

178
C Language

c=2;
Explanation:
Here unary minus (or negation) operator is used twice. Same
maths rules applies, ie. minus * minus= plus.
Note:
However you cannot give like --2. Because -- operator can only be
applied to variables as a decrement operator (eg., i--). 2 is a constant and not a
variable.

13. #define int char


main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}

Answer:
sizeof(i)=1

Explanation:
Since the #define replaces the string int by the macro char

14. main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}
Answer:
i=0
Explanation:
In the expression !i>14 , NOT (!) operator has more precedence
than ‘ >’ symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false).
0>14 is false (zero).

15. #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

Answer:
77

Explanation:
p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is
pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10,
which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is
pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is
98.

179
C Language

Now performing (11 + 98 – 32), we get 77("M");


So we get the output 77 :: "M" (Ascii is 77).

16. #include<stdio.h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}

Answer:
SomeGarbageValue---1

Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying
to access the third 2D(which you are not declared) it will print garbage values.
*q=***a starting address of a is assigned integer pointer. Now q is pointing to
starting address of a. If you print *q, it will print first element of 3D array.

17. #include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}

Answer:
Compiler Error

Explanation:
You should not initialize variables in declaration

18. #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;

180
C Language

};
struct yy *q;
};
}
Answer:
Compiler Error

Explanation:
The structure yy is nested within structure xx. Hence, the elements
are of yy are to be accessed through the instance of structure xx, which needs an
instance of yy to be known. If the instance is created after defining the structure
the compiler will not know about the instance relative to xx. Hence for nested
structure yy you have to declare member.

19. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}

Answer:
Hai

Explanation:
\n - newline
\b - backspace
\r - linefeed

20. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}

Answer:
45545

Explanation:
The arguments in a function call are pushed into the stack from left
to right. The evaluation is by popping out from the stack. and the evaluation is
from right to left, hence the result.

21. #define square(x) x*x


main()
{
int i;
i = 64/square(4);
printf("%d",i);
}

181
C Language

Answer:
64

Explanation:

the macro call square(4) will substituted by 4*4 so the expression


becomes i = 64/4*4 . Since / and * has equal priority the expression will be
evaluated as (64/4)*4 i.e. 16*4 = 64

22. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}

Answer:
ibj!gsjfoet

Explanation:
++*p++ will be parse in the given order
_ *p that is value at the location currently pointed by p will be taken
_ ++*p the retrieved value will be incremented
_ when ; is encountered the location will be incremented that is p++ will be
executed
Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by
executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’
and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p
becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1doesnot
print anything.

23. #include <stdio.h>


#define a 10
main()
{
#define a 50
printf("%d",a);
}

Answer:
50

Explanation:
The preprocessor directives can be redefined anywhere in the
program. So the most recently assigned value will be taken.

182
C Language

24. #define clrscr() 100

main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100

Explanation:
Preprocessor executes as a seperate pass before the execution of
the compiler. So textual replacement of clrscr() to 100 occurs.The input program
to compiler looks like this :

main()
{
100;
printf("%d\n",100);
}
Note:
100; is an executable statement but with no action. So it doesn't
give any problem

25. main()
{
41printf("%p",main);
}

Answer:
Some address will be printed.

Explanation:
Function names are just addresses (just like array names are
addresses).
main() is also a function. So the address of function main will be printed. %p in
printf specifies that the argument is an address. They are printed as hexadecimal
numbers.

27) main()
{
clrscr();
}
clrscr();
Answer:
No output/error

Explanation:
The first clrscr() occurs inside a function. So it becomes a function
call. In the second clrscr(); is a function declaration (because it is
not inside any function).

28) enum colors {BLACK,BLUE,GREEN}

183
C Language

main()
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
Answer:
0..1..2

Explanation:
enum assigns numbers starting from 0, if not explicitly defined.

29) void main()


{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer

30) main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300

Explanation:
printf takes the values of the first two assignments of the program.
Any number of printf's may be given. All of them take only the first
two values. If more number of assignments given in the
program,then printf will take garbage values.

31) main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H

Explanation:

* is a dereference operator & is a reference operator. They can be


applied any number of times provided it is meaningful. Here p
points to the first character in the string "Hello". *p dereferences it
and so its value is H. Again & references it to an address and *
dereferences it to the value H.

184
C Language

32) main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}

Answer:
Compiler error: Undefined label 'here' in function main

Explanation:
Labels have functions scope, in other words the scope of the labels
is limited to functions. The label 'here' is available in function fun()
Hence it is not visible in function main.
33) main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}

Answer:
Compiler error: Lvalue required in function main
Explanation:
Array names are pointer constants. So it cannot be modified.

34) void main()


{
int i=5;
printf("%d",i++ + ++i);
}
Answer:
Output Cannot be predicted exactly.

Explanation:
Side effects are involved in the evaluation of i

185
C Language

35) void main()


{
int i=5;
printf("%d",i+++++i);
}

Answer:
Compiler Error

Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an
illegal combination of operators.

36) #include<stdio.h>
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}

Answer:
Compiler Error: Constant expression required in function main.

Explanation:
The case statement can have only constant expressions (this
implies that we cannot use variable names directly so an error).
Note:
Enumerated types can be used in case statements.

37) main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}

Answer:
1
Explanation:

Scanf returns number of items successfully read and not 1/0. Here
10 is given as input which should have been scanned successfully.
So number of items read is 1.

38) #define f(g,g2) g##g2


main()
{
int var12=100;
printf("%d",f(var,12));

186
C Language

Answer:
100

39) main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}

Answer:
1

Explanation:
before entering into the for loop the checking condition is
"evaluated". Here it evaluates to 0 (false) and comes out of the
loop, and i is incremented (note the semicolon after the for loop).

40) #include<stdio.h>
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

Answer:
M

Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p
meAnswer:"p is pointing to '\n' and that is incremented by one."
the ASCII value of '\n' is 10. then it is incremented to 11. the value
of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is
incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both
11 and 98 is added and result is subtracted from 32.
i.e. (11+98-32)=77("M");

41) #include<stdio.h>
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);

187
C Language

Answer:
Compiler Error
Explanation:
Initialization should not be done for structure members inside the
structure declaration

42) #include<stdio.h>
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}

Answer:
Compiler Error
Explanation:
in the end of nested structure yy a member have to be declared.
43) main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}

Answer:
Linker error: undefined symbol '_i'.

Explanation:
extern declaration specifies that the variable i is defined
somewhere else. The compiler passes the external variable to be
resolved by the linker. So compiler doesn't find an error. During
linking the linker searches for the definition of i. Since it is not
found the linker flags an error.

44) main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.

Explanation:
The rule is that a variable is available for use from the point of

188
C Language

declaration. Even though a is a global variable, it is not available


for main. Hence an error.

45) main()
{
extern out;
printf("%d", out);
}
int out=100;

Answer:
100

Explanation:
This is the correct way of writing the previous program.

46) main()
{
show();
}
void show()
{
printf("I'm the greatest");
}

Answer:
Compier error: Type mismatch in redeclaration of show.

Explanation:
When the compiler sees the function show it doesn't know anything
about it. So the default return type (ie, int) is assumed. But when
compiler sees the actual definition of show mismatch occurs since it
is declared as void. Hence the error.
The solutions are as follows:
1. declare void show() in main() .
2. define show() before main().
3. declare extern void show() before the use of show().

47) main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(“%u %u %u %d \n”,a,*a,**a,***a);
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
}

Answer:
100, 100, 100, 2
114, 104, 102, 3

Explanation:
The given array is a 3-D one. It can also be viewed as a 1-D array.

189
C Language

247834222334
100 102 104 106 108 110 112 114 116 118 120 122
thus, for the first printf statement a, *a, **a give address of first
element . since the indirection ***a gives the value. Hence, the
first line of the output.
for the second printf a+1 increases in the third dimension thus
points to value at 114, *a+1 increments in second dimension thus
points to 104, **a +1 increments the first dimension thus points to
102 and ***a+1 first gets the value at first location and then
increments it by 1. Hence, the output.

48) main( )
{
int a[ ] = {10,20,30,40,50},j,*p;

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


{
printf(“%d” ,*a);
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(“%d ” ,*p);
p++;
}
}

Answer:
Compiler error: lvalue required.

Explanation:
Error is in line with statement a++. The operand must be an lvalue
and may be of any of scalar type for the any operator, array name
only when subscripted is an lvalue. Simply array name is a nonmodifiable
lvalue.

**49) main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}

190
C Language

Answer:
111
222
333
344

Explanation:
Let us consider the array and the two pointers with some address
a
01234
100 102 104 106 108
p
100 102 104 106 108
1000 1002 1004 1006 1008
ptr
1000
2000
After execution of the instruction ptr++ value in ptr becomes 1002,
if scaling factor for integer is 2 bytes. Now ptr – p is value in ptr –

starting location of array p, (1002 – 1000) / (scaling factor) = 1,


*ptr – a = value at address pointed by ptr – starting value of array
a, 1002 has a value 102 so the value is (102 – 100)/(scaling
factor) = 1, **ptr is the value stored in the location pointed by
the pointer of ptr = value pointed by value pointed by 1002 =
value pointed by 102 = 1. Hence the output of the firs printf is 1,
1, 1.
After execution of *ptr++ increments value of the value in ptr by
scaling factor, so it becomes1004. Hence, the outputs for the
second printf are ptr – p = 2, *ptr – a = 2, **ptr = 2.
After execution of *++ptr increments value of the value in ptr by
scaling factor, so it becomes1004. Hence, the outputs for the third
printf are ptr – p = 3, *ptr – a = 3, **ptr = 3.
After execution of ++*ptr value in ptr remains the same, the value
pointed by the value is incremented by the scaling factor. So the
value in array p at location 1006 changes from 106 10 108,.
Hence, the outputs for the fourth printf are ptr – p = 1006 – 1000
= 3, *ptr – a = 108 – 100 = 4, **ptr = 4.

50) main( )
{
char *q;
int j;
for (j=0; j<3; j++) scanf(“%s” ,(q+j));
for (j=0; j<3; j++) printf(“%c” ,*(q+j));
for (j=0; j<3; j++) printf(“%s” ,(q+j));
}
Explanation:
Here we have only one pointer to type char and since we take input
in the same pointer thus we keep writing over in the same location,
each time shifting the pointer value by 1. Suppose the inputs are
MOUSE, TRACK and VIRTUAL. Then for the first input suppose the
pointer starts at location 100 then the input one is stored as

191
C Language

M O U S E \0
When the second input is given the pointer is incremented as j
value becomes 1, so the input is filled in memory starting from
101.
M T R A C K \0
The third input starts filling from the location 102
M T V I R T U A L \0
This is the final value stored .
The first printf prints the values at the position q, q+1 and q+2 =
MTV
The second printf prints three strings starting from locations q,
q+1, q+2
i.e MTVIRTUAL, TVIRTUAL and VIRTUAL.

51) main( )
{
void *vp;
char ch = ‘g’, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}

Answer:
g20fy

Explanation:
Since a void pointer is used it can be type casted to any other type
pointer. vp = &ch stores address of char ch and the next
statement prints the value stored in vp after type casting it to the
proper data type pointer. the output is ‘g’. Similarly the output
from second printf is ‘20’. The third printf statement type casts it to
print the string from the 4th value hence the output is ‘fy’.

52) main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}
Answer:
Ck

Explanation:
In this problem we have an array of char pointers pointing to start
of 4 strings. Then we have ptr which is a pointer to a pointer of
type char and a variable p which is a pointer to a pointer to a

192
C Language

pointer of type char. p hold the initial value of ptr, i.e. p = s+3.
The next statement increment value in p by 1 , thus now value of p
= s+2. In the printf statement the expression is evaluated *++p
causes gets value s+1 then the pre decrement is executed and we
get s+1 – 1 = s . the indirection operator now gets the value from
the array of s and adds 3 to the starting address. The string is
printed starting from this position. Thus, the output is ‘ck’.

53) main()
{
int i, n;
char *x = “girl”;
n = strlen(x);
*x = x[n];
for(i=0; i<n; ++i)
{
printf(“%s\n”,x);
x++;
}
}
Answer:
(blank space)

irl
rl
l

Explanation:
Here a string (a pointer to char) is initialized with a value “girl”.
The strlen function returns the length of the string, thus n has a
value 4. The next statement assigns value at the nth location (‘\0’)
to the first location. Now the string becomes “\0irl” . Now the printf
statement prints the string after each iteration it increments it
starting position. Loop starts from 0 to 4. The first time x[0] = ‘\0’
hence it prints nothing and pointer value is incremented. The
second time it prints from x[1] i.e “irl” and the third time it prints
“rl” and the last time it prints “l” and the loop terminates.

54) int i,j;


for(i=0;i<=10;i++)
{
j+=5;
assert(i<5);
}

Answer:
Runtime error: Abnormal program termination.
assert failed (i<5), <file name>,<line number>
Explanation:
asserts are used during debugging to make sure that certain
conditions are satisfied. If assertion fails, the program will
terminate reporting the same. After debugging use,

#undef NDEBUG
and this will disable all the assertions from the source code.

193
C Language

Assertion
is a good debugging tool to make use of.

55) main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes
you can just ignore it just because it has no effect in the
expressions (hence the name dummy operator).
56) What are the files which are automatically opened when a C file is
executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard
error).
57) what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);

b: fseek(ptr,0,SEEK_CUR);
Answer :
a: The SEEK_SET sets the file position marker to the starting of the
file.
b: The SEEK_CUR sets the file position marker to the current
position
of the file.

58) main()
{
char name[10],s[12];
scanf(" \"%[^\"]\"",s);
}

How scanf will execute?

Answer:
First it checks for the leading white space and discards it.Then it
matches with a quotation mark and then it reads all character upto
another quotation mark.

59) What is the problem with the following code segment?


while ((fgets(receiving array,50,file_ptr)) != EOF)
;
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking
for != NULL.

194
C Language

60) main()
{
main();
}
Answer:
Runtime error : Stack overflow.

Explanation:
main function calls itself again and again. Each time the function is
called its return address is stored in the call stack. Since there is
no condition to terminate the function call, the call stack overflows
at runtime. So it terminates the program and results in an error.

61) main()
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer:
Compiler error (at line number 4): size of v is Unknown.

Explanation:
You can create a variable of type void * but not of type void, since
void is an empty type. In the second line you are creating variable
vptr of type void * and v of type void hence an error.

62) main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}

Answer:
255

Explanation:
In first sizeof, str1 is a character pointer so it gives you the size of
the pointer variable. In second sizeof the name str2 indicates the
name of the array whose size is 5 (including the '\0' termination
character). The third sizeof is similar to the second one.

63) main()
{
char not;
not=!2;
printf("%d",not);
}

195
C Language

Answer:
0

Explanation:
! is a logical operator. In C the value 0 is considered to be the
boolean value FALSE, and any non-zero value is considered to be
the boolean value TRUE. Here 2 is a non-zero value so TRUE.
!TRUE is FALSE (0) so it prints 0.

64) #define FALSE -1


#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}

Answer:
TRUE
Explanation:
The input program to the compiler after processing by the
preprocessor is,
main(){
if(0)
puts("NULL");
else if(-1)
puts("TRUE");
else
puts("FALSE");
}

Preprocessor doesn't replace the values given inside the double


quotes. The check by if condition is boolean value false so it goes
to else. In second if -1 is boolean value true hence "TRUE" is
printed.

65) main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}

Answer:
1==1 is TRUE

Explanation:
When two strings are placed together (or separated by whitespace)
they are concatenated (this is called as "stringization"
operation). So the string is as if it is given as "%d==1 is %s". The
conditional operator( ?: ) evaluates to "TRUE".

196
C Language

66) main()
{
int y;
scanf("%d",&y); // input given is 2000
if( (y%4==0 && y%100 != 0) || y%100 == 0 )
printf("%d is a leap year");
else
printf("%d is not a leap year");
}

Answer:
2000 is a leap year

Explanation:
An ordinary program to check if leap year or not.

67) #define max 5


#define int arr1[max]
main()
{
typedef char arr2[max];
arr1 list={0,1,2,3,4};
arr2 name="name";
printf("%d %s",list[0],name);
}

Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})

Explanation:
arr2 is declared of type array of size 5 of characters. So it can be
used to declare the variable name of the type arr2. But it is not the
case of arr1. Hence an error.
Rule of Thumb:

#defines are used for textual replacement whereas typedefs are


used for declaring new types.

68) int i=10;


main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}

197
C Language

Answer:
30,20,10

Explanation:
'{' introduces new block and thus new scope. In the innermost
block i is declared as,
const volatile unsigned
which is a valid declaration. i is assumed of type int. So printf
prints 30. In the next block, i has value 20 and so printf prints 20.
In the outermost block, i is declared as extern, so no storage space
is allocated for it. After compilation is over the linker resolves it to
global variable i (since it is the only variable visible there). So it
prints i's value as 10.

69) main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
Answer:
10

Explanation:
The variable i is a block level variable and the visibility is inside
that block only. But the lifetime of i is lifetime of the function so it
lives upto the exit of main function. Since the i is still allocated
space, *j prints the value stored in i since j points i.

70) main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1
Explanation:

-i is executed and this execution doesn't affect the value of i. In


printf first you just print the value of i. After that the value of the
expression -i = -(-1) is printed.

71) #include<stdio.h>
main()
{
const int i=4;
float j;

198
C Language

j = ++i;
printf("%d %f", i,++j);
}

Answer:
Compiler error

Explanation:
i is a constant. you cannot change the value of constant

72) #include<stdio.h>
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d..%d",*p,*q);
}

Answer:
garbagevalue..1

Explanation:
p=&a[2][2][2] you declare only two 2D arrays. but you are trying
to access the third 2D(which you are not declared) it will print
garbage values. *q=***a starting address of a is assigned integer
pointer. now q is pointing to starting address of a.if you print *q
meAnswer:it will print first element of 3D array.

73) #include<stdio.h>
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}

Answer:
hello 5

Explanation:
if you declare i as register compiler will treat it as ordinary integer
and it will take integer value. i value may be stored either in
register or in memory.

74) main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11

Explanation:

199
C Language

the expression i+++j is treated as (i++ + j)

76) struct aaa{


struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
struct aaa abc,def,ghi,jkl;
int x=100;
abc.i=0;abc.prev=&jkl;
abc.next=&def;
def.i=1;def.prev=&abc;def.next=&ghi;
ghi.i=2;ghi.prev=&def;
ghi.next=&jkl;
jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
x=abc.next->next->prev->next->i;
printf("%d",x);
}

Answer:
2

Explanation:
above all statements form a double circular linked list;
abc.next->next->prev->next->i
this one points to "ghi" node the value of at particular node is 2.

77) struct point


{
int x;
int y;
};
struct point origin,*pp;
main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
printf("origin is (%d%d)\n",pp->x,pp->y);
}
Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure. we can access the elements of the
structure either with arrow mark or with indirection operator.
Note:
Since structure point is globally declared x & y are initialized as
zeroes

78) main()
{

200
C Language

int i=_l_abc(10);
printf("%d\n",--i);
}
int _l_abc(int i)
{
return(i++);
}

Answer:
9

Explanation:
return(i++) it will first return i and then increments. i.e. 10 will be
returned.

79) main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}

Answer:
0001...0002...0004

Explanation:
++ operator when applied to pointers increments address
according to their corresponding data-types.

80) main()
{
char c=' ',x,convert(z);
getc(c);
if((c>='a') && (c<='z'))
x=convert(c);
printf("%c",x);
}
convert(z)
{
return z-32;
}

Answer:
Compiler error

Explanation:
declaration of convert and format of getc() are wrong.

201
C Language

81) main(int argc, char **argv)


{
printf("enter the character");
getchar();
sum(argv[1],argv[2]);
}
sum(num1,num2)
int num1,num2;
{
return num1+num2;
}

Answer:
Compiler error.

Explanation:
argv[1] & argv[2] are strings. They are passed to the function sum
without converting it to integer values.

82) # include <stdio.h>


int one_d[]={1,2,3};
main()
{
int *ptr;
ptr=one_d;
ptr+=3;
printf("%d",*ptr);
}

Answer:
garbage value
Explanation:
ptr pointer is pointing to out of the array range of one_d.

83) # include<stdio.h>
aaa() {
printf("hi");
}
bbb(){
printf("hello");
}
ccc(){
printf("bye");
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;

202
C Language

ptr[2]=ccc;
ptr[2]();
}

Answer:
Bye

Explanation:
ptr is array of pointers to functions of return type int.ptr[0] is
assigned to address of the function aaa. Similarly ptr[1] and ptr[2]
for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(),
since ptr[2] points to ccc.

85) #include<stdio.h>
main()
{
FILE *ptr;
char i;
ptr=fopen("zzz.c","r");
while((i=fgetch(ptr))!=EOF)
printf("%c",i);
}

Answer:
contents of zzz.c followed by an infinite loop

Explanation:
The condition is checked against EOF, it should be checked against
NULL.

86) main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}

Answer:
0..0

Explanation:
The value of i is 0. Since this information is enough to determine
the truth value of the boolean expression. So the statement
following the if statement is not executed. The values of i and j
remain unchanged and get printed.

87) main()
{
int i;
i = abc();
printf("%d",i);
}

203
C Language

abc()
{
_AX = 1000;
}

Answer:
1000

Explanation:
Normally the return value from the function is through the
information from the accumulator. Here _AH is the pseudo global
variable denoting the accumulator. Hence, the value of the
accumulator is set 1000 so the function returns value 1000.

88) int i;
main(){
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))

printf("%d--",t--);
}

// If the inputs are 0,1,2,3 find the o/p


Answer:
4--0
3--1
2—2

Explanation:
Let us assume some x= scanf("%d",&i)-t the values during
execution
will be,
tix
4 0 -4
3 1 -2
220

89) main(){
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}

Answer:
Hello

Explanation:
The comma operator has associativity from left to right. Only the
rightmost value is returned and the other values are evaluated and
ignored. Thus the value of last variable y is returned to check in if.
Since it is a non zero value if becomes true so, "hello" will be
printed.

204
C Language

90) main(){
unsigned int i;
for(i=1;i>-2;i--)
printf("c aptitude");
}

Explanation:
i is an unsigned integer. It is compared with a signed value. Since
the both types doesn't match, signed is promoted to unsigned
value. The unsigned equivalent of -2 is a huge value so condition
becomes false and control comes out of the loop.
91) In the following pgm add a stmt in the function fun such that the address
of
'a' gets stored in 'j'.
main(){
int * j;
void fun(int **);
fun(&j);
}
void fun(int **k) {
int a =0;
/* add a stmt here*/
}

Answer:
*k = &a

Explanation:
The argument of the function is a pointer to a pointer.

92) What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}
ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation
93) main()
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
Answer:
300

205
C Language

Explanation:
The pointer points to % since it is incremented twice and again
decremented by 2, it points to '%d\n' and 300 is printed.

94) main(){
char a[100];
a[0]='a';a[1]]='b';a[2]='c';a[4]='d';
abc(a);
}
abc(char a[]){
a++;
printf("%c",*a);
a++;
printf("%c",*a);
}

Explanation:
The base address is modified only in function and as a result a
points to 'b' then after incrementing to 'c' so bc will be printed.

95) func(a,b)
int a,b;
{
return( a= (a==b) );
}

main()
{
int process(),func();
printf("The value of process is %d !\n ",process(func,3,6));
}
process(pf,val1,val2)
int (*pf) ();
int val1,val2;
{
return((*pf) (val1,val2));
}

Answer:
The value if process is 0 !

Explanation:
The function 'process' has 3 parameters - 1, a pointer to another
function 2 and 3, integers. When this function is invoked from
main, the following substitutions for formal parameters take place:
func for pf, 3 for val1 and 6 for val2. This function returns the
result of the operation performed by the function 'func'. The
function func has two integer parameters. The formal parameters
are substituted as 3 for a and 6 for b. since 3 is not equal to 6,
a==b returns 0. therefore the function returns 0 which in turn is
returned by the function 'process'.
96) void main()

206
C Language

{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}

Answer:
0000
Explanation:
The variable "I" is declared as static, hence memory for I will be
allocated for only once, as it encounters the statement. The function
main() will be called recursively unless I becomes equal to 0, and since
main() is recursively called, so the value of static I ie., 0 will be printed
every time the control is returned.

97) void main()


{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7

Explanation:
The int ret(int ret), ie., the function name and the argument name
can be the same.
Firstly, the function ret() is called in which the sizeof(float) ie., 4 is
passed, after the first expression the value in ret will be 6, as ret is
integer hence the value stored in ret will have implicit type conversion
from float to int. The ret is returned in main() it is printed after and
preincrement.

98) void main()


{
char a[]="12345\0";
int i=strlen(a);
printf("here in 3 %d\n",++i);
}

Answer:
here in 3 6

Explanation:
The char array 'a' will hold the initialized string, whose length will
be counted from 0 till the null character. Hence the 'I' will hold the value
equal to 5, after the pre-increment in the printf statement, the 6 will be
printed.

207
C Language

99) void main()


{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}

Answer:
0 65535

Explanation:

100) void main()


{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}

Answer:
Ok here

Explanation:
Printf will return how many characters does it print. Hence
printing a null character returns 1 which makes the if
statement true, thus "Ok here" is printed.

101) void main()


{
void *v;

int integer=2;
int *i=&integer;
v=i;
printf("%d",(int*)*v);
}

Answer:
Compiler Error. We cannot apply indirection on type void*.

Explanation:
Void pointer is a generic pointer type. No pointer arithmetic can
be done on it. Void pointers are normally used for,
1. Passing generic pointers to functions and returning such
pointers.
2. As a intermediate pointer type.
3. Used when the exact pointer type will be known at a later
point of time.

208
C Language

102) void main()


{
int i=i++,j=j++,k=k++;
printf(“%d%d%d”,i,j,k);
}

Answer:
Garbage values.

Explanation:
An identifier is available to use in program code from the point of
its declaration.
So expressions such as i = i++ are valid statements. The i, j and k
are automatic variables and so they contain some garbage value.
Garbage in is garbage out (GIGO).

103) void main()


{
static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}

Answer:
i=1j=1k=1

Explanation:
Since static variables are initialized to zero by default.
104) void main()
{
while(1){
if(printf("%d",printf("%d")))
break;
else
continue;
}
}

Answer:
Garbage values

Explanation:

The inner printf executes first to print some garbage value. The
printf returns no of characters printed and this value also cannot be
predicted. Still the outer printf prints something and so returns a
non-zero value. So it encounters the break statement and comes
out of the while statement.

104) main()
{

209
C Language

unsigned int i=10;


while(i-->=0)
printf("%u ",i);
}

Answer:
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the
expression i-- >=0 will always be true, leading to an infinite loop.

105) #include<conio.h>
main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}

Answer:
Garbage-value 0

Explanation:
The value of y%2 is 0. This value is assigned to x. The condition
reduces to if (x) or in other words if(0) and so z goes uninitialized.
Thumb Rule: Check all control paths to write bug free code.

106) main()
{
int a[10];
printf("%d",*a+1-*a+3);
}

Answer:
4

Explanation:
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !

107) #define prod(a,b) a*b


main()
{
int x=3,y=4;
printf("%d",prod(x+2,y-1));
}
Answer:
10

Explanation:
The macro expands and evaluates to as:
x+2*y-1 => x+(2*y)-1 => 10
108) main()
{

210
C Language

unsigned int i=65000;


while(i++!=0);
printf("%d",i);
}

Answer:
1

Explanation:
Note the semicolon after the while statement. When the value of i
becomes 0 it comes out of while loop. Due to post-increment on i
the value of i while printing is 1.

109) main()
{
int i=0;
while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}

Answer:
-1

Explanation:
Unary + is the only dummy operator in C. So it has no effect on
the expression and now the while loop is, while(i--!=0) which is
false and so breaks out of while loop. The value –1 is printed due
to the post-decrement operator.

113) main()
{
float f=5,g=10;
enum{i=10,j=20,k=50};
printf("%d\n",++k);
printf("%f\n",f<<2);
printf("%lf\n",f%g);
printf("%lf\n",fmod(f,g));
}
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply
++.
Bit-wise operators and % operators cannot be applied on float
values.
fmod() is to find the modulus values for floats as % operator is for
ints.

110) main()
{

211
C Language

int i=10;
void pascal f(int,int,int);
f(i++,i++,i++);
printf(" %d",i);
}
void pascal f(integer :i,integer:j,integer :k)
{
write(i,j,k);
}

Answer:
Compiler error: unknown type integer
Compiler error: undeclared function write

Explanation:
Pascal keyword doesn’t mean that pascal code can be used. It
means that the function follows Pascal argument passing mechanism in
calling the functions.

111) void pascal f(int i,int j,int k)


{
printf(“%d %d %d”,i, j, k);
}
void cdecl f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
main()
{
int i=10;
f(i++,i++,i++);
printf(" %d\n",i);
i=10;
f(i++,i++,i++);
printf(" %d",i);
}

Answer:
10 11 12 13
12 11 10 13

Explanation:
Pascal argument passing mechanism forces the arguments to be
called from left to right. cdecl is the normal C argument passing
mechanism where the arguments are passed from right to left.

112). What is the output of the program given below


main()
{
signed char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}

212
C Language

Answer
-128

Explanation
Notice the semicolon at the end of the for loop. THe initial
value of the i is set to 0. The inner loop executes to
increment the value from 0 to 127 (the positive range of
char) and then it rotates to the negative value of -128. The
condition in the for loop fails and so comes out of the for
loop. It prints the current value of i that is -128.

113) main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}

Answer
infinite loop

Explanation
The difference between the previous question and this one is that
the char is declared to be unsigned. So the i++ can never yield negative
value and i>=0 never becomes false so that it can come out of the for
loop.

114) main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}

Answer:
Behavior is implementation dependent.

Explanation:
The detail if the char is signed/unsigned by default is
implementation dependent. If the implementation treats the char
to be signed by default the program will print –128 and terminate.
On the other hand if it considers char to be unsigned by default, it
goes to infinite loop.
Rule:
You can write programs that have implementation
dependent behavior. But dont write programs that depend on such
behavior.

115) Is the following statement a declaration/definition. Find what does it


mean?
int (*x)[10];

Answer
Definition.

213
C Language

x is a pointer to array of(size 10) integers.


Apply clock-wise rule to find the meaning of this definition.

116). What is the output for the program given below


typedef enum errorType{warning, error, exception,}error;
main()
{
error g1;
g1=1;
printf("%d",g1);
}

Answer
Compiler error: Multiple declaration for error

Explanation
The name error is used in the two meanings. One means
that it is a enumerator constant with value 1. The another use is
that it is a type name (due to typedef) for enum errorType. Given a
situation the compiler cannot distinguish the meaning of error to
know in what sense the error is used:
error g1;
g1=error;
// which error it refers in each case?
When the compiler can distinguish between usages then it
will not issue error (in pure technical terms, names can only be
overloaded in different namespaces).
Note: the extra comma in the declaration,
enum errorType{warning, error, exception,}
is not an error. An extra comma is valid and is provided just for
programmer’s convenience.

117) typedef struct error{int warning, error,


exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}

Answer
1

Explanation
The three usages of name errors can be distinguishable by the
compiler at any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as
in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the

214
C Language

variable name as in :
g1.error =1;
printf("%d",g1.error);
typedef struct error{int warning, error, exception;}error;

This can be used to define variables without using the preceding struct
keyword as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it
is perfectly legal and valid.
Note
This code is given here to just explain the concept behind. In real
programming don’t use such overloading of names. It reduces the
readability of the code. Possible doesn’t mean that we should use it!

118) #ifdef something


int some=0;
#endif
main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation.
The name something is not already known to the compiler
making the declaration
int some = 0;
effectively removed from the source code.

119) #if something == 0


int some=0;
#endif
main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer
00
Explanation
This code is to show that preprocessor expressions are not
the same as the ordinary expressions. If a name is not
known the preprocessor treats it to be equal to zero.

120). What is the output for the following program


main()

215
C Language

{
int arr2D[3][3];

printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0]))


);
}

Answer
1

Explanation
This is due to the close relation between the arrays and
pointers. N dimensional arrays are made up of (N-1)
dimensional arrays.
arr2D is made up of a 3 single arrays that contains 3
integers each .
The name arr2D refers to the beginning of all the 3 arrays.
*arr2D refers to the start of the first 1D array (of 3
integers) that is the same address as arr2D. So the
expression (arr2D == *arr2D) is true (1).
Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero
doesn’t change the value/meaning. Again arr2D[0] is the
another way of telling *(arr2D + 0). So the expression
(*(arr2D + 0) == arr2D[0]) is true (1).
Since both parts of the expression evaluates to true the
result is true(1) and the same is printed.

121) void main()


{
if(~0 == (unsigned int)-1)
printf(“You can answer this if you know how values are represented
in memory”);
}
Answer
You can answer this if you know how values are represented
in memory
Explanation
~ (tilde operator or bit-wise negation operator) operates on
0 to produce all ones to fill the space for an integer. –1 is
represented in unsigned value as all 1’s and so both are
equal.
122) int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
arr2D
arr2D[1]
arr2D[2]
arr2D[3]

216
C Language

printf("x= %d y = %d\n",x,y);
}
Answer
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help
understand this.

123) main()
{
char *p = “ayqm”;
printf(“%c”,++*(p++));
}

Answer:
B

124) main()
{
int i=5;
printf("%d",++i++);
}

Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is
required.

125) main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}

Answer:
b

Explanation:
There is no difference between the expression ++*(p++)
and ++*p++. Parenthesis just works as a visual clue for the
reader to see which expression is first evaluated.

126)
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}

217
C Language

iny ccc(){printf(“bye”);}
main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();

Answer:
bye

Explanation:
int (* ptr[3])() says that ptr is an array of pointers to functions
that takes no arguments and returns the type int. By the
assignment ptr[0] = aaa; it means that the first function pointer in
the array is initialized with the address of the function aaa.
Similarly, the other two array elements also get initialized with the
addresses of the functions bbb and ccc. Since ptr[2] contains the
address of the function ccc, the call to the function ptr[2]() is same
as calling ccc(). So it results in printing "bye".

127)
main()
{
int i=5;
printf(“%d”,i=++i ==6);
}
Answer:
1

Explanation:
The expression can be treated as i = (++i==6), because == is of
higher precedence than = operator. In the inner expression, ++i is
equal to 6 yielding true(1). Hence the result.

128) main()
{
char p[ ]="%d\n";
p[1] = 'c';
printf(p,65);
}

Answer:
A

Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”.
Since this string becomes the format string for printf and ASCII

218
C Language

value of 65 is ‘A’, the same gets printed.


129) void ( * abc( int, void ( *def) () ) ) ();
Answer::
abc is a ptr to a function which takes 2 parameters .(a). an
integer variable.(b). a ptrto a funtion which returns void. the
return type of the function is void.
Explanation:
Apply the clock-wise rule to find the result.

130) main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
}

Answer:
No output

Explanation:
Ending the string constant with \0 explicitly makes no difference.
So “some” and “some\0” are equivalent. So, strcmp returns 0
(false) hence breaking out of the while loop.

131) main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}

Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not
appended automatically to the string. Since str1 doesn’t have null
termination, it treats whatever the values that are in the following
positions as part of the string until it randomly reaches a ‘\0’. So
str1 and str2 are not the same, hence the result.

132) main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}
Answer:
Compiler Error: Lvalue required.
Explanation:
As we know that increment operators return rvalues and
hence it cannot appear on the left hand side of an
assignment operation.
133) void main()

219
C Language

{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}

Answer:
garbage-value 0

Explanation:
The memory space allocated by malloc is uninitialized, whereas
calloc returns the allocated memory space initialized to zeros.

134) void main()


{
static int i;
while(i<=10)
(i>2)?i++:i--;
printf(“%d”, i);
}

Answer:
32767

Explanation:
Since i is static it is initialized to 0. Inside the while loop the
conditional operator evaluates to false, executing i--. This
continues till the integer value rotates to positive value (32767).
The while condition becomes false and hence, comes out of the
while loop, printing the i value.

135) main()
{
int i=10,j=20;
j = i, j?(i,j)?i:j:j;
printf("%d %d",i,j);
}

Answer:
10 10

Explanation:
The Ternary operator ( ? : ) is equivalent for if-then-else
statement. So the question can be written as:
if(i,j)
{
if(i,j)
j = i;
else
j = j;
}
else

220
C Language

j = j;
136) 1. const char *a;
2. char* const a;
3. char const *a;
-Differentiate the above declarations.

Answer:
1. 'const' applies to char * rather than 'a' ( pointer to a constant
char )
*a='F' : illegal
a="Hi" : legal
2. 'const' applies to 'a' rather than to the value of a (constant
pointer to char )

*a='F' : legal
a="Hi" : illegal
3. Same as 1.

137) main()
{
int i=5,j=10;
i=i&=j&&10;
printf("%d %d",i,j);
}

Answer:
1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner
expression (j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is
1. Hence the result.

138) main()
{
int i=4,j=7;
j = j || i++ && printf("YOU CAN");
printf("%d %d", i, j);
}

Answer:
41

Explanation:
The boolean expression needs to be evaluated only till the truth
value of the expression is not known. j is not equal to zero itself
means that the expression’s truth value is 1. Because it is followed
by || and true || (anything) => true where (anything) will not be
evaluated. So the remaining expression is not evaluated and so the
value of i remains the same.
Similarly when && operator is involved in an expression, when any
of the operands become false, the whole expression’s truth value
becomes false and hence the remaining expression will not be
evaluated.
false && (anything) => false where (anything) will not be

221
C Language

evaluated.

139) main()
{
register int a=2;
printf("Address of a = %d",&a);
printf("Value of a = %d",a);
}
Answer:
Compier Error: '&' on register variable
Rule to Remember:
& (address of ) operator cannot be applied on register
variables.

140) main()
{
float i=1.5;
switch(i)
{
case 1: printf("1");
case 2: printf("2");
default : printf("0");
}
}

Answer:
Compiler Error: switch expression not integral

Explanation:
Switch statements can be applied only to integral types.

141) main()
{
extern i;
printf("%d\n",i);
{
int i=20;
printf("%d\n",i);
}
}

Answer:
Linker Error : Unresolved external symbol i

Explanation:
The identifier i is available in the inner block and so using extern
has no use in resolving it.

142) main()
{
int a=2,*f1,*f2;

222
C Language

f1=f2=&a;
*f2+=*f2+=a+=2.5;
printf("\n%d %d %d",a,*f1,*f2);
}

Answer:
16 16 16
Explanation:
f1 and f2 both refer to the same memory location a. So changes
through f1 and f2 ultimately affects only the value of a.

143) main()
{
char *p="GOOD";
char a[ ]="GOOD";
printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d",
sizeof(p), sizeof(*p), strlen(p));
printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
}
Answer:
sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
sizeof(a) = 5, strlen(a) = 4

Explanation:
sizeof(p) => sizeof(char*) => 2
sizeof(*p) => sizeof(char) => 1
Similarly,
sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the
array and it is not the same as the sizeof the pointer variable. Here
the sizeof(a) where a is the character array and the size of the
array is 5 because the space necessary for the terminating NULL
character should also be taken into account.

144) #define DIM( array, type) sizeof(array)/sizeof(type)


main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr, int));
}

Answer:
10

Explanation:
The size of integer array of 10 elements is 10 * sizeof(int). The
macro expands to sizeof(arr)/sizeof(int) => 10 * sizeof(int) /
sizeof(int) => 10.

145) int DIM(int array[])


{
return sizeof(array)/sizeof(int );

223
C Language

}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));
}

Answer:
1

Explanation:
Arrays cannot be passed to functions as arguments and only the
pointers can be passed. So the argument is equivalent to int *
array (this is one of the very few places where [] and * usage are
equivalent). The return statement becomes, sizeof(int *)/
sizeof(int) that happens to be equal in this case.

146) main()
{
static int a[3][3]={1,2,3,4,5,6,7,8,9};
int i,j;
static *p[]={a,a+1,a+2};
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),
*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
}
}

Answer:
1111
2424
3737
4242
5555
6868
7373
8686
9999
Explanation:
*(*(p+i)+j) is equivalent to p[i][j].
147) main()
{
void swap();
int x=10,y=8;
swap(&x,&y);
printf("x=%d y=%d",x,y);
}
void swap(int *a, int *b)
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
Answer:
x=10 y=8
Explanation:

224
C Language

Using ^ like this is a way to swap two variables without using a


temporary variable and that too in a single statement.
Inside main(), void swap(); means that swap is a function that
may take any number of arguments (not no arguments) and
returns nothing. So this doesn’t issue a compiler error by the call
swap(&x,&y); that has two arguments.
This convention is historically due to pre-ANSI style (referred to as
Kernighan and Ritchie style) style of function declaration. In that
style, the swap function will be defined as follows,
void swap()
int *a, int *b
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
where the arguments follow the (). So naturally the declaration for
swap will look like, void swap() which means the swap can take
any number of arguments.
148) main()
{
int i = 257;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
11
Explanation:
The integer value 257 is stored in the memory as, 00000001
00000001, so the individual bytes are taken by casting it to char *
and get printed.

149) main()
{
int i = 258;
int *iPtr = &i;
printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
21

Explanation:
The integer value 257 can be represented in binary as, 00000001
00000001. Remember that the INTEL machines are ‘small-endian’
machines. Small-endian means that the lower order bytes are
stored in the higher memory addresses and the higher order bytes
are stored in lower addresses. The integer value 258 is stored in
memory as: 00000001 00000010.

150) main()
{
int i=300;
char *ptr = &i;
*++ptr=2;
printf("%d",i);
}

225
C Language

Answer:
556
Explanation:
The integer value 300 in binary notation is: 00000001 00101100.
It is stored in memory (small-endian) as: 00101100 00000001.
Result of the expression *++ptr = 2 makes the memory
representation as: 00101100 00000010. So the integer
corresponding to it is 00000010 00101100 => 556.

151) #include <stdio.h>


main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = (*ptr<least ) ?*ptr :least;
printf("%d",least);
}
Answer:
0

Explanation:

After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is
‘\0’. So the value of ‘str’ is less than that of ‘least’. So the value of
‘least’ finally is 0.
152) Declare an array of N pointers to functions returning pointers to functions
returning pointers to characters?
Answer:
(char*(*)( )) (*ptr[N])( );

153) main()
{
struct student
{
char name[30];
struct date dob;
}stud;
struct date
{
int day,month,year;
};
scanf("%s%d%d%d", stud.rollno, &student.dob.day,
&student.dob.month, &student.dob.year);
}

Answer:
Compiler Error: Undefined structure date
Explanation:

226
C Language

Inside the struct definition of ‘student’ the member of type struct


date is given. The compiler doesn’t have the definition of date
structure (forward reference is not allowed in C in this case) so it
issues an error.

154) main()
{
struct date;
struct student
{
char name[30];
struct date dob;
}stud;
struct date
{
int day,month,year;
};
scanf("%s%d%d%d", stud.rollno, &student.dob.day,
&student.dob.month, &student.dob.year);
}

Answer:
Compiler Error: Undefined structure date
Explanation:
Only declaration of struct date is available inside the structure
definition of ‘student’ but to have a variable of type struct date the
definition of the structure is required.

155) There were 10 records stored in “somefile.dat” but the following program

printed 11 names. What went wrong?


void main()
{
struct student
{
char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
{
fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}

Explanation:
fread reads 10 records and prints the names successfully. It
will return EOF only when fread tries to read another record
and fails reading EOF (and returning EOF). So it prints the
last record again. After this only the condition feof(fp)
becomes false, hence comes out of the while loop.

227
C Language

156) Is there any difference between the two declarations,


1. int foo(int *arr[]) and
2. int foo(int *arr[2])
Answer:
No
Explanation:
Functions can only pass pointers and not arrays. The numbers that
are allowed inside the [] is just for more readability. So there is no
difference between the two declarations.

157) What is the subtle error in the following code segment?


void fun(int n, int arr[])
{
int *p=0;
int i=0;
while(i++<n)
p = &arr[i];
*p = 0;
}

Answer & Explanation:


If the body of the loop never executes p is assigned no
address. So p remains NULL where *p =0 may result in
problem (may rise to runtime error “NULL pointer
assignment” and terminate the program).

158) What is wrong with the following code?


int *foo()
{
int *s = malloc(sizeof(int)100);
assert(s != NULL);

return s;
}
Answer & Explanation:
assert macro should be used for debugging and finding out bugs.
The check s != NULL is for error/exception handling and for that
assert shouldn’t be used. A plain if and the corresponding remedy
statement has to be given.

159) What is the hidden bug with the following statement?


assert(val++ != 0);
Answer & Explanation:
Assert macro is used for debugging and removed in release
version. In assert, the experssion involves side-effects. So the
behavior of the code becomes different in case of debug version
and the release version thus leading to a subtle bug.
Rule to Remember:
Don’t use expressions that have side-effects in assert statements.

160) void main()


{
int *i = 0x400; // i points to the address 400

228
C Language

*i = 0; // set the value of memory location pointed by i;


}

Answer:
Undefined behavior
Explanation:
The second statement results in undefined behavior because it
points to some location whose value may not be available for
modification. This type of pointer in which the non-availability of
the implementation of the referenced location is known as
'incomplete type'.

161) #define assert(cond) if(!(cond)) \


(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort())
void main()
{
int i = 10;
if(i==0)
assert(i < 100);
else
printf("This statement becomes else for if in assert macro");
}

Answer:
No output

Explanation:
The else part in which the printf is there becomes the else for if in the
assert macro. Hence nothing is printed.
The solution is to use conditional operator instead of if statement,
#define assert(cond) ((cond)?(0): (fprintf (stderr, "assertion failed: \ %s,
file %s, line %d \n",#cond, __FILE__,__LINE__), abort()))

Note:

However this problem of “matching with nearest else” cannot be


solved by the usual method of placing the if statement inside a
block like this,
#define assert(cond) { \
if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort()) \
}

162) Is the following code legal?


struct a
{
int x;
struct a b;
}
Answer:
No

229
C Language

Explanation:
Is it not legal for a structure to contain a member that is of the
same
type as in this case. Because this will cause the structure
declaration to be recursive without end.

163) Is the following code legal?


struct a
{
int x;
struct a *b;
}

Answer:
Yes.

Explanation:
*b is a pointer to type struct a and so is legal. The compiler knows,
the size of the pointer to a structure even before the size of the
structure
is determined(as you know the pointer to any type is of same size).
This type of structures is known as ‘self-referencing’ structure.

164) Is the following code legal?


typedef struct a
{
int x;
aType *b;
}aType
Answer:
No

Explanation:
The typename aType is not known at the point of declaring the
structure (forward references are not made for typedefs).

165) Is the following code legal?


typedef struct a aType;

struct a
{
int x;
aType *b;
};
Answer:
Yes
Explanation:
The typename aType is known at the point of declaring the
structure, because it is already typedefined.

166) Is the following code legal?


void main()

230
C Language

{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
aType *b;
};
}

Answer:
No

Explanation:
When the declaration,
typedef struct a aType;
is encountered body of struct a is not known. This is known as
‘incomplete types’.

167) void main()


{
printf(“sizeof (void *) = %d \n“, sizeof( void *));
printf(“sizeof (int *) = %d \n”, sizeof(int *));
printf(“sizeof (double *) = %d \n”, sizeof(double *));
printf(“sizeof(struct unknown *) = %d \n”, sizeof(struct unknown *));
}

Answer :
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2

Explanation:
The pointer to any type is of same size.

168) char inputString[100] = {0};


To get string input from the keyboard which one of the following is better?
1) gets(inputString)
2) fgets(inputString, sizeof(inputString), fp)
Answer & Explanation:
The second one is better because gets(inputString) doesn't know
the size of the string passed and so, if a very big input (here, more
than 100 chars) the charactes will be written past the input string.
When fgets is used with stdin performs the same operation as gets
but is safe.

169) Which version do you prefer of the following two,


1) printf(“%s”,str); // or the more curt one
2) printf(str);
Answer & Explanation:
Prefer the first one. If the str contains any format characters like
%d then it will result in a subtle bug.
170) void main()

231
C Language

{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(“%d”,k);
}

Answer:
Compiler Error: “Unexpected end of file in comment started in line
5”.

Explanation:
The programmer intended to divide two integers, but by the
“maximum munch” rule, the compiler treats the operator
sequence / and * as /* which happens to be the starting of
comment. To force what is intended by the programmer,
int k = *ip/ *jp;
// give space explicity separating / and *
//or
int k = *ip/(*jp);
// put braces to force the intention
will solve the problem.

171) void main()


{
char ch;
for(ch=0;ch<=127;ch++)
printf(“%c %d \n“, ch, ch);
}

Answer:
Implementaion dependent

Explanation:
The char type may be signed or unsigned by default. If it is signed
then ch++ is executed after ch reaches 127 and rotates back to -
128. Thus ch is always smaller than 127.
172) Is this code legal?
int *ptr;
ptr = (int *) 0x400;
Answer:
Yes
Explanation:

The pointer ptr will point at the integer in the memory location
0x400.

173) main()
{
char a[4]="HELLO";
printf("%s",a);

232
C Language

Answer:
Compiler error: Too many initializers

Explanation:
The array a is of size 4 but the string constant requires 6 bytes to
get stored.

174) main()
{
char a[4]="HELL";
printf("%s",a);
}
Answer:
HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string
“HELL” and doesnt have enough space to store the terminating null
character. So it prints the HELL correctly and continues to print
garbage values till it accidentally comes across a NULL character.

175) main()
{
int a=10,*j;
void *k;
j=k=&a;
j++;
k++;
printf("\n %u %u ",j,k);
}

Answer:
Compiler error: Cannot increment a void pointer

Explanation:
Void pointers are generic pointers and they can be used only when
the type is not known and as an intermediate address storage
type. No pointer arithmetic can be done on it and you cannot apply
indirection operator (*) on void pointers.

176) main()
{
extern int i;
{ int i=20;
{
const volatile unsigned i=30; printf("%d",i);
}
printf("%d",i);
}

233

You might also like