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

C-Programing by Pankaj Sir

Uploaded by

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

C-Programing by Pankaj Sir

Uploaded by

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

PROGRAMMING IN C

FOR
[ B. Tech., B.Sc. and Diploma]

Pankaj Kapoor Soniya Kapoor


(Assistant Professor) (Assistant Professor)
M.Tech., Kurukshetra University M.Tech., J.M.I.T., Raduar

B HARAT P UBLICATIONS
5A/12, Ground Floor, Ansari Road, Darya Ganj, New Delhi - 110002
B.O. 135-A, Santpura Road, Yamuna Nagar - 135001 (Haryana)
Phone: 01732-227178, 232178, +91-9416227140
Email: [email protected]
© Reserved with the publisher

All rights reserved. No part of this publication may be reproduced, stored in


a retrieval system or transmitted, in any form or by any means, electronic,
mechanical, photocopying, recording or otherwise, without the prior
permission of the publisher.

Dedicated to our Beloved Parents

ISBN– 13:978–93–81252–20 –7

First Edition : 2013-14

Price : Rs. 300/-

Publishing by : BHARAT PUBLICATIONS

Laser Type-setting by : Shri Balaji Graphics, Delhi

Legal Warning : The publisher has taken all possible precautions in publishing this book, in spite of al the efforts some errors might have
crept in. Any mistake, error or discrepancy noted may be brought to our knowledge which shall be taken care of in the next edition. It is
notified that neither the publisher nor the book seller or the author will be responsible for any damage or loss of action to anyone, of any kind,
in any manner, therefrom. For missing pages or misprints the publisher takes responsibility to exchange within 15 days of purchase of hte
same edition. All costs in this connection are to be borne by the purchaser.

(ii)
Introduction to C 1
1.1 OVERVIEW OF C PROGRAMMING
C language is one of the most popular computer languages today because it is
a structured, high level, machine independent language. It allows software developers
to develop programs without worrying about the hardware platforms where they will
be implemented. C is called a high level, compiler language. The aim of any high
level computer language is to provide an easy and natural way of giving a programme
of instructions to a computer.
C is one of a large number of high level languages which can be used for
general purpose programming, i.e., anything from writing small programs for personal
amusement to writing complex applications. It is unusual in several ways. Before C,
high level languages were criticized by machine code programmers because they
shielded the user from the working details of the computer. The C language has
been equipped with features that allow programs to be organized in an easy and
logical way. This is vitally important for writing lengthy programs because complex
problems are only manageable with a clear organization and program structure.
C allows meaningful variable names and meaningful function names to be used
in programs without any loss of efficiency and it gives a complete freedom of style,
it has a set of very flexible loop constructions and neat ways of making decisions.
These provide an excellent basis for controlling the flow of programs. Another
feature of C is the way it can express ideas concisely. The richness of a language
shapes what it can talk about. C gives us the apparatus to build neat and compact
programs. C tries to make the best of a computer by linking as closely as possible to
the local environment.
The increasing popularity of C is probably due to its many desirable qualities.
It is a robust language whose rich set of built-in functions and operators can be used
to write any complex program. The C compiler combines the capabilities of an
assembly language with the features of a high-level language and therefore it is well
suited for writing both system software and business packages. Programs written in
C are efficient and fast. This is due to its variety of data types and powerful operators.
C is highly portable. This means that C programs written for one computer can be
run on another with little or no modification. Another feature of C is its ability to
extend itself.
Development of "C" (Introduction and history)
"C" is a programming language developed at AT & T Bell Laboratories of USA
in 1972. It was developed Dennis Ritche in late 1970’s. it began to replace the
more familiar languages of that time like PL/1, ALGOL etc.

1.1
1.2 Programming in C

1. "C" became popular because of its reliability, simple and easy to use.
2. It was friendly capable and reliable
3. ALGOL60 was developed and did not become popular because it was too
general and too abstract.
4. They developed "CPL" (Combined Programming Language)
5. Next as it could not come up to make ALGOL 60 better one they moved to
"BCPL" (Basic Combines Programming Language. Developed by martin
Richard Cambridge university)
6. At the same time a language called "B" written by ken Thompson at AT &
Ts’. Bell laboratories as a further simplification of BCPL.
7. "C" s compactness and coherence is mainly due to its one main language.
e.g., LISP.

Year Language Developed by Remarks

1960 ALGOL International Group Too general, too abstract


1963 CPL D.W. Barron Hard to Learn & implementation
1967 BCPL Martin Richards Could deal only special problem
1970 B Ken Thomson Could deal only special problem
1972 C Denis Ritchie Lost Generality of BCPL, B restored

Note: C is a middle level language because it was due to have both a relatively good
programming efficiency and relativity good machine efficiency.

Features of "C" Language


1. It is robust language because of rich set of built-in functions.
2. It is efficient and fast because of its variant data-types and powerful operation.
3. It is highly Portable i.e., programs written in one computer can be run on
another.
4. It is well suited for structure program, thus allows the user to think about the
problem in the terms of functional blocks.
5. Debugging, testing and maintenance is easy.
6. Ability to extend itself, we can continuously add our own functions to the
program.

Application Of C Programming
C Programming is best known programming language. C Programming is
near to machine as well as human so it is called as Middle level Programming
Language. C Programming can be used to do verity of tasks such as networking
related, OS related.
Application of C Programming are listed below :
1. C language is used for creating Computer Applications.
2. Used in writing Embedded software's.
3. Firmware for various electronics, industrial and communications products
which use micro-controllers.
Introduction to C 1.3

4. It is also used in developing Verification Software, Test Code, Simulators


etc. for various applications and hardware products.
5. For Creating Compiles of different Languages which can take input from
other language and convert it into lower level machine dependent
language.
6. C is used to implement different Operating System Operations.
7. UNIX kernel is completely developed in C Language.

1.2 BASIC STRUCTURE OF A C PROGRAM


The structure of a C program is a protocol (rules) to the programmer, while
writing a C program. The general basic structure of C program is shown in the
Fig. 1.1. The whole program is controlled within main ( ) along with left brace
denoted by "{" and right braces denoted by "}". If you need to declare local variables
and executable program structures are enclosed within "{" and "}" is called the body
of the main function. The main ( ) function can be preceded by documentation,
preprocessor statements and global declarations.

Documentation

Pre process or statements

Global declarations

Main ( )
{
Local declarations
Program statements Body of the
Main ( ) function
Calling user defined functions (option to user)
}
User defined functions
Function 1
(Option to user)
Function 2
Function n

Fig. 1.1.

Preprocessor Statements
The preprocessor statement begins with # symbol and is also called the
preprocessor directive. These statements instruct the compiler to include C
preprocessors such as header files and symbolic constants before compiling the C
program. Some of the preprocessor statements are listed below.
#include<studio.h> 
#include<math.h> 
#include<studio.h>  header files

#include<CONIO.h> 
1.4 Programming in C

#define P L 3.1412. 
#define TRVE 1  symbolic constat
#define FALSE 0 
Global Declarations
The variables are declared before the main ( ) function as well as user defined
functions are called global variables. These global variables can be accessed by all the
user defined functions including main ( ) function.
The main ( ) function
Each and Every C program should contain only one main ( ). The C program
execution starts with main () function. No C program is executed without the main
function. The main ( ) function should be written in small (lowercase) letters and it
should not be terminated by semicolon. Main ( ) executes user defined program
statements, library functions and user defined functions and all these statements
should be enclosed within left and right braces.
Braces
Every C program should have a pair of curly braces ({ }). The left braces
indicates the beginning of the main ( ) function and the right braces indicates the end
of the main ( ) function. These braces can also be used to indicate the user-defined
functions beginning and ending. These two braces can also be used in compound
statements.
Local Declarations
The variable declaration is a part of C program and all the variables are used in
main ( ) function should be declared in the local declaration section is called local
variables. Not only variables, we can also declare arrays, functions, pointers etc.
These variables can also be initialized with basic data types. For example :
Code:
main ( )
{
int sum = 0;
float y;
}
Here, the variable sum is declared as integer variable and it is initialized to
zero. Other variables declared as int and float and these variables inside any function
are called local variables.

