Jayanth C Language
Jayanth 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.
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#
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
Software : The set of programs (language, package, operating system, files, folders etc)
is known as software.
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.
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
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.
4
C Language
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
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
1) scanf(): it is used to accept the contents into the variable until it founds enter
(return) key or space symbol.
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
ex: c=a+b+10
=, + operator c,a,b,10 operands (variables, constants)
Syntax: variable=expression;
Ex: c=6 (c 6)
c=(a+b)-(d+e)/f
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
9) Unary operators:
8
C Language
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 ;
10) Other operators: in addition to these operators c++ supports many number of
operators which are used for the special purpose such as - >, .( ) , [] , ,, { } etc.,
9
C Language
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.
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
Example 2
#define NOTFINISHED 0
/**********************************************/
11
C Language
main ()
{ int i; /* declarations */
do
{
/* Nothing !!! */
}
while (NOTFINISHED);
Question
12
C Language
13
C Language
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();
}
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();
}
15
C Language
getch();
}
16
C Language
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();
}
18
C Language
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
19
C Language
}
else if (condition 2)
{
statement(s);
}
- - - - - - -
else
{
statement(s);
}
20
C Language
be used so that after executing the statements in the control terminates from the
Decision Making Statement.
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
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);
}
getch();
}
22
C Language
23
C Language
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
25
C Language
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
#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();
}
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();
}
30
C Language
goto natural;
}
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();
}
32
C Language
getch();
}
33
C Language
34
C Language
}
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
#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();
}
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();
}
37
C Language
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();
}
38
C Language
{
for(j=1;j<=i;j++)
{
printf("%5d",j);
}
printf("\n");
}
getch();
}
#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();
}
#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();
}
41
C Language
{
for(j=1;j<=i;j++)
{
printf("%d\t",j);
}
printf("\n");
}
getch();
}
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();
}
43
C Language
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
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.
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
#include<stdio.h>
#include<conio.h>
46
C Language
Void main()
int a[5],i;
clrscr();
scanf(“%d”,&a[i]);
printf(“%d \n”,a[i]);
getch();
#include<stdio.h>
#include<conio.h>
Void main()
int a[55],i,n;
clrscr();
47
C Language
scanf(“%d”,&n);
scanf(“%d”,&a[i]);
printf(“%d \n”,a[i]);
getch();
#include<stdio.h>
#include<conio.h>
void main()
int a[56],i,sum=0;
clrscr();
scanf(“%d”,&n);
48
C Language
scanf(“%d”,&a[i]);
sum=sum+a[i];
getch();
searching techniques
49
C Language
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
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);
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);
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);
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.
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 = 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;
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
{
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();
}
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..
......
....
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:
int starter,main,dessert;
{ int 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:
int starter,main,dessert;
{ int total;
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 */
/* */
/********************************************************/
#include <stdio.h>
#include <ctype.h> /* contains character utilities */
/********************************************************/
{ char ch;
for (ALLCHARS)
{
if (isalpha(ch))
{
printf ("%c ",ch);
}
62
C Language
for (ALLCHARS)
{
if (isupper(ch))
{
printf ("%c ",ch);
}
}
for (ALLCHARS)
{
if (islower(ch))
{
printf ("%c ",ch);
}
}
for (ALLCHARS)
{
if (isdigit(ch))
{
printf ("%c ",ch);
}
}
for (ALLCHARS)
{
if (isxdigit(ch))
{
printf ("%c ",ch);
}
}
for (ALLCHARS)
{
63
C Language
if (ispunct(ch))
{
printf ("%c ",ch);
}
}
for (ALLCHARS)
{
if (isalnum(ch))
{
printf ("%c ",ch);
}
}
for (ALLCHARS)
{
if (iscsym(ch))
{
printf ("%c ",ch);
}
}
}
Program Output
VALID CHARACTERS FROM isalpha()
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij
klmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
0123456789
64
C Language
0123456789ABCDEFabcdef
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
0123456789ABCDEFGHIJKLMNOPQRSTUVW
XYZabcdefghijklmnopqrstuvwxyz
0123456789ABCDEFGHIJKLMNOPQRSTUVW
XYZ_abcdefghijklmnopqrstuvwxyz
Mathematical Functions
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 */
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 */
/* */
/******************************************************/
#include <stdio.h>
#include <math.h>
#include <limits.h>
#define TRUE 1
#define AMPLITUDE 30
#define INC 0.02
/******************************************************/
/* Level 0 */
/******************************************************/
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));
/*****************************************************/
/* 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
70
C Language
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.
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
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
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 (*).
The pointer variable will be declared using * opeator in the required data type.
Syntax: <data type> *<variable>;
Example: int *p, x;
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.
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)
Pointer to arrays:
A pointer can also point to an arrays, which may be single dimensional array or
double dimensional array.
75
C Language
7 8 9
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.
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
77
C Language
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"
78
C Language
printf("string is %s\n",str);
free(str);
}
#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
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
To access the fields from a structure into the funtion use the following syntax:
syntax: var[value].field
example: s[0].sno;
81
C Language
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();
}
83
C Language
84
C Language
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.
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
};
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;
};
enum Types
{
86
C Language
INT,
FLOAT,
CHAR
};
union WhichType x;
enum Types x_status;
switch (x_status)
{
case INT : x.ordinal = 12;
break;
case FLOAT : x.continuous = 12.23;
break;
case CHAR : x.letter = '*';
}
struct Union_Handler
{
union WhichType x;
enum Types x_status;
}
var;
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");
88
C Language
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);
EOF: EOF indicated End Of File. The expression will becomes true if end of the file is
reached.
ftell(): it returns current position of file pointer as a byte number into a long integer
syntax: n=ftell(fp);
input statements
1) fgetc(): it is used read a character from the file.
ex: ch=fgetc(fp);
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);
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;
}
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);
}
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
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
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]
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();
}
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);
96
C Language
example: initgraph(&gd,&gm,"c:\\tc\\bgi");
text=24*80 pixel=480*640
syntax: sound(milliseconds);
outtextxy(): it is used to display the string in the specified row and column.
syntax: outtextxy(column,row,"string");
(or)
outtextxy(x,y,"string");
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);
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.
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);
}
}
98
C Language
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();
}
99
C Language
# include "conio.h"
# include "graphics.h"
void main()
{
int gd=DETECT,gm=0;
initgraph(&gd,&gm,"c:\\tc\\bgi");
cleardevice();
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();
}
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
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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
#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();
}
109
C Language
110
C Language
111
C Language
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();
}
113
C Language
114
C Language
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();
}
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
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();
}
#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();
}
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
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();
}
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();
}
#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();
}
130
C Language
#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();
}
132
C Language
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();
}
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();
}
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();
}
136
C Language
{
int i,j;
clrscr();
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
printf("* ");
printf("\n");
}
getch();
}
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();
}
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();
}
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();
}
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();
}
#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();
}
#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();
}
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();
}
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();
}
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();
}
#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();
}
#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();
}
#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();
}
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();
}
#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();
}
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++)
{
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
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
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();
}
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
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
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
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
165
C Language
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
#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();
}
#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();
}
#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();
}
#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
#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();
}
#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,
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:
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 :
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 :
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.
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
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.
181
C Language
Answer:
64
Explanation:
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.
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
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).
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.
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:
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.
Explanation:
Side effects are involved in the evaluation of i
185
C Language
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.
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
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;
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 –
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.
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);
}
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.
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.
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");
}
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.
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:
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:
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
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.
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
Answer:
Compiler error.
Explanation:
argv[1] & argv[2] are strings. They are passed to the function sum
without converting it to integer values.
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--);
}
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.
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.
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
Answer:
0 65535
Explanation:
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.
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
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).
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
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 !
Explanation:
The macro expands and evaluates to as:
x+2*y-1 => x+(2*y)-1 => 10
108) main()
{
210
C Language
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.
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.
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.
Answer
Definition.
213
C Language
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.
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!
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.
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.
215
C Language
{
int arr2D[3][3];
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.
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
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.
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.
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.
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
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.
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
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
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
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.
228
C Language
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'.
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:
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.
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.
Explanation:
The typename aType is not known at the point of declaring the
structure (forward references are not made for typedefs).
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.
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’.
Answer :
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2
Explanation:
The pointer to any type is of same size.
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.
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