Program statements
These statements are building blocks of a program. They represent instructions
to the computer to perform a specific task (operations). An instruction may contain
an input-output statements, arithmetic statements, control statements, simple
assignment statements and any other statements and it also includes comments
that are enclosed within /* and */ . The comment statements are not compiled and
executed and each executable statement should be terminated with semicolon.
Introduction to C 1.5

User defined functions


These are subprograms, generally, a subprogram is a function and these
functions are written by the user are called user-defined functions. These functions
are performed by user specific tasks and this also contains set of program statements.
They may be written before or after a main () function and called within main ()
function. This is an optional to the programmer.
Now, let us write a small program to display some message shown below.

Code:
#include <stdio.h>
main()
{
printf ("welcome to the world of C/n");
}

1.3 STEP BY STEP EXECUTION OF C PROGRAM


Step 1: Edit
1. This is First Step i.e. Creating and Editing Program.
2. First Write C Program using Text Editor, such as
[ Borland C/C++ 3.0, Notepad++, Notepad ]
3. Save Program by using [.C] Extension.
4. File Saved with [.C] extension is called "Source Program".
Step 2: Compiling
1. Compiling C Program: C Source code with [.C] Extension is given as input
to compiler and compiler converts it into Equivalent Machine Instruction.
2. In Borland C/C++ 3.0 program can be compiled using key [Alt + F9].
3. Compiler Checks for errors. If source code is error-free then Code is converted
into Object File [.Obj].

Step 3: Checking Errors


1. During Compilation Compiler will check for error, If compiler finds any error
then it will report it.
2. User has to re-edit the program.
3. After re-editing program, Compiler again check for any error.
4. If program is error-free then program is linked with appropriate libraries.

Step 4: Linking Libraries


1. Program is linked with included header files.
2. Program is linked with other libraries.
3. This process is executed by Linker.
Step 5: Executing
1. ALT+F5 to run the program. If run time error occurs then "Run-time"
errors are reported to user.
2. Again programmer has to review code and check for the solution.
1.6 Programming in C

Editing
Create/modify
program source code

Source File
Compiling (*.c)

Generate machine
instructions

Yes
Error? Object File
(*.obj)

No
Linking
Link in
libraries, etc.

Yes
Error? Executable File
(*.exe)

No
Executing

Run program

Yes
Error?

No

Complier
This reads the entire source program and converts it to the object code. It
provides error not of one line, but errors of the entire program. It executes as a
whole and it is fast
Interpreter
It reads only one line of a source program at a time and converts it into an
object code. In case of errors/same will be indicated instantly. It executes line by line
and it is slow.
Introduction to C 1.7

Linker is a function which links up the files that present in the operating system,
it also links the files for the hardware and makes the system ready for executing.

Preprocessor
This is a program that processes the source program before it is passed on to
the compiler. The program typed in the editor is the source code to the preprocessor,
and then it passed the source code to the compiler. It is not necessary to write
program with preprocessor & activity
Preprocessor directories are always initialized at the beginning of the program.
It begins with the symbol (#) hash. It place before the main() function
e.g.,
# include <station>
# define PI 3.14
Header Files
Header files contain definitions of functions and variables which can be
incorporated into any C program by using the pre-processor #include statement.
Standard header files are provided with each compiler, and cover a range of areas,
string handling, mathematical, data conversion, printing and reading of variables.
To use any of the standard functions, the appropriate header file should be
included. This is done at the beginning of the C source file. For example, to use the
function printf() in a program, the line
#include <stdio.h>

should be at the beginning of the source file, because the definition for printf() is
found in the file “stdio.h” All header files have the extension .h and generally
reside in the /include subdirectory.
#include <stdio.h>
#include "mydecls.h"

The use of angle brackets <> informs the compiler to search the compilers
include directory for the specified file. The use of the double quotes “” around the
filename inform the compiler to search in the current directory for the specified file.

A Simple C Program
The following program is written in the C programming language :
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
}
A Note about C Programs
In C, lowercase and uppercase characters are very important! All commands in
C must be lowercase. The C programs starting point is identified by the word
main()
1.8 Programming in C

This informs the computer as to where the program actually starts. The brackets
that follow the keyword main indicate that there are no arguments supplied to this
program (this will be examined later on).
The two braces, { and }, signify the begin and end segments of the program.
The purpose of the statement
include <stdio.h>
is to allow the use of the printf statement to provide program output. Text to
be displayed by printf() must be enclosed in double quotes. The program has only
one statement
printf("Programming in C is easy.\n");
print f() is actually a function (procedure) in C that is used for printing variables
and text. Where text appears in double quotes "", it is printed without modification.
There are some exceptions however. This has to do with the \ and % characters.
These characters are modifiers, and for the present the \ followed by the n character
represents a newline character. Thus the program prints
Programming in C is easy.
and the cursor is set to the beginning of the next line. As we shall see later on, what
follows the \ character will determine what is printed, i.e., a tab, clear screen, clear
line etc. Another important thing to remember is that all C statements are terminated
by a semi-colon ;

1.4 CHARACTERISTICS OF C
We briefly list some of C's characteristics that have lead to its popularity as a
programming language and define the language. Naturally we will be studying many
of these aspects throughout our tutorial.
q Extensive use of function calls
q Small size
q Loose typing - unlike PASCAL
q Structured language
q Low level (Bitwise) programming readily available
q Pointer implementation - extensive use of pointers for memory, array,
structures and functions.
C has now become a widely used professional language for various reasons.
q It has high-level constructs.
q It produces efficient programs.
q It can handle low-level activities.
q It can be compiled on a variety of computers.
The main drawback of c is that it has poor error detection which can make it
off putting to the beginner. However diligence in this matter can pay off handsomely
since having learned the rules of the C we can break them. Not all languages allow
this. This if done carefully and properly leads to the power of C programming.
Introduction to C 1.9

1.5 CHARACTER SET


The characters that can be used to form words and expressions depends upon
the computer to which the program is run. The Characters in C are:
1. Letters A-X, a-z, both upper and lower
2. Digits 0-9
3. Special character, +,-,*,",;,./,
4. White spaces newline, horizontal tab, carriage return, blank space.

“C” Basic Building Blocks and Definition


Token Meaning

Keyword A variable is a meaningful name of data storage location in


computer memory. When using a variable you refer to memory
address of computer

Constant Constants are expressions with a fixed value

Identifier The term identifier is usually used for variable names

String Sequence of characters

Special Symbol Symbols other than the Alphabets and Digits and white-spaces
Operators A symbol that represent a specific mathematical or non
mathematical action

"C" Tokens
Individual words and punctuation marks are characters. In a "C" program the
smallest individual units are known as "C" tokens. It has 6 types of tokens.

Keywords

Constants

Identifier
Tokens
Strings

Special
Symbols

Operators

Keywords
Keywords are reserved words by compiler. Keywords are assigned with fixed
meaning and they cannot be used as variable name. No header file is needed to
include the keywords.
1.10 Programming in C

There are 32 keywords e.g., auto, break, double, int, float.

Auto Double Int Struct


Break Else Long Switch
Case Enum Register Typedef
Char Extern Return Union
Const Float Short Unsigned
Continue For Signed Void
Default Goto Sizeof Volatile
Do If Statie while

Identifiers
Identifiers are names of variables, functions, and arrays. They are user-defined
names, consisting sequence of letters and digits, with the letter as the first character.
e.g.,
# define NUM 10
int A 20;
"NUM", "A" are user - defined id.

Constants
Constants in "C" are applicable to the values which not change during the
execution of a program. C constants can be divided into two major categories:
1. Primary Constants
2. Secondary Constants.
These constants are further categorized as shown in Fig. 1.2.

C Constant

Primary Constant Secondary Constants

Integer Constant Array


Real Constant Pointer
Character Constant Structure
Union
Enum. etc.

Fig. 1.2. C constants.


(a ) Integer Constants: Sequence of number 0-9 without decimal points,
fractional part or any other symbols. It requires two or four bytes, can be
+ve, -ve or Zero the number without a sign is as positive.
e.g., -10, +20, 40
Introduction to C 1.11

(b) Real Constants: Real constants are often known as floating constants.
e.g., 2.5, 5.521, 3.14 etc.
(c) Character Constants: A single character constants are given within a
pair of single quote mark. The sequence of characters within double
quote marks is called String Constant.
e.g., 'a', '8', "Straight", "India", "4", etc.
Variables
This is a data name used for storing a data, its value may be changed during
the execution. The variables value keeps changing during the execution of the
program.
e.g., height, average, sum, etc.

1.6 DATA TYPES


C language is rich in data types. American National Standard Institute.
C supports three classes of data types :
1. Primary data type (fundamental)
2. Derived data types
3. User defined data types.
All "C" compilers support 5 fundamental primitive data types
1. Integer (int)
2. Character (char)
3. Floating point (float)
4. Double-precession (double)
5. void

Data Type Bytes in RAM Ranges of data type


Char 1 bytes -128 to 127
Int 2 bytes -32, 768 to 32,767
float 4 bytes 1.2E-38 to 3.4E+38 (6 Decimal Places)
double 8 bytes 2.3E-308 to 1.7E+308 (15 Decimal Places)

Integer Types: Integers are whole numbers with a range of variables supported
by a particular machine. In a signed integer uses one bit for sign and 15 bits for
magnitude C has three classes of integer storage
1. short int
2. int
3. long int
It has a set of qualifiers i.e.,
1. sign qualifier
2. unsigned qualifier.
short int uses half the range of storage amount of data, unsigned int use all the
bits for the magnitude of the number and are positive.
1.12 Programming in C

Type Storage size Value range Format


signed char 1 byte -128 to 127 %c
unsigned char 1 byte 0 to 255 %c
short signed int 2 bytes -32,768 to 32,767 %d
short unsigned int 2 bytes 0 to 65,535 %u
Signed int 2 bytes -32,768 to 32,767 %d
unsigned int 2 bytes 0 to 65,535 %u
long signed int 4 bytes -2,147,483,648 to 2,147,483,647 %ld
long unsigned int 4 bytes 0 to 4,294,967,295 %ul

Character Data type: Characters are usually stored in 8 bits


Floating Point Type: Floating Point numbers are stored with 6 digits of
precision. Those are defined with keyword float. When the accuracy is not sufficient
then the data type double can be used. Double gives a precession of 15 digits these
known as double precession numbers. Still for a better process we can use long
double which uses 80 bits and gives a precession of 19 digits.
1. float
2. double
3. long double

Type Storage size Value range Precision


Float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
Double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

void data type: A void type has no value this is usually used to specify the
return type of function, this function does not return any value to calling function.

1.7 VARIABLE DECLARATION IN C


All variables must be declared before we use them in C program, although
certain declarations can be made implicitly by content. A declaration specifies a
type, and contains a list of one or more variables of that type as follows:
type variable_list;
Here, type must be a valid C data type including char, int, float, double, or any
user defined data type etc., and variable_list may consist of one or more identifier
names separated by commas. Some valid variable declarations along with their
definition are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
Introduction to C 1.13

You can initialize a variable at the time of declaration as follows:


int i = 100;
An extern declaration is not a definition and does not allocate storage. In
effect, it claims that a definition of the variable exists somewhere else in the program.
A variable can be declared multiple times in a program, but it must be defined only
once. Following is the declaration of a variable with extern keyword:
extern int i;

Variable Initialization in C
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is:
variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly otherwise,
sometime program would produce unexpected result. Try following example which
makes use of various types of variables:
#include <stdio.h>

int main ()
{
/* variable declaration: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of c : 30
value of f : 23.333334
1.14 Programming in C

Lvalues and Rvalues in C


There are two kinds of expressions in C:
1. lvalue: An expression that is an lvalue may appear as either the left-
hand or right-hand side of an assignment.
2. rvalue: An expression that is an rvalue may appear on the right- but not
left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so may not be assigned and cannot appear on the
left-hand side. Following is a valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10 = 20;

PROGRAMS EXAMPLES
PROGRAM 1.1 : To Find Sum and Average of Three Real Numbers
#include <stdio.h>
main()
{
float a, b, c, sum, avg;
printf("\nEnter value of three numbers: ");
scanf("%f %f %f", &a, &b, &c);

sum = a + b + c;
avg = sum / 3;

printf("\nSum = %.2f", sum);


printf("\nAverage = %.2f",avg);
getch();
}
PROGRAM 1.2 : To Accept Student Roll No, Marks in 3 Subjects and
Calculate Total, Average and Print it.
#include <stdio.h>
#nclude <conio.h>
main()
{ int r,b,c,d, tot, avg;
clrscr();
printf ("ENTER STUDENT RNO ; ");
scanf ("%d",&r);
printf("ENTER FIRST SUBJECT MARKS ;");
scanf("%d",&b);
printf("ENTER SECOND SUBJECT MARKS;");
scanf("%d",&c);
printf("ENTER THIRD SUBJECT MARKS ;");
scanf("%d",&d);
tot=b+c+d;
avg=tot/3;
printf("\n\n\t\t VIDYARTHI COMPUTERS - HANAMAKONDA \n\n");
Introduction to C 1.15

printf("\t STUDENT RNO ; %d ",r);


printf("\t FIRST SUBJECT MARKS ;%d ",b);
printf("\t SECOND SUBJECT MARKS ;%d ",C);
printf("\t THIRD SUBJECT MARKS ;%d ",d);
printf("\t AVERAGE MARKS ; %d", avg);
getch();
}
?
PROGRAM 1.3 : To Convert Temperature from Degree Centigrade
to Fahrenheit
f = (1.8*c) + 32

#include <stdio.h>
main()
{
float c, f;
printf("\nEnter temperature in degree Centigrade: ");
scanf("%f", &c);

f = (1.8*c) + 32;

printf("\n\nTemperature in degree Fahrenheit: %.2f", f);


getch();
}
PROGRAM 1.4 : To find Simple Interest and Compound Interest
SI = (p * r * t) / 100
CI = p * pow((1 + r/100), t) - p

#include <stdio.h>
#include <math.h>
main()
{
float p, r, t, si, ci;

printf("\nEnter priciple, rate and time: ");


scanf("%f %f %f", &p, &r, &t);

si = (p * r * t) / 100;
ci = p * pow((1 + r/100), t) - p;

printf("\n\nSimple Interest: %.2f", si);


printf("\n\nCompound Interest: %.2f", ci);
getch();
}

PROGRAM 1.5 : To find the area of circle


#include <stdio.h>
#define PI 3.141
int main(){
float r, a;
1.16 Programming in C

printf("Radius: ");
scanf("%f", &r);
a = PI * r * r;
printf("%f\n", a);
return 0;
}

PROGRAM 1.6 : To find the area of any triangle.


Area = v(s*(s-a)*(s-b)*(s-c))
Where s = (a + b + c)/2

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

int main(){

float a,b,c;
float s,area;

printf("Enter size of each sides of triangle");


scanf("%f%f%f",&a,&b,&c);

s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));

printf("Area of triangle is: %.3f",area);

return 0;
}
PROGRAM 1.7 : To find the surface area of cube.
Surface area = 6 * a2

Formula of volume of cube: Volume = a3


#include<stdio.h>

int main(){

float a;
float surface_area,volume;

printf("Enter size of any side of a cube : ");


scanf("%f",&a);

surface_area = 6 * (a * a);
volume = a * a * a;
printf("Surface area of cube is: %.3f",surface_area);
printf("\nVolume of cube is : %.3f",volume);

return 0;
}
Introduction to C 1.17

PROGRAM 1.8 : To Swap Values of Two Variables using Third Variable


#include <stdio.h>

main()
{
int a, b, temp;

printf("\nEnter any two numbers: ");


scanf("%d %d", &a, &b);

printf("\n\nBefore Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);

temp = a;
a = b;
b = temp;

printf("\n\nAfter Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);
getch();
}

PROGRAM 1.9 : To Swap Values of Two Variables Without using


3rd Variable
#include <stdio.h>

main()
{
int a, b, temp;

printf("\nEnter any two numbers: ");


scanf("%d %d", &a, &b);

printf("\n\nBefore Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);

a = a + b;
b = a - b;
a = a - b;

printf("\n\nAfter Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);
getch();
}

1.8 OPERATORS
An expression is a sequence of operators and operands that specifies
computation of a value, or that designates an object or a function, or that generates
side effects, or that performs a combination thereof.
1.18 Programming in C

Arithmetic Operators: The symbols of the arithmetic operators are:

Operation Operator Comment Value of Value of


Sum before Sum after
Multiply * sum = sum * 2; 4 8
Divide / sum = sum / 2; 4 2
Addition + sum = sum + 2; 4 6
Subtraction – sum = sum – 2; 4 2
Increment ++ ++sum; 4 5
Decrement -- --sum; 4 3
Modulus % sum = sum # 3; 4 1

Example:
#include <stdio.h>
main()
{
int sum = 50;
float modulus;

modulus = sum % 10;


printf("The %% of %d by 10 is %f\n", sum, modulus);
}

Pre/Post Increment/Decrement Operators


PRE means do the operation first followed by any assignment operation. POST
means do the operation after any assignment operation. Consider the following
statements
++count; /* PRE Increment, means add one to count */
count++; /* POST Increment, means add one to count */

Example:
#include <stdio.h>
main()
{
int count = 0, loop;

loop = ++count; /* same as count = count + 1; loop = count; */


printf("loop = %d, count = %d\n", loop, count);

loop = count++; /* same as loop = count; count = count + 1; */


printf("loop = %d, count = %d\n", loop, count);
}
If the operator precedes (is on the left hand side) of the variable, the operation
is performed first, so the statement
loop = ++count;
really means increment count first, then assign the new value of count to loop.
Introduction to C 1.19

The Relational Operators


These allow the comparison of two or more variables.
== equal to
!= not equal
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Example:
#include <stdio.h>
main()/*Program introduces the for statement, counts to ten*/
{
int count;
for( count = 1; count <= 10; count = count + 1 )
printf("%d ", count );
printf("\n");
}

Logical Operator (AND, NOT, OR)


Combining more than one condition: These allow the testing of more
than one condition as part of selection statements. The symbols are :
LOGICAL AND &&
Logical and requires all conditions to evaluate as TRUE (non-zero).
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
Logical not negates (changes from TRUE to FALSE) a condition.
Example:
#include <stdio.h>
main()
{
int number;
int valid = 0;
while( valid == 0 ) {
printf("Enter a number between 1 and 10 -->");
scanf("%d", &number);
if( (number < 1 ) && (number > 10) ){
printf("Number is outside range 1-10. Please re-
enter\n");
valid = 0;
}
else
valid = 1;
}
printf("The number is %d\n", number );
}
1.20 Programming in C

Example: The following program uses an if statement with logical AND to


validate the users input to be in the range 1-10. (Logical NOT)
#include <stdio.h>
main()
{
int flag = 0;
if( ! flag ) {
printf("The flag is not set.\n");
flag = ! flag;
}
("The value of flag is %d\n", flag);
}
Example: Consider where a value is to be inputted from the user, and checked
for validity to be within a certain range, lets say between the integer values 1 and
100. (Logical OR)
#include <stdio.h>
main()
{
int number;
int valid = 0;
while( valid == 0 ) {
printf("Enter a number between 1 and 100");
scanf("%d", &number );
if( (number < 1) || (number > 100) )
printf("Number is outside legal range\n");
else
valid = 1;
}
printf("Number is %d\n", number );
}
PROGRAM 1.10 : To accept a year and check whether the given year
is leap year or not.
#include <stdio.h>
#include <conio.h>
main( )
{
int y;
clrscr( );
printf("enter a year:");
scanf("%d",&y);
if(y%4==0& &y%100!=0|| y%400==0);
printf("the above given year IS a leap year");
else
printf("the above given year IS not a leap year");
getch();
}
Introduction to C 1.21

Output:
enter a year:2004
the above given year IS a leap year

The Conditional Expression Operator or Ternary Operator


This conditional expression operator takes THREE operands. The two symbols
used to denote this operator are the ? and the :. The first operand is placed before
the ?, the second operand between the ? and the :, and the third after the :. The
general format is,
condition ? expression1 : expression2
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the
result of the evaluation becomes the result of the operation. If the condition is
FALSE (zero), then expression2 is evaluated and its result becomes the result of the
operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
If x is less than zero then s = -1
If x is greater than zero then s = x * x

Example:
#include <stdio.h>
main()
{
int input;

printf("I will tell you if the number is positive,


negative or zero!"\n");
printf("please enter your number now--->");
scanf("%d", &input );
(input < 0) ? printf("negative\n") : ((input > 0) ?
printf("positive\n") : printf("zero\n"));
}

PROGRAM 1.11 : To find biggest of two no by using ternary numbers :


# include <stdio.h>
# include <conio.h>
main( )
{
int a,b,big;
clrscr( );
printf("enter value a");
scanf("%d",&a);
printf("enter the value of b");
scanf("%d",&b);
big=(a>b)?a:b;
1.22 Programming in C

printf("biggest of the given numbers IS %d",big);


getch();
}

PROGRAM 1.12 : Tto accept a year and check the given year is leap or
not by using ternary:
# include <stdio.h>
# include <conio.h>
main( )
{
int y,leap;
clrscr( );
printf("enter any yr");
scanf("%d",&y);
leap=(y%400= =0)?:(y%100!=0)?(y%4= =0)?1:0:0;
if(leap= =1)
printf(" the given year is leap year");
else
printf("given year is not leap year);
getch( );
}?

Bit Operations
C has the advantage of direct bit manipulation and the operations available
are,

Operation Operator Comment Value of Value of


Sum before Sum after
AND & sum = sum & 2; 4 0
OR | sum = sum|2 4 6
Exclustive OR ^ sum = sum ^2; 4 6
I′s Complement ~ sum = ~ sum; 4 -5
Left Shift << sum = sum <<2; 4 16
Right Shift >> sum = sum >>2; 4 1

Example:
/* Example program illustrating << and >> */
#include <stdio.h>
main()
{
int n1 = 10, n2 = 20, i = 0;

i = n2 << 4; /* n2 shifted left four times */


printf("%d\n", i);
i = n1 >> 5; /* n1 shifted right five times */
printf("%d\n", i);
}
Introduction to C 1.23

Example:
/* Example program using EOR operator */
#include <stdio.h>
main()
{
int value1 = 2, value2 = 4;

value1 ^= value2;
value2 ^= value1;
value1 ^= value2;
printf("Value1 = %d, Value2 = %d\n", value1, value2);
}
Example:
/* Example program using AND operator */
#include <stdio.h>
main()
{
int loop;
for( loop = 'A'; loop <= 'Z'; loop++ )
printf("Loop = %c, AND 0xdf = %c\n", loop, loop & 0xdf);
}

PROGRAM 1.13 : C programming code to swap using bitwise XOR :


#include <stdio.h>
int main()
{
int x, y;
scanf("%d%d", &x, &y);
printf("x = %d\ny = %d\n", x, y);

x = x ^ y;
y = x ^ y;
x = x ^ y;

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


return 0;
}

1.9 OPERATOR PRECEDENCE AND ASSOCIATIVITY


C Programming supports wide range of Operators. While Solving the Expression
we must follow some rules, Example: while Solving the expression [ a + b *c ] , we
should first perform Multiplication Operation and then Addition . Similarly in order
to solve such complicated expression you should have hands on Operator Precedence
and Associativity of Operators.

Operator Precedence and Associativity


C operators have two properties: Priority and Associativity. When an
expression has more than one operator then it is the relative priorities of the operators
with respect to each other that determine the order in which expression will be
evaluated. Associativity defines the direction in which the operator having same
precedence acts on the operands. It can be either left-to-right or right-to-left. Priority
is given precedence over associativity to determine the order in which the expressions
1.24 Programming in C

are evaluated. Associativity is then applied, if the need arises. Precedence of the
Operator and Associativity are Listed in the following table and this table is summarized
in decreasing Order of Priority i.e., topmost operator has highest priority and
bottommost operator has lowest priority.
Precedence of the Operator are Listed in the Following Table and This Table is
Summarized in decreasing Order of Priority i.e., Topmost Operator has Highest
Priority and Bottommost Operator has Lowest Priority.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type) * & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = +,= -,= *,= /,= %,= >>,= <<,= &,= ^,= |,= Right to left
Comma , Left to right

Operator Procedure and Associativity


Notes:
1. Comma Operator Has Lowest Precedence.
2. Unary Operators are Operators having Highest Precedence.
3. Sizeof is Operator not Function.
4. Operators sharing Common Block in the Above Table have Equal Priority or
Precedence.
5. While Solving Expression, Equal Priority Operators are handled on the basis of
FIFO [First in First Out] i.e., Operator Coming First is handled First.

1.10 TYPE CONVERSION AND TYPECASTING


All the expression involved data of the same type; but what happens when
expression involve two different data types, such as multiplying a floating point
number and an integer? Such types of situation are handled either through type
conversion or typecasting.
Type conversion and typecasting of variables refer to changing a variable of
one type into another. Type conversion is done implicitly whereas typecasting has
to be done explicitly by the programmer. We will discuss both of them in this section.
Introduction to C 1.25

Type Conversion
Type conversion is done while evaluating expressions, the compiler breaks
each expression down into individual sub-expressions. Typically, these sub-expressions
involve a unary or binary operator and some operands. Most binary operators require
their operands to be of the same type. If operands of mixed types are used, the
compiler will convert one operand to agree with the other. To do this, it uses a
hierarchy of data types:

High Level
long double

double

float

unsigned long int

long int

long int

Unsigned int

int

short char
Lower Level

Type conversion is done automatically by the compiler whenever data from


different types is intermixed. When a value from one type is assigned to another
type, the compiler implicitly converts the value into a value of the new type. For
example:
double dValue = 3; // implicit conversion to double value 3.0
int nValue = 3.14156; // implicit conversion to integer value 3
In the above example, the value 3 is promoted to a double value and then
assigned to dValue. The compiler will not complain about doing this. This is known
as promotion. (when a lower level data type is promoted to a higher level).
In some cases, when an integer is converted into a floating point number, the
resulting floating point may not exactly match the integer value. This is because
floating point number format is used internally by the computer cannot accurately
match represent every possible integer. the loss of accuracy because if this feature
would always be insufficient for the final result. Let us summarize how promotion is
done:
q float operands are converted to long.
q char or short operands hether signed or unsigned are converted to int.
q if any operand is double, the other operand is also converted to double.
Hence, the result is also type of double.
q if any operand is long, the other operand is also converted to long.
Hence, the result is also type of long.
1.26 Programming in C

However, some type conversions are inherently unsafe, and if the compiler
can detect that an unsafe conversion is being implicitly requested, it will issue a
warning.
float f =3.5;
int i;
i=f;
In the second example, the fractional part of the double value (3.5) is dropped
to (3) because integers can not support fractional values. Because converting a double
to an int usually causes data loss (making it unsafe). Other unsafe conversions involve
assigning unsigned variables to signed variables (and vice-versa), and assigning long
integers (eg. a 4-byte long) to integer variables of a smaller size (eg. a 2-byte short).
Similarly if we convert an int to a short int or int to char, the compiler just drops the
extra bits.
Thus, we can observe the following changes that are unavoidable when
performing type conversion.
q When a float value is converted to an integer value, the fractional part is
truncated.
q When a double value is converted to a float value, the rounding of digit
is done.
q When a long int value is converted to an int value, the excess higher
order bits are dropped.

Typecasting
Typecasting is also known as forced conversion. Casting represents a request
by the programmer to do an explicit type conversion. It is done when the value of
higher data type has to be converted into the value of lower data type. However, this
cast is under the programmer’s control and not under the compiler’s control. For
example if we need to explicitly type cast a floating variable into an integer variable.
In standard C programming, casts are done via the () operator, with the name of the
type to cast to inside. For example:
float salary = 10000.00;
int sal;
sal = (int)salary;
As we see in the code, typecasting can be done by placing the destination data
type in parentheses followed by the variable name that has to be converted. Hence,
we conclude that typecasting is done to make a variable of one data type to act like
a variable of another type.
We can also typecast integer values to its character equivalent (as per ASCII
code) and vice-versa. Type casting is also done in arithmetic operation to get correct
result. For example, when dividing two integers, the result can be of floating type.
Also, when multiplying two integers the result can be of ling. So, to get correct
precision value, typecasting can be done. For instance,
int a = 500, b = 70;
float res;
res = (float) a / b;
Let us look at some more examples of typecasting.
q res = ( int) 9.5
9.5 is converted to 9 by truncating and then assigned to res.
Introduction to C 1.27

q res = (int) 12.3 / (int) 4.2


it is equivalent as 12 / 4 and the value 3 is assigned to res.
q res = (double) total / n;
total is converted to double and then division is done in floating point
mode.
q res = (int) a + b;
a is converted to integer and then add with b.
q res = cos ( (double) x );
it converts x to double before finding its cosine.

PROGRAM 1.14 : Write a program to convert a floating point number


into the corresponding integer.
#include<stdio.h>
#include<conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf(“\nEnter any floating point number”);
scanf(“%f”, &f_num);
i_num = (int) f_num;
printf(“\n The integer variant of %f is = %d”,
f_num,i_num);
return 0;
}
Write a program to convert an integer into the correspond-
ing floating point number.
#include<stdio.h>
#include<conio.h>
int main()
{
float f_num;
int i_num;
clrscr();
printf(“\nEnter any integer”);
scanf(“%d”, &i_num);
f_num = (float) i_num;
printf(“\n The floating point variant of %d is = %f”,
i_num,f_num);
return 0;
}

KEY POINTS TO REMEMBER


t C is a programming language developed at AT & T Bell Laboratories of
USA in 1972. It was developed Dennis Ritche.
t C became popular because of its reliability, simple and easy to use. It is
efficient and fast because of its variant data-types and powerful operation.
1.28 Programming in C

t The structure of a C program is a protocol (rules) to the programmer, while


writing a C program.
t Each and Every C program should contain only one main ( ). The C program
execution starts with main () function.
t C Source code with [.C] Extension is given as input to compiler and compiler
converts it into equivalent machine instruction.
t Interpreter reads only one line of a source program at a time and converts
it into an object code.
t Header files contain definitions of functions and variables which can be
incorporated into any C program by using the pre-processor #include
statement.
t Preprocessor is a program that processes the source program before it is
passed on to the compiler.
t In a C program the smallest individual units are known as tokens.
t Keywords are reserved words by compiler. Keywords are assigned with fixed
meaning and they cannot be used as variable name.
t Identifiers are names of variables, functions, and arrays. They are user-
defined names, consisting sequence of letters and digits, with the letter as
the first character.
t Constants in C are applicable to the values which not change during the
execution of a program.
t C language is rich in data types. ANSI (American National Standard Institute)
C supports three classes of data types. Primary data type (fundamental),
Derived data types and User- defined data types.
t All variables must be declared before we use them in C program.
t Storage refers to the scope of a variable and memory allocated by compiler
to store that variable. Scope of a variable is the boundary within which a
variable can be used. Storage class defines the scope and lifetime of a variable.
t The static class specifies that space for the identifier is maintained for the
duration of the program.
t An expression is a sequence of operators and operands that specifies
computation of a value.
t The conditional expression operator takes THREE operands and that’s why
called Ternary operator.
t Unary Operators are Operators having Highest Precedence.
t C operators have two properties: Priority and Associativity.
t When an expression has more than one operator then it is the relative
priorities of the operators with respect to each other that determine the
order in which expression will be evaluated.
t Associativity defines the direction in which the operator having same
precedence acts on the operands.
Introduction to C 1.29

SHORT ANSWER TYPE QUESTIONS


1. What is C language?
Ans. C is a programming language developed at AT & T's Bell Laboratories of USA in
1972.The C programming language is a standardized programming language
developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the
UNIX operating system. It has since spread to many other operating systems, and
is one of the most widely used programming languages.
2. Who invented C Language?
Ans. Dennis Ritchie in 1972 developed a new language by inheriting the features of
both BCPL and B and adding additional features. He named the language as just
C.
3. Who invented B Language?
Ans. Ken Thomson at AT&T Bell Labs developed a language and named it B. Even the
B language was found to have some short comings to support development of
both business applications and system software.
4. Who invented BCPL Language?
Ans. Basic Combined Programming Language(BCPL) was developed by Martin
Richards, Cambridge university.
5. Why C Language?
Ans. C is one of the high level languages. It is a general purpose language, which
means it can be used to write programs of any sort.
6. What are the features of C Language ?
Ans. q In C one can write programs like that of high level languages as in COBOL,
BASIC, FORTRAN etc. as well as it permits very close interaction with the
inner workings of the computer.
q It is a general purpose programming language. It is usually called system
programming language but equally suited to writing a variety of applications.
q It supports various data types.
q It follows the programming style based on fundamental control flow
constructions for structured programming.
q Functions may be pre-defined or user defined and they may return values of
basic types, structures, unions or pointers.
7. What are the advantages of C language ?
Ans. 1. Easy to write
2. Rich set of operators and functions that are built-in
3. Support for bit-wise operation
4. Flexible use of pointers
5. Direct control over the hardware
6. Ability to access BIOS/DOS routines
7. Interacting using Interrupts
8. Ability to write TSR programs
9. Ability to create .COM files
10. Ability to create library files (.LIB)
11. Ability to write interface programs
12. Incorporating assembly language in C program
1.30 Programming in C

8. What are the disadvantages of c langauge?


Ans. 1. C is considered difficult to learn.
2. Because of its conciseness, the code can be difficult to follow.
3. It is not suited to applications that require a lot of report formatting and data
file manipulation.
9. What are the salient features of c languages?
Ans. The following are the salient features of C language are :
q C is called a middle level language
q C supports structured design approach
q C is extensible
q C is rich in data types and operators
q C is portable.
10. What is character set?
Ans. Character set is the set of characters allowed and supported in the programming
language. Generally a program is a collection of instructions, which contain groups
of characters. Only a limited set of characters is allowed to write instructions in the
program.
11. What is a constant?
Ans. A constant is a value that does not change during the program execution. A constant
used in C does not occupy memory.
12. What are the types of constants in c?
Ans. C constants can be divided into two categories :
q Primary constants
q Secondary constants
13. What are the types of C instructions?
Ans. Now that we have written a few programs let us look at the instructions that we
used in these programs. There are basically three types of instructions in C :
q Type Declaration Instruction
q Arithmetic Instruction
q Control Instruction
14. List out the characteristics of a program.
Ans. q Clarity q Integrity
q Simplicity q Efficiency
q Generality.
15. What is meant by tokens?
Ans. The tokens are usually referred as individual text and punctuation in the passage
of text. The C language program can contain the individual units called the C
tokens.
16. What are Keywords?
Ans. Keywords are reserved words that have standard and pre-defined meaning in C
.These keywords can be used only for their intended purpose.
17. What are the types of input statements available in C?
Ans. q Formatted I/O statements
q Unformatted I/O statements.
18. Define getchar () function.
Ans. The getchar() function reads a single character from a standard input device. This
function do not requires any arguments.
Introduction to C 1.31

19. What is meant by local variable?


Ans. The variables which are defined inside a function block or inside a compound
statement of a function sub-program are called local variables.
20. What is meant by global variable?
Ans. The variable that is used in more than one function throughout the program are
called global variables and declared outside of all the function.
21. What is data types?
Ans. Data types refer to the classes of data that can be manipulated by C programs.
The three fundamental data types supported by C are character, integer and real
type.
22. What is storage class? What are the different storage classes in C?
Ans. Storage class is an attribute that changes the behavior of a variable. It controls the
lifetime, scope and linkage. The storage classes in c are auto, register, and extern,
static, typedef.
23. Where is the auto variables stored?
Ans. Auto variables can be stored anywhere, so long as recursion works. Practically,
they restored on the stack. It is not necessary that always a stack exist. You could
theoretically allocate function invocation records from the heap.
24. What are register variables? What are the advantages of using register
variables?
Ans. If a variable is declared with a register storage class, it is known as register variable.
The register variable is stored in the cpu register instead of main memory. Frequently
used variables are declared as register variable as it's access time is faster.
25. What is conversion operator?
Ans. You can define a member function of a class, called a conversion function, that
converts from the type of its class to another specified type.
26. What are the advantages of auto variables?
Ans. q The same auto variable name can be used in different blocks.
q There is no side effect by changing the values in the blocks.
q The memory is economically used.
q Auto variables have inhabitast protection because of local scope.
27. What is pre increment and post increment?
Ans. ++n (pre increment) increments n before its value is used in an assignment operation
or any expression containing it. n++ (post increment) does increment after the
value of n is used.
28. What are qualifiers?
Ans. Qualifiers or modifiers are identifiers that may precede the scalar data types (except
float) to specify the number of bits used for representing the respective type of
data in memory. The qualifiers in C are short, long, signed, and unsigned.
29. What are the rules for the identifier?
Ans. q The first character must be an alphabet or underscore (_)
q Digits may be included in the variable
q The maximum number of characters in a word are 32 (It may vary depending
upon the platform)
q No other special characters are allowed.
30. What is an expression?
Ans. Expression is defined as a combination of operands and operators to obtain some
computation. Operands represent variables or values and The operator tells is
what operation to be performed.
1.32 Programming in C

31. Why C is called a middle level language?


Ans. C combines the features of both Assembly Level Languages (Low Level Languages)
and Higher Level Languages. For this reason, C is referred to as a Middle Level
Language. The feature of ALLs is that of enabling us to develop system level
programs and the features of HLLs are those of higher degree of readability and
machine independence.
32. How can variables be characterized?
Ans. The variables can be categorized by storage class as well as by data type. The
storage class specifies the portion of the program within which the variables are
recognized.
33. Give the rules for variable declaration?
Ans. The rules for variable declaration in C are given below :
q A variable name consists of alphabets, digits and the underscore (_) character
q The length of variable should be kept upto 8 characters though your system
may allow upto 40 characters
q They must begin with an alphabet
q Some systems also recognize an underscore as the first character
q White space and commas are not allowed
q Any reserved word (keyword) cannot be used as a variable name.
34. What is the purpose of type declarations?
Ans. The type declaration allow to create a synonym for other data types. Its syntax is
typedef type identifier; The declaration typedef unsigned long int declares INTEGER.
35. What is escape sequences?
Ans. An escape sequence is a set of characters, when taken together, represent one
character which may have a special significance. Escape sequences help to format
the outputs properly or create appropriate signals.
36. What is bit field?
Ans. A bit field is a commonly used data structure used to compactly hold a set of
Boolean flags. Instead of using Boolean variables for each flag, the flags are stored
in a fixed-size data structure like an integer, whose size in bits is known. The
Boolean flags are then stored in each bit of the data structure, minimizing memory
usage. In order to retrieve, read and write information from and to a bit field, the
programmer uses the bitwise operators AND, OR and NOT.
37. What are the use of bit field?
Ans. The Bit field are useful for number of reasons, such as :
q When storage is limited, we can store several Boolean variables in one byte.
q Certain devices transmit status information encoded into one or more bits
within a byte.
q Certain encryption routines need to access the bits within a byte.
38. What are the types of keywords supported by ANSI C?
Ans. There are 32 keywords supported by ANSI C :
q auto q double
q int q struct
q break q else
q long q switch
39. What is an operands?
Ans. The operators can be defined as symbols which specify operations to be performed.
The C language includes a number of operators. These operators are used in
different combinations to form expressions. The data items on which the operators
act upon are known as operands.
Introduction to C 1.33

40. What is the value of sizeof (char)?


Ans. The value returned by sizeof (char) is always 1 since char uses only one byte in
any machine. For other data types, the number of bytes used to represent a data
type depends on the implementation of a compiler.
41. What are the types of bitwise operator?
Ans. There are three types of bitwise operator :
q Bitwise AND(&)
q Bitwise OR(|)
q Bitwise Exclusive OR(^)
42. What is storage class?
Ans. The storage class in C provides the complete information about the location and
visibility of variables. Scope of a variable means the portion of the program within
which it can be referenced and lifetime means the time of its existence in the
memory.
43. What are the different storage classes in C?
Ans. There are four types of storage classes :
q Automatic: Variable used as a local variable. This is the default one. Initial
value of variable is garbage value without initialization.
q Extern: Variable used as a local variable. Retains its value during next function
call.
q Register: Variable used as a local variable. May be stored in register if possible.
Default initial value is garbage value.
q Static: Variable used as a global variable.
44. What are the types of unary operators?
Ans. C support unary operators are:
q minus operator -
q increment operator + +
q decrement operator -
q size operator
q (type) operator
45. What is the Difference between = and = = Operators?
Ans. The two operators = and == are used for assignment and checking respectively. If
not properly used, it causes many problems. The following program illustrates
what will happen if we use = instead of = =.
46. What is unary operator?
Ans. The operators that act upon a single operand to produce a new value are known
as unary operators.
47. What is the size of () operator?
Ans. Even though it looks like a keyword, sizeof( ) is an operator which is used to know
the memory size of the data types and variables. This operator returns the number
of bytes allocated for the variable (or) data type. The format of the sizeof() operator
is as follows.
sizeof (v);
where v is a variable name / data type / value.
48. What is the use of bitwise operator?
Ans. The bitwise operator performs the operation on bits (i.e. bit by bit). Using the
bitwise operators we can set / reset / check any bit in the value of the variable.
1.34 Programming in C

49. What is an Operator?


Ans. An operator is a symbol, which instructs the computer to perform the specified
manipulation over some data. The rich set of operators available in C enable us to
write efficient and concise programs and this fact serves to set C apart from any
other programming languages.
50. What is a ternary operator in C?
Ans. Perhaps the most unusual operator in C language is one called the conditional
expression operator. Unlike all other operators in C which are either unary or
binary operators the conditional expression operator is a ternary operator; that is,
it takes three operands. The two symbols that are used to denote this operator are
the question mark (?) and the colon (:). The first operand is placed before the ?,
the second between the ? and the and the third after the :.
51. What is meant by operator precedence?
Ans. Operator precedence describes the order in which C evaluates different operators
in a complex expression.
52. What are the types of type qualifiers in c?
Ans. The two type qualifiers provided by C are:
q const
q volatile
53. What is the purpose of scanf() and printf() functions?
Ans. The function scanf() is used for formatted input from the standard input and provides
many of the conversion facilities.
It is used for formatted output to standard output device, that is, screen. The
format specification string and the data to be output, are the arguments
(parameters) to the printf() function.
54. What is floating point constants?
Ans. Floating-point constants are numbers with decimal parts. A floating-point constants
consists of :
q An integral part
q A decimal point
q A fractional part
q An exponent part
q An optional suffix
55. What is string constants?
Ans. A string constant or literal contains a sequence of zero or more characters or
escape sequences enclosed in double Quotation marks.
56. What is integer constants?
Ans. An integer constant is an integer-valued number. It can represent decimal, octal,
or hexadecimal values.
57. What is character constants?
Ans. A character constant is a single character, enclosed within the pair of single
quotation mark (apostrophes).
58. What is the difference between C & C++?
Ans. C++ is an object oriented programming but C is a procedure oriented programing.
C is super set of C++. C can't support inheritance, function overloading, method
overloading etc. but C++ can do this. In C-programe the main function could not
return a value but in the C++ the main function should return a value.
Introduction to C 1.35

59. What are the types of data types and explain?


Ans. There are five basic Data types in C. These are:
q void: means nothing i.e. no data involvement in an action
q char: to work with all types of characters used in computer operations
q int: to work with an integer type of data in any computational work
q float: to work with the real type of data or scientific numbers in the exponential
form
q double: to work with double precision of numbers when the approximation is
very crucial.
60. What is signed and unsigned?
Ans. A numeric value, may have a positive or a negative sign. In the memory, for a
variable, one bit is used exclusively to maintain the sign of the data. If we don't
have sign, the sign bit also may be used for data. If the value is negative, the sign
bit is 1, and if it is positive, it will be 0.
61. What is the use of typedef?
Ans. The typedef help in easier modification when the programs are ported to another
machine. A descriptive new name given to the existing data type may be easier to
understand the code.
62. What is meant by type specifiers?
Ans. Type specifiers decide the amount of memory space occupied by a variable. In the
ease of integral types; it also explicitly states the range of values that the object
can hold.
63. What are the types of type specifiers?
Ans. The available data type specifiers are :
q Short
q Long
q Signed
q Unsigned
64. What is meant by type casting?
Ans. It is the explicit type conversion required for a number before carrying out processing
or assigning to another variable.
65. What are the primitive data types in c?
Ans. There are five different kinds of data types in C.
q char
q int
q float
q double
q void

MULTIPLE CHOICE QUESTIONS


1. C language has been developed by
(a) Ken Thomson (b) Dennis Ritchie
(c) Peter Norton (d) Martin Richards
2. C language has been developed at
(a) Microsoft corporation,USA (b) AT & T Bell labs,USA
(c) Borland International,USA (d) IBM,USA
1.36 Programming in C

3. C language came into existence in the year


(a) 1971 (b) 1957
(c) 1972 (d) 1983
4. C is a
(a) Middle level language (b) High level language
(c) Low level language (d) Both (a) and (b )
5. The maximum value that an integer constants can have is
(a) -32767 (b) 32767
(c) 1.7014e+38 (d) -1.7014e+38
6. All keywords in C are in
(a) Lower Case letters (b) Upper Case letters
(c) Camel Case letters (d) None
7. C can be used on
(a) Ms-Dos OS (b) Linux OS
(c) Windows (d) All Of Above
8. C programs converted into machine language with the help of
(a) editor (b) compiler
(c) operating system (d) none of above
9. In C a variable cannot contain
(a) blank spaces (b) hypen
(c) decimal point (d) all of above
10. Which is the format specifier for integer
(a) %s (b) %d
(c) %f (d) %c
11. A integer at 1 time can store?
(a) 2 bytes (b) 4 bytes
(c) 8 bytes (d) 32 bytes
12. If a is an integer then a=5/2 will return value
(a) 2.5 (b) 3
(c) 2 (d) 0
13. Which datatype can store largest value
(a) int (b) float
(c) double (d) none of these
14. FORTRAN is………….language.
(a) low level (b) high level
(c) mid level (d) machine level
16. An integer constant must have
(a) At least one decimal point (b) A commas along with digit
(c) At least one digit (d) Digits separeted by commas
17. && is…………………..
(a) Arithmatic operator (b) Relational operator
(c) Logical operator (d) Assignment operator
Introduction to C 1.37

18. A character variable can at a time store………character.


(a) 1 (b) 8
(c) 254 (d) 2
19. Which of the following statement is false
(a) Each new C instruction has to be written on a separate line.
(b) Usually all C statements are entered in small case letters
(c) Blank spaces may be inserted between two words in a C statement.
(d) Blank spaces cannot be inserted within a integer variables.
20. Meaning of opperater “<<”
(a) shift right (b) shift left
(c) more greater than (d) more less than
21. Which of the following is character constant
(a) thank you (b) enter values of p,n,r
(c) 23.56e-03 (d) none
22. The real constant inc can be expressed in which of the following forms
(a) fractional only (b) exponential only
(c) ASCII value form only (d) both 1,2
23. Which of the following statement is wrong
(a) mes=123 (b) con=154
(c) this=111 (d) 3+a=d
24. By default any real number is treated as
(a) a float
(b) a double
(c) a long double
(d) depends upon the memory model that you are using
25. How many data type in ‘C’ program?
(a) Float (b) Double
(c) Int, Float, (d) Char, Int, Float,Double
26. What would be the output of the following program?
main( )
{
Printf (“\n%x”,-1>>4);
}
(a) ffff (b) 0fff
(c) 0000 (d) fff0
27. Every computer understand only one language without using translation
program, called as:
(a) Assembly language (b) Machine language
(c) High level language (d) None of these
28. Machine language program are called as:
(a) source programe (b) object programe
(c) both a & b (d) none of these
1.38 Programming in C

29. An original C language program is called as:


(a) Source programe (b) Object program
(c) both (d) none of these
30. What would be the output of the following program ?
main ( )
{
Int i=32,j=0*20,k,l,m;
K=i/j;
L=i&j;
M=k^l;
Printf(“%d%d%d%d%d”,i,j,k,l,m);
}
(a) 32 32 32 32 0 (b) 0 0 0 0 0
(c) 0 32 32 32 32 (d) 32 32 32 32 32
31. What would the output of the following program?
main( )
{
char ch=a;
printf(“%d%d”,size of (ch),size of ((a) );
}
(a) 1 1 (b) 1 2
(c) 2 2 (d) 2 1
32. The values of a, b, c
int a=2, b=3, c=4
a=(b++)+c;
b=a+(++(c);
(a) 8,12,5 (b) 8,13,5
(c) 7,12,5 (d) 7,11,5
33. Write the output of the following
int n =7;
printf(“%d%d%d”, n++, n, n—);
(a) 787 (b) 667
(c) 778 (d) 887
34. Which of the following is the correct order of evaluation for the below
expression?
z = x + y * z / 4 % 2 - 1
(a) * / % + - = (b) = * / % + -
(c) / * % - + = (d) * % / - + =
35. Which variable is called automatic or auto variables
(a) register variables (b) local variables
(c) static variables (d) external variables
36. “^” operator means
(a) shift right (b) bitwise OR
(c) bitwise AND (d) bitwise exclusive
Introduction to C 1.39

37. HIEARCHY decides which operator


(a) is most important (b) is used first
(c) is fastest (d) operators on larges numbers
38. Which of the statement is false
(a) key words can be used as veriable names
(b) variable can cotain a digit
(c) variable names do not contain a blank space
(d) capital letters can be used in veriable names
39. According to the Standard C specification, what are the respective minimum
sizes (in bytes) of the following three data types: short; int; and long?
(a) 1, 2, 2 (b) 1, 2, 4
(c) 1, 2, 8 (d) 2, 2, 4
40. Which of following are ternary operater
(a) ?,: (b) !
(c) &&,” (d) none of these

ANSWERS

1. (b) 2. (b) 3. (c) 4. (d) 5. (b)


6. (a) 7. (d) 8. (b) 9. (d) 10. (b)
11. (a) 12. (c) 13. (c) 14. (c) 15. (c)
16. (c) 17. (c) 18. (a) 19. (a) 20. (b)
21. (d) 22. (b) 23. (d) 24. (a) 25. (d)
26. (a) 27. (b) 28. (b) 29. (a) 30. (a)
31. (b) 32. (c) 33. (b) 34. (a) 35. (b)
36. (d) 37. (b) 38. (a) 39. (d) 40. (a)

REVIEW QUESTIONS

1. What is C language?
2. Describe the several features of C language.
3. Explain the structure of c program.
4. Explain why C language is called middle level language.
5. What are header file? Why are they important? Can we write C program without
using any header file?
6. What do you understand by identifiers and keywords?
7. List all the basic or primary data-types available in C with their format specifier.
8. Write about space requirement for variables of different data types?
9. What are variables?
10. Explain the difference between declaration and definition.
11. What is the benefit of using const for declaring constants?
12. What is an operator? Describe the different types of operators that are included in
the ‘C’ language with the example for each?
13. What is unary operator?
14. What is a modulus operator? What are the restrictions of a modulus operator?
1.40 Programming in C

15. Explain pre and post increment-decrement operator with suitable example.
16. List all the Bitwise operators available in C. Explain with suitable example
17. Explain sizeof () operator with suitable example.
18. Explain conditional operator or turnery operator with suitable example.
19. Explain precedence and associatively with suitable example.
20. Explain automatic type conversion and casting with suitable some example.
21. What are logical operators are used in C? Illustrate with examples.
22. Why n++ executes faster than n+1?
23. List all the storage class available in c and specify the scope, lifetime, storage and
their default initial value.
24. Why do we need different types of storage classes ?
25. What are advantages and disadvantages of external storage class?
26. What are the advantages of auto variables?
27. Which bit wise operator is suitable for checking whether a particular bit is on or
off ?
28. Differentiate between typecasting and type conversion.

___________

You might also like