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

Problem Solving Through C Programming - Chapter 2: January 2013

This document provides an overview of the C programming language, including: 1. A brief history of C and its origins from other programming languages like ALGOL and BCPL. 2. The key features of C that make it robust, portable, and suitable for system software development. 3. Common applications that are developed using C, like operating systems, databases, and scientific software.

Uploaded by

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

Problem Solving Through C Programming - Chapter 2: January 2013

This document provides an overview of the C programming language, including: 1. A brief history of C and its origins from other programming languages like ALGOL and BCPL. 2. The key features of C that make it robust, portable, and suitable for system software development. 3. Common applications that are developed using C, like operating systems, databases, and scientific software.

Uploaded by

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

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/276202732

Problem Solving Through C Programming - Chapter 2

Book · January 2013

CITATIONS READS
0 41,596

1 author:

Rama M A
Maharani Lakshmi Ammanni College for Women
11 PUBLICATIONS   59 CITATIONS   

SEE PROFILE

All content following this page was uploaded by Rama M A on 12 May 2015.

The user has requested enhancement of the downloaded file.


Overview of
C Language 2
2.1 HISTORY OF C
Programming is the process of converting a solution (algorithm or flowchart) to a set
of instructions. A computer language is used to write the set of instructions (Computer
Program).
By 1960 a horde of computer languages had come into existence almost each for a
specific purpose. At this stage people started thinking that instead of learning so many
languages, each for a different purpose, why not use only one language which can program
all the possible applications. Therefore, an international committee developed a language
called ALGOL 60. Since it was too abstract and too general, a new language called
Combined Programming Language (CPL) was developed at Cambridge University.
However CPL turned out to be very hard to learn and difficult to implement. Basic
Combined Programming Language (BCPL) was developed to solve the above problem. But
unfortunately it turned to be too less powerful and too specific. Around this time a
language called B was written for Unix by Ken Thompson at AT & T’s Bell Labs, as
further simplification of CPL. Dennis M Ritchie (Circa 1972) inherited the features of B
and BCPL, added some of his own and developed C.
C is a general Computer Programming Language. It was originally created for the
specific purpose of rewriting Unix operating System. The intention of these programmers
was to port Unix onto other dissimilar machines. What was required was a language that
would permit Assembly like operations such as Bit manipulations, and at the same time
be executable on different Computers. Hence a new language was called for and C was
born. C++, an object oriented extension was created by Bjarne Stroustrup, also at Bell
labs.

2.2 SALIENT FEATURES OF C


C has many advantages over other high level languages.
 It is robust.
 C has the advantage of assembly level programming such as bit manipulation
and all the significant features of high level language such as easy debugging,
compactness etc. Therefore most of the C compilers are written in C.
 C is also called as a middle level language since it combines the features of high
level as well as low level programming.
OVERVIEW OF C LANGUAGE 37

 It is highly suited for writing system software and application packages.


 C consists of a rich variety of data types and powerful operators. This makes C
programs much more efficient and fast.
 It is platform independent and highly portable i.e., C can be run on almost any
operating system.
 C is a structured language, wherein the program is subdivided into a number of
modules. Each of these modules performs a specific task. Further structured
programming helps in making program debugging, testing and maintenance,
easier.
 One of the salient feature of C is its ability to add on to its library. User-defined
functions can be added to the C library making the programs simpler.
 C provides manipulation of internal processor registers.
 It allows pointer arithmetic and pointer manipulation.
 Expressions can be represented in compact form using C.

2.3 APPLICATIONS OF C
C has been used to develop system software and application software such as:
 Compilers
 Loaders
 Linkers
 Interpreters
 Operating Systems
 Data Base Management Systems (DBMS)
 Word Processors
 Spread sheets
 Graphics packages
 CAD/CAM applications
 Scientific and Engineering Applications
To write a sequence of instructions in any programming language the following must
be known :
1. The character set or alphabets of the language.
2. Using the character set, forming meaningful words called tokens.
3. Writing instructions using tokens.
4. Writing a program using these instructions.

2.4 C CHARACTER SET


A character set denotes a collection of symbols such as alphabets, digits or special
symbols, used to represent information. Fig. 2.1 lists the valid characters available in C.
38 PROBLEM SOLVING TECHNIQUES USING C

Alphabets Upper case alphabets A to Z


Lower case alphabets a to z

Digits 0 to 9

Special symbols ~ tilde


` back quote
! exclamatory mark
# hash
% percentage
^ caret
& ampersand
“ double quote
‘ single quote (apostrophe)
( left parentheses
) right parentheses
{ left braces
} right braces
[ left bracket
] right bracket
+ plus sign
– minus sign
* asterisk
/ slash
_ underscore
= equal sign
\ back slash
; semicolon
: colon
, comma
. dot
< less than
> greater than
? question mark
| vertical bar

White spaces Includes space, tab (\t, \v)


new line (\n), form feed

Fig. 2.1 : C character set


OVERVIEW OF C LANGUAGE 39

2.5 C TOKENS
A token is the basic and the smallest unit of a program. There are six types of
tokens in C which are listed in Fig. 2.2. Each token can be formed using one or more C
characters.

Token Usage
1. Keywords Include do, int, for etc
2. Identifiers Include variable names such as total, area, sum
3. Constants Include numbers such as 250, 25.5, –200 etc
4. Strings Include “college”, “2+3” etc
5. Operators Include +, –, *, ++ etc
6. Special symbols Include !, #, [ ], { } etc

Fig. 2.2 : C Tokens

Trigraph Characters
Some of the characters shown in Figure 2.1 are not supported by non-english
keyboards. In such cases C has introduced the concept of trigraph sequences, providing a
way for the user to enter the characters not available on the keyboard. Every non-
available character is represented by 3 characters - two question marks followed by
another character. For example, the left and the right braces { } can be keyed in using the
trigraphs ??< and ??>.

2.6 C KEYWORDS
There are some reserved words in C, called keywords. All the keywords have
standard pre-defined meanings and can be used only for the purpose intended. All
keywords must be written in lowercase. They cannot be used as user-defined identifiers.
The standard keywords are listed as in Fig. 2.3.

auto break case char const


continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while

Fig. 2.3 : C Keywords


40 PROBLEM SOLVING TECHNIQUES USING C

2.7 IDENTIFIERS
 Identifiers refer to the names of program elements such as variables, functions
and arrays.
 Identifiers are sequence of characters chosen from the set A–Z, a–z, 0–9,
and _ (underscore).
 C is a case sensitive language so that ALFA and Alfa are different.
 The underscore symbol _ is generally in the middle of an identifier (embedded).
 Identifiers may be of reasonable length of 8–10 characters though certain
computers allow up to 32 characters.
 Identifier names must start with an alphabet or underscore followed by letters,
digit or a combination of both.
 C has a list of keywords that cannot be used anywhere other than that
predefined in the language i.e., you can’t have a variable named int. Also one
must follow the practice of choosing names for variables which indicate the roles
of those variables in the program.

Example 2.1
valid identifiers are :
sum,avg_ht, x1,y1,PINCODE,Total
invalid identifiers are:
10th,S.I., total amount, Std-no

2.8 A C PROGRAM
The best way to learn C or any programming language is to begin writing programs
in it. Consider the following program.
/*Program to print a message*/
#include<stdio.h>
main()
{
printf(“Programming in C is fun!!\n”);
return;
}

The output of the above program is


Programming in C is fun!!
 C consists of functions, one of which must be main(). main()denotes the
beginning of the program.
OVERVIEW OF C LANGUAGE 41

 A function is a subprogram that contains instructions to perform specific


computation on its variables. When its instructions have been executed the
function returns control to the calling program, to which it may return results of
its computations. Because main () too is a function from which control returns to
the operating system at program termination, it is usual to include a return
statement in main ().
 printf is a library function in C that simply prints or displays its’ arguments at
the terminal.
 \n is called as the new line character and executes a line feed.
 A semicolon must terminate all program statements in C.
 Some compilers require the pre-processor directive #include<stdio.h>
 Preprocessing is a phase of compilation that is performed before analysis of the
program text. This must begin in the first column, They are not terminated by a
semicolon.
 stdio.h is a header file that comes with the C compiler and contains the data
that printf() needs. It is an abbreviation for “Standard input/output”.
 The body of the program is enclosed in braces { }; a pair of braces defines a block.
A program may consist of several blocks, which may include yet other blocks and
so on.
 C is case sensitive. All the functions and keywords must be in lower case.
 C statements may be of any length and may extend over several lines, as long
as any string in it is not broken. A semicolon by itself constitutes a null
statement.
Comments
Comments in programs are included between a forward slash-asterisk and asterisk-
forward slash pair-as shown.
/*.............*/
Comment lines are non-executable statements and hence are ignored by the
compiler.

Example 2.2
/*Comments may extend over many lines,
but as a rule they should be short*/

2.9 BASIC STRUCTURE OF A C PROGRAM


A C program is divided into a number of sections. It may contain one or more
sections as shown in fig. 2.4.
42 PROBLEM SOLVING TECHNIQUES USING C

Documentation Section - Comments


Preprocessor Section - Header files
Definition Section - Defining symbolic constants
Global Declaration Section - Global variables declared
main() - Function heading
{
Declaration part - Variable declarations
Executable part - Statements in C
}

Subroutine Section U|
f1
f2
|V User-defined functions
: ||
fn W
Fig. 2.4 : Structure of a C Program

(i) Documentation Section


This section consists of a set of comment lines useful for documentation. Though
comments are not necessary in a program, they help users to understand the program
better.
(ii) Preprocessor and Definition Section
This section contains header files which begin with a # symbol and are extended
with .h. They are also known as preprocessor directives used to include header files in a C
program. Examples of preprocessor statements are
# include <stdio.h>
# include <math.h>

Symbolic Constants are included using # define. For example to define the value of
PI, the statement is:
# define PI 3.14159

(iii) Global Declaration Section


Global declaration section is used to define variables that would be used in more
than one function. Such variables are called global variables and they must be declared
before the main( ) function.

(iv) The main( ) Function


All C programs must contain main( ) function. Further there must be only one
main( ) function. main( ) denotes the starting of a C program.
OVERVIEW OF C LANGUAGE 43

(v) Braces
All C programs incorporate a set of curly braces { }. Execution of the program begins
at the opening brace { of the main( ) function and ends at its closing brace }.
(vi) Declaration Part
This part is used to declare all the variables, arrays functions etc. used in the C
program. Initialization along with declaration can also be done here.
(vii) Executable Part
This part of the program consists of a set of executable statements such as Input/
Output statements, arithmetic statements, control statements etc. It can also include
comment statements which are ignored by the compiler (non-executable). The declaration
part and the executable part must be within opening and closing braces.
Every statement in the declaration part and executable part ends with a semicolon.

(viii) Subroutine Section


This section is optional and consists of all the user-defined functions called in the
main( ) function.

Example 2.3
/*Program to find the area of a square*/
#include <stdio.h>
main()
{
float side, area ;
side=5;
area=side*side;
printf(“\nArea of a square=%f’,area);
}

Output:
Area of a square = 25.0

The first line of Example 2.3 refers to the documentation section. It consists of a set
of comment lines giving the name and other details of the program.
The second line is the preprocessor statement # include <stdio.h> providing the link
to the system library.
The third line refers to the main ( ) function. All C programs must have only one
main ( ) function.
The fourth line contains the declaration part where the variables side and area are
declared.
The rest of the program contains the executable statements. The declaration part
and the executable part are within opening & closing braces.
44 PROBLEM SOLVING TECHNIQUES USING C

Every statement in the declaration part and executable part ends with a semicolon.
Execution of the program begins at the opening brace of the main( ) function and
ends at its closing brace.

2.10 PROGRAMMING STYLE


C does not have any restrictions while typing (unlike COBOL, FORTRAN) and
hence is known as free-form language. However one should follow a particular style while
writing the programs.
The program statements must be written in lower case. Upper case must be used for
Symbolic Constants.
When writing a group of statements within braces, the opening and closing braces
must be aligned. The statements within the braces must be indented.
Each specific task must be labeled with a comment statement.
A set of statements in C can be written in separate lines or more lines. For example
the statements:
p=a+b;
q=q+12;
r=x*y;

can also be written as


p=a+b;q=q+12;r=x*y;

However for better readability, the statements can be written in separate lines.

2.11 EXECUTING A C PROGRAM


The different steps involved in executing or running a C program are as follows:
1. Writing the program
C programs can be written using Turbo C, Microsoft C etc. Some compilers like
Turbo C have an in-built editor which allow the user to write, modify, compile, link
and execute the program. The written program is called the source code or source
program.

2. Compiling the source program


When the C program is compiled, the compiler checks for syntax errors if any. If
errors exist, the user must edit the program and compile it once again to generate
the object code.

3. Linking the program


In most of the compilers, linking of functions in the program, with the C library is
done automatically. The compiled and linked program is the executable code.
OVERVIEW OF C LANGUAGE 45

4. Executing the program


The C program is executed by giving the command relevant to the compiler.
In turbo C, the executable code generated has an extension .exe. For example, for
the C program called sum.C, the executable code generated is sum.exe and the
command :
c:\> sum

will execute the program.

2.12 CONSTANTS
Any fixed value that does not change during the execution of a program is known as
a constant. C consists of several types of constants, as shown in fig. 2.5.
Types of C constants
C constants can be divided into two categories :
 Primary Constants
 Secondary Constants
These constants can further be divided as follows :

or
derived
type
Function
Array
pointer
structure
union
enumerated

Fig. 2.5 : C constants

2.12.1 Integer Constants


Integers and real constants are numbers and are generally referred to as numeric
constants.
An integer constant consists of a sequence of digits and is an integer-valued number. There
are 3 types of integer constants depending on the number system. They are:
 Decimal
 Octal
 Hexadecimal
46 PROBLEM SOLVING TECHNIQUES USING C

Fig. 2.6 Integer Constants

Decimal Integer Octal Integer Hexadecimal Integer


It is a combination of It is a combination of It is a combination of digits
digits from 0 through 9 digits from 0 through 7 from 0 to 9 and letters from
A through F, representing
numbers from 10 to 15.
must have at least 1 The first digit must be 0 Must begin with ox or OX
digit (zero)
must not have a must not have a decimal Must not have a decimal
decimal point point. point.
could be positive or could be positive or Could be positive or
negative negative negative
No commas or blanks No commas or blanks No commas or blanks
allowed allowed allowed.
Examples : Examples : Examples :
426, +17.–5050.0 are valid 051,044,025 are valid Ox1, Oxa38, OxA1 are valid
10,000, 12.467 are invalid 540,068,03.45 are invalid Ox2.5, OABC, OxEGG are invalid

In most of the personal computers the maximum integer value is 32767 (decimal
system), 77777 in octal or 7fff in hexadecimal which is 215 – 1.
Large integer constants can be stored by using qualifiers, such as U,L and UL which
are appended to the end of the constant. For example :

12345678U or 12345678u
456789L or 4567891
2345789UL or 2345789ul

U refers to unsigned integer, UL to unsigned long integers and L refers to long


integer.

2.12.2 Real Constants


Quantities which are represented by numbers with fractional part are called real or
floating point constants.
(a) A real constant must have at least 1 digit.
(b) It must have a decimal point.
(c) It can be either positive or negative.
(d) No commas or blanks are allowed within a real constant.
OVERVIEW OF C LANGUAGE 47

Example 2.4

+325.66,45.0, –38.2,124.6789 are valid real constants.


11,530, –5E 10 are invalid.

The exponential (or scientific) form of representation of real constant is used when
the value is either too small or too large. In this form the real constant is represented in
two parts. The part appearing before ‘e’ is called Mantissa, and the part following ‘e’ is
called Exponent. For example, consider the value 516.55. This can be written as 5.1655 E2
in exponential form.
E2 means multiply by 102.
The rules for expressing real constants in exponential form are :
(a) The mantissa part and the exponential part must be separated by the letter e(or
E).
(b) The mantissa may be positive or negative.
(c) The exponent must have at least one digit, which must be a positive or negative
integer.
(d) Range of real constants in exponential form is 3.4e+38 to 3.4e+38.

Example 2.5

+3.2e–5, 4.5e8, –0.5e + 3, –2.4E – 5 are valid exponential constants.


–3E06,4.2e–5.5 are invalid.

Real numbers are referred to as floating point numbers since the exponent causes
the decimal point to float.

2.12.3 Character Constants


(a) A character constant is a single character within single quotes.
(b) The maximum length of a character constant is 1.
(c) Arithmetic operations are possible on character constant since they too
represent integer values.
(d) C also recognizes all the backlash character constants (Escape sequences)
available.

Example 2.6

‘\o’ ‘a’, ‘|’ ‘5’, ‘=’, are valid character constants.


‘xy’, ‘a4’, ‘26’ are invalid character constants.
48 PROBLEM SOLVING TECHNIQUES USING C

Note that the character constant ‘2’ is not the same as the number 2. Every
character has an equivalent integer value known as the ASCII code. Some character
constant & their equivalent ASCII values are as below :

Constant ASCII code

‘A’ 65
‘B’ 66
‘Z’ 90
‘a’ 97
‘z’ 122
‘0’ 48
‘1’ 49
‘’ 32

2.12.4 String Constants


A string constant consists of zero or more number of characters enclosed within
double quotes. The characters within quotes could be digits, characters, special characters
and blank spaces.

Example 2.7

"Red","Phone:334–5670","Rs.20.25", " ","" are valid


“Line1\n\Line2\nLine3' ‘Tc’, ‘Error’ are invalid
The string "" is a null string.

Note that ‘A’ is not equal to “A” since a string constant containing a single character
does not have a corresponding integer value. In fact it contains two characters, the
specified character followed by a null character represents by \0.

2.12.5 Coding constants


There are 3 types of code constants used in programs:
 Literal constants
 Defined constants
 Memory constants
Literal constants: are used to specify data, which cannot be changed. For example:
x=y+1;
In this statement 1 is a literal constant.
Defined Constants: are constants that can be defined using a preprocessor
command #define. This constant is placed at the beginning of a program since it is a
OVERVIEW OF C LANGUAGE 49

preprocessor command. For example :


# define MAX 30

The defined constants make the program easily modifiable and enhance the
understandability of the program.
Memory Constants: use a c type qualifier called const, to indicate that the data
specified is a constant and that it cannot be changed. Its general format is :
const Datatype identifier = value ;

For example :
const float pi = 3.14159 ;

defines a memory constant pi of float type with a value of 3.14159.

2.13 ESCAPE SEQUENCES


Special backslash character constants are denoted by backslash followed by a
particular character. These combinations of two characters are called escape sequences.
For example :
Consider the statement printf (“\nThis is easy!!”);
The \n is an example of an escape sequence. It is used to print the newline
character.
Each \n in the string of printf causes the cursor to be placed at the beginning of the
next line. To print a string in more than one line, place \n wherever you want to insert a
new line in the output.
If a string does not contain a \n at its end, the next string will begin in the same
line i.e., alongside the first string.

Example 2.8
main ( )
{
printf(“ This\n string\n will\n be\n
printed\n in\n 8\n lines.”);
}
Output
This
string
will
be
printed
in
8
lines.
50 PROBLEM SOLVING TECHNIQUES USING C

To include double quotes within a string use the escape sequence \”.
Similarly \\ is used to print \ and \’ to print single quote.
To continue a long string into the next line, insert a backslash (\) followed by a <cr>,
where you wish to break the string.
All escape sequences begin with a backslash.
Other escape sequences available in C are :

\a Rings terminal bell (alert)


\? Question mark
\b Backspace
\r Carriage return
\f Form feed
\t Horizontal tab
\ Vertical tab
\o ASCII null character
\n New line
\” Quotation mark(“)
\\ Backslash(\)
\0 Null
\’ Single quote

Some character constants can be expressed in terms of escape sequences. For


example, ‘\n’,’\\’,’\’ are valid character constants.

2.14 VARIABLES
A variable is an identifier used to store a single data item. This data could be a
numerical quantity or a character constant. During execution of the program, data must
be assigned to the variable. Therefore a variable can take different values at different
times during the execution of the program. The data stored in the variable can be accessed
any time, by referring to the variable name.
OVERVIEW OF C LANGUAGE 51

Example 2.9

Consider the following C program segment.


int x, y, z;
char p ;
:
:
x = 1; / *value1 is assigned to x*/
y=2 / *value2 is assigned to y*/
z = 3; / *value2 is assigned to z*/
x = y + z; /* value of x changes to 5*/
p = ’A’ ; /* value 65 is assigned to p*/
y = 6; /* value of y changes to 6*/
z = 7; /* value of z changes to 7*/
p = ’a’; /*value of p changes to 97*/

From the above example it is clear that a variable can be assigned different data at
different times within the program.
The rules for naming a variable are the same as those for an identifier.
They are :
1. Variable names generally begin with a letter followed by letters, digits
underscore or a combination of all.
2. No special character except the underscore symbol ( _ ) is allowed. Underscore is
generally embedded in a variable name to make it more readable.
3. Maximum length of a variable name should not exceed 32 characters. Normally
the length must not exceed 8 characters since many compilers treat the first 8
characters as significant.
4. C variables are case sensitive, so that Counter, counter and COUNTER are 3
different variables.
5. C keywords cannot be used as variable names.
6. White spaces are not allowed in a variable name.
7. Appropriate variable names must be chosen to indicate their role in the
program.

Example 2.10

Sum_total,avg_ht are valid variable names.


#NO,50th,Lotus 123 are invalid.
52 PROBLEM SOLVING TECHNIQUES USING C

2.15 DATA TYPES IN C


C consists of a rich variety of data types which can be represented within the
memory of the computer. Basically there are 4 primary data types namely :
1. integer(int)
2. character(char)
3. floating point(float) and
4. double-precision floating point (double)
The permissible range of values for each data type depends on its memory
requirement. Table 8.5 gives description, size and range of simple data types.

Data Description Size in Range


Type bytes
int integer value 2 –32, 768 to 32,767
char single character 1 –128 to 127
float a real number containing 4 3.4E–38 to3.4E+38
a decimal and/or an exponent
double double-precision floating 8 1.7e–308 to 1.7e + 308
point number giving precision
of 14 digits

Fig. 2.7 : Simple Data Types

2.15.1 Integer Data Types


Integer data types are whole numbers whose range of values are machine
dependent. To make efficient usage of storage space, C provides qualifiers or modifiers.
The storage space can be changed by affixing one of the modifiers.

Modifiers for Integers


The following modifiers are available for integer data types :
i) Unsigned int : This declaration removes the sign bit and makes the entire
word available for storing positive integers.
ii) Short int : The short int declaration is useful for small integer values (signed).
iii) Unsigned short int : This declaration can be used for small range of positive
integers.
iv) Long int : This declaration is used for large integer values (signed). When a
long integer constant is assigned a value, the letter L or 1 may be written
immediately after the right most digit.
OVERVIEW OF C LANGUAGE 53

v) Unsigned long int : Unsigned long removes the sign bit and doubles the
storage space of long int for positive integers.
The qualifier signed is not used since the default declaration assumes a signed
number. Fig. 2.8 gives data type, size and range of modifiers.

Data Type Size in bytes Range


Unsigned int 2 0 to 65535
Short int 2 –32768 to 32767
Unsigned short int 2 0 to 65535
long int 4 –2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
long double 10 3.4E –4932 to 1.1E + 4932
unsigned char 1 0 to 255

Fig. 2.8 : Size and Range of Modifiers

The modifier can also be affixed to octal and hexadecimal numbers.

2.15.2 Floating Point Data Types


Single precision floating point data types are declared by using the keyword float.
Floating point numbers occupy 4 bytes and are accurate to about 6 significant digits.

2.15.3 Double Precision Data Types


Since memory is fixed, any calculation involving floating point numbers introduces
round off errors. At the same time scientific calculations require a far greater accuracy
than provided by single precision arithmetic. Thus when large-scale scientific or
engineering computations are involved, the double declaration is used. The double
specification allows storage in 8 bytes correct to 14 digits and has a greater range. The
precision of the number can be extended by using long double which occupies 10 bytes.

2.15.4 Character Data Types


Character data types store a single character from the ASCII set. They occupy a
single byte and are declared by the keyword char. The qualifier unsigned can be used
with char to give a range of 0 to 255.

2.15.5 Void Data Type


Void data type is a non-specific c type which has no values and no operations. The
keyword used is void. It is used to return the result of a function that does not contain a
return value. It is also used to define a pointer, pointing to a general data.
54 PROBLEM SOLVING TECHNIQUES USING C

2.16 DECLARING VARIABLES


A variable declaration consists of a data type followed by one or more variable
names, and ending with a semicolon. This declaration informs the compiler about the
name of the variable and the type of data it will store. The syntax is :

data_type a1,a2,......an;

where a1,a2,......an are variable names and data_type is a basic date type such as int, float,
etc. Declaration of more than one variable must be separated by commas.

Example 2.11

int x, y, z ;
float avg, sum ;
char ans ;
double amount;

Here x,y and z are declared as integer variables, avg and sum as float variables, ans
is a character type of variable and amount is of double type.
The above declarations can be also be written as :
int x ;
int y ;
int z ;
float avg ;
float sum;
char ans ;

Variable declaration for modifiers can be as :


short int count ;
long int fact ;

These declarations can also be written as :


short count;
long fact;
Since short and short int are the same. Similarly long int and long mean the same.

2.17 ASSIGNING VALUES TO VARIABLES


Values can be assigned to variables in 3 different ways :
 In the declaration part.
 In the executable part by using assignment.
 Through input from keyboard.
 Assigning initial values to variables is called initialization.
OVERVIEW OF C LANGUAGE 55

2.18 ASSIGNMENT STATEMENT


Variables can be assigned values by using the assignment operator = The syntax is

Variable_name=constant/Variable/expression;

Consider the assignment statement


total = 0;

This statement causes the value 0, on the right hand side of the equal (=) sign, to be
assigned to the variable total on the left.
The right hand side of statement can be a constant, variable or an expression
containing one or both. For example, in the statement
sum = marks1 + marks2;

The expression on RHS is evaluated first and the resultant value in stored in sum
i.e., marks1 and marks2 are added and the result is stored in sum. Similarly
count = count +1;

Increments the old value of count by 1 and stores it in count. If the old value of
count was 10, the new value becomes 11.

Example 2.12
/*Assigning value to variables in the declaration part*/
.
.
.
.
int x=1,y=2,z=3;
float avg=0.0,pi;
char opt=’y’;

Examples of assigning values to variables in the executable part are :


pi=3.1415;
total=0;
opt=’N’;

C also allows multiple assignments in one statement. Some valid statement are :
a=b=c=0;
x1=x2=large;

Note : The left hand side of an assignment statement must always contain only one
variable name.
56 PROBLEM SOLVING TECHNIQUES USING C

Example 2.13
/*Program to find circumference of a circle*/
#include<stdio.h>
main()
{
/*Declaration and assignment*/
float pi=3.14159,radius=10,circum;
circum=2*pi*radius;
printf(“\nCircumference=%f’’,circum);
return;
}
Output
Circumference=62.831802

Example 2.14
/*Program to find total and average of marks obtained in 4 subjects*/
#include<stdio.h>
main()
{
int m1,m2,m3,m4;
float total,avg;
/* assignment in executable part*/
m1=50;m2=70;m3=75;m4=67;
total=m1+m2+m3+m4;
avg=total/4;
printf(“\nThe average marks=%f’’,avg);
return;
}

Output
The average marks = 65.500000

Example 2.15
/*Program to compute area of a circle*/
#include<stdio.h>
main()
{
/*Declarations*/
float pi, r, area;
/*Assignments*/
pi=3.14159;
OVERVIEW OF C LANGUAGE 57

r=5;
/*calculation and printing*/
area=pi*r*r;
printf(“\nArea of circle=%f”,area);
return;
}

Output
Area of circle=78.539749

Another way of assigning values to the variables is to read data through keyboard
using the scanf( )function. It is similar to printf( )function used to print the output.

Example 2.16

/*Program to calculate simple interest*/


#include<stdio.h>
main()
{
int year;
float prin,rate,si;
printf(“\nEnter principle,rate and period:”)
scanf(“%f %f %d”,&prin,&rate,&year);
si=prin*rate*year/100;
printf(“\nSimple Interest=%f",si);
return;
}
Output
Enter principle,rate and period :1000 5 2
Simple Interest = 100.000000

2.19 SYMBOLIC CONSTANTS


The #define, also called Macro definition is used to declare a symbolic constant in a
C program. A symbolic constant is a name given to a constant. Like # include, #define is a
preprocessor directive. Its general form is :

#define name replacement-string

Where a replacement-string may include other previously #defined variables and


name is a valid variable name. During compilation of a program with macro definition,
every occurrence of the macro name is replaced with its value, as defined in #define by the
replacement-string.
58 PROBLEM SOLVING TECHNIQUES USING C

Some valid examples are :

#define MAX_MARKS 100


#define PI 3.14159
#define COLLEGE "MLACW"

Example 2.17

Given the circumference find radius of a circle.

/* Program to find radius of a circle given the circumference */


#include<stdio.h>
#define PI 3.14159
#include<math.h>
main()
{
float r,circum;
clrscr();
printf("\n Enter the circumference of the circle : ");
scanf("%f",&circum);
r = circum / ( 2 * PI );
printf("\n The radius of the given circle is :%7.2f",r);
getch();
return;
}

Output
Enter the circumference of the circle : 8
The radius of the given circle is : 1.27

2.20 OPERATORS IN C
C provides several operators for elementary arithmetic operations like addition,
subtraction, multiplication, division, residue-modulo (the operation that gives the
remainder after division of one integer by another) and logical manipulations.
An operator is a symbol used for certain type of manipulations, logical or
mathematical. The data on which the operators act are called operands. An expression is
a valid combination of operators and operands that results in a value. For example in the
expression :
12*5
* is the multiplication operator,
12 and 5 are the operands.
OVERVIEW OF C LANGUAGE 59

Operators may be classified into 4 categories namely


(i) unary
(ii) Binary
(iii) Ternary
(iv) Special

2.20.1 Unary Operators


Operators that operate on a single operand are known as unary operators.
The unary operators always precede the operand. The different unary operators available
in C are :
(i) Unary plus (+)
(ii) Unary minus (–)
(iii) Increment (++)
(iv) Decrement (– –)
(v) Logical NOT (!)
(vi) Bitwise complement (~)
(vii) Address (&)
The unary minus operator is used for negation. It change sign of the quantity on its
right i.e., it multiplies its only operand by –1. Similarly unary plus multiplies its operand
by +1.

2.20.2 Binary Operators


Binary operators operate on two operands. They are classified into five categories as
follows:
(i) Arithmetic
(ii) Relational
(iii) Logical
(iv) Assignment
(v) Bitwise

2.20.3 Ternary Operators


Ternary operators act on three data elements. The conditional operator (?:) is a
ternary operator.

2.20.4 Special Operators


Special operators include operators such as comma (,) and sizeof.
60 PROBLEM SOLVING TECHNIQUES USING C

2.21 ARITHMETIC OPERATORS


C supports five arithmetic operators. They are listed in Fig. 2.9.

Operator Purpose
+ Addition
– Subtraction or (unary)
* Multiplication
/ Division
% Remainder after integer division

Fig. 2.9 : Arithmetic Operators

There is no exponentiation operator available in C. However, the library function


pow( ) is provided to compute exponentiation.
Dividing one integer by another integer is called as integer division, which
truncates, the fractional part. The % operator gives the remainder of such a division. For
example, consider a = 10, b = 3.

a % b gives 10% 3 giving the result 1


and a/b gives 10/3 giving the result 3

% operator can have only integer operands.


Example 2.18
Consider a and b to be 2 integer variables.
a = 16, b = 3.

Expression Result

+16 16
–5 –5
a+b 19
a–b 13
a*b 48
a/b 5(decimal part is truncated)
a%b 1(remainder of division)

Consider C1 & C2 to be 2 character constants representing the alphabets P and T.


i.e., C1 = 'P' and C2 = 'T'
OVERVIEW OF C LANGUAGE 61

 C1 = 80, C2 = 84.

Expression Result
C1+C2 164
C1+C2+5 169
C1+’1' 129

where the value of '1' is 49.

In integer division, if one of the number is negative, the result will be truncated
depending on the machine. For example :
5/6=0 and –5/–6=0

but –5/6 may be zero or –1. In turbo C it is 0. Further, in modulo division the sign of
the remainder is the sign of the first operand. For example :
–20 % 6 = –2
–20 % –6 = –2
20 % –6 = 2

Calculations involving real numbers is called real arithmetic. In such a type of


calculation the values may be in fractional form or exponential form and the result would
be approximated to the number of significant digits allowed.
Mixed-mode Arithmetic operations consists of a real and an integer operand. If
one of the operand is real, the result is also real. For example :

15/2.0 = 7.5
However 15/2 = 7

2.22 RELATIONAL OPERATORS


The relational operators are used to form relational expressions, representing
conditions that are either true or false. The result of the expression is an integer. Further,
false is represented by zero value and true in represented by non-zero value. For example
expressions
50<200
x>y

are called relational expressions whose value can be either true or false i.e., 50<200 is
false; when x = 10 and y = 5, x > y is true. There are 6 relational operators in C. They are
as shown in Fig. 2.10.
62 PROBLEM SOLVING TECHNIQUES USING C

Operator Meaning
> greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Fig. 2.10 : Relational Operators

The last two operators are also called as Equality Operators.

Example 2.19

Consider 3 integer variables, i = 1, j = 2 and k = 7

Expression Logical value Integral value


(i) 10.5<=12 true 1
(ii) i==20 false 0
(iii) 5>20 false 0
(iv) (i+j)>=k false 0
(v) (j+k+1)>(i+5) true 1
(vi) k!=7 false 0

In the 4th and 5th example given above the expressions contain arithmetic
expression. Thus in the relational expression (i+j)>=k, the arithmetic expression i+j will be
evaluated and then the result is compared with k. These arithmetic operators have higher
priority over relational operators. The relational operators are used to compare two
quantities in decision statements.

Example 2.20

/* Program to show usage of relational operators */


#include <stdio.h>
main()
{
int i=1,j=2,k=7;
clrscr();
printf("\n Value of 10.5 <= 12 : %d",10.5 <= 12);
OVERVIEW OF C LANGUAGE 63

printf("\n Value of i == 2 : %d",i == 2);


printf("\n Value of 5 < 4 : %d",5 < 4);
printf("\n Value of i+j >= k : %d",i+j >= k);
printf("\n Value of j+k+1 > i+5 : %d",j+k+1 > i+5);
printf("\n Value of k != 7 : %d",k != 7);
getch();
return;
}

Output
Value of 10.5 <= 12 : 1
Value of i == 2 : 0
Value of 5 < 4 : 0
Value of i+j >= k : 0
Value of j+k+1 > i+5 : 1
Value of k != 7 : 0

2.23 LOGICAL OPERATORS


Logical operators are used to combine two or more logical expressions. There are 3
logical operators in C. They are logical AND, logical OR and logical NOT (Fig. 2.11).

Operator Meaning

! logical NOT
&& logical AND
|| logical OR

Fig 2.11 Logical Operators

 The result of a logical AND is true only if both operands are true. The result is
false if either operand is false.
 The result of a logical OR is false only if both operands are false. The result is
true if either operand is true.
 C also consists of the unary operator ! (not) that negates the value of a logical
expression i.e., it causes true expression to become false and vice-versa. This
operator is known as logical NOT operator. Further like relational operators, a
logical expression results in zero or non-zero value depending on whether it is
false or true.
64 PROBLEM SOLVING TECHNIQUES USING C

Example 2.21

Consider i = 8, x = 5.1, c = ‘a’ where i is an integer variable, x is a floating point


variable and c is a char variable.

Expression Logical value Integer value

(i>6)&&(c==’a’) true 1 (or non-zero)


i<=6||(c==’b’) false 0
i>=6&&(c==97) true 1
(x<10)||(i>10) true 1
!(i<=4) true 1
(c!=’p’) true 1

The truth table for logical operators is as shown in Fig. 2.12.

a b Result of Result of Result of


Result of I Result of II a && b a || b !a
condition condition
True True True True False
True False False True False
False True False True True
False False False False True

Fig. 2.12 : Truth Table for logical Operators

2.24 ASSIGNMENT OPERATORS


The assignment operator ‘=’ is used to assign the value of a variable, constant or
expression to a variable. The syntax is :

variable=variable/constant/expression;

For example :
x = 10; /*x is assigned a value 10 * /

b = x; /*The value of x is assigned to b i.e., 10*/

sum=a+b; /*The sum of a & b which is 20 is assigned to sum */


OVERVIEW OF C LANGUAGE 65

Example 2.22
/*Program to print sum of 4 numbers*/
#include<stdio.h>
main( )
{
int a, b, c, d,sum;
printf(“\nEnter 4 numbers:”);
scanf(“%d%d%d%d”,&a,&b,&c,&d);
sum=a+b+c+d ; /*assignment statement*/
printf(“\nSum=%d”,sum);
return;
}
Output
Enter 4 numbers : 50 15 22 40
Sum=127

C also provides abbreviated or shorthand assignment operators. They are of the


form:

Variable operator = Expression;

For example the statement


n = n + 5;

can be written using shorthand assignment operator as :


n + = 5;

Where += is the abbreviated or compound operator. In the above case + = means add
5 to n. The different shorthand assignment operators are as shown in Fig. 2.13.

Normal Shorthand Operator Meaning


assignment assignment
n=n+1 n += 1 += sum & assign
n = n – 50 n –= 50 –= subtract & assign
n = n*10 n *= 10 *= multiply & assign
n=n/6 n /= 6 /= divide & assign
n=n%5 n %= 5 %= find modulo and assign

Fig. 2.13 : Compound/Shorthand Assignment Operator

The priority of the above operators + =, –=, *=, /= and % = is the same as the
assignment operator.
66 PROBLEM SOLVING TECHNIQUES USING C

Advantages of Shorthand Assignment Operators


The main advantages of abbreviated assignment operators are :
1. The variable on the left hand side need not be written again on the right hand
side.
2. The statement is short and easier to read.
3. It is efficient.
Difference between = = and = operator
1. == is an equality or relational operator, used for comparison = is an assignment
operator which assigns the resultant value on its right hand side to the variable
on its left hand side.
2. == operator does not change the value of the variable on the left hand side.
However = operator does change the value of the variable on the left hand side
of the assignment statement.
Multiple assignment
C allows multiple assignments of the form;

variable1 = variable2 = .......... = expression;

where assignments are done from right to left. For example, the assignment
statement.
x = y = z = 10;
means x = (y = (z = 10));
 Assignment will be done from right to left i.e., First 10 is assigned to z.
 Next the value of z (which is 10) is assigned to y and so on.
 The final values of x, y and z will be 10.

2.25 INCREMENT/DECREMENT OPERATOR


The increment and decrement operators are specifically used in C or C++.
They are not generally available in other languages.
Increment operator ++ is used to increment the value of the variable by 1.
Decrement operator – – is used to decrement the value of the variable by 1.
They are also called as unary operators Fig. 2.14. Since they operate on only one
data element.

Operator Meanings Usage

++ Increment a++ or ++ a means a = a + 1


–– Decrement a – – or – – a means a = a – 1

Fig. 2.14 : Unary operators


OVERVIEW OF C LANGUAGE 67

Example 2.23
Consider the following statements :
int x, y;
:
x = 10;
y = ++x;

x is increment by 1 so that x and y will have a value 11. Similarly in


int a, b;
:
a = 5;
b = —a;

will result in the value of a and b to be 4.


Post-increment operator ++ is written to the right of its operand as in n ++;
which is the same as n = n + 1;
Post-decrement operator –– is also written to the right of its operand as in n—
, and is equivalent to n = n – 1;
Pre-increment and pre-decrement operators ++ and – – are always placed to the
left of the operand as follows :
++n; /* same as n = n+1*/
– –n; /* same as n = n–1*/

The behavior of post and pre–increment or decrement operators are the same when
used with a single operand. However, they behave differently when the operand is
embedded in an expression.

2.25.1 Difference between postfix & prefix operators


(i) The pre-increment or decrement operator first increments or decrements the
value of its operand by 1 and then assigns the resulting value to the variable on
the left hand side. For example, consider
int a, b;
a = 15;
b = ++a;

In this example, the value of a is incremented by 1 and then this value 16 is


assigned to b.
(ii) The post increment or decrement operator first assigns the value to the variable
on the left hand side and then increments or decrements the operand by 1.
Consider the following program segment :
int m,n;
n = 2;
m = n– –;
68 PROBLEM SOLVING TECHNIQUES USING C

The value of n is first assigned to m and then it is decremented i.e., n becomes 1, but
value of m is 2.
In subscripted variables.
a[j++]=5;

is equivalent to a[j]=5;
j++;

Similarly, a[++i]=5;
is equivalent to i = i+1;
a[i] = 5;

Consider the statement


x = n++/2;

where n = 5. After execution, n is 6 but x gets the value 5/2 which is 2.

Example 2.24
/* Program to show usage of increment and decrement operators */
#include<stdio.h>
main()
{
int x=1,y=2,z=3,p;
clrscr();
p=(x++) + (++y);
printf(“\n P=%d X=%d Y=%d”,p,x,y);
p=(++x) + (––z);
printf(“\n P=%d X=%d Z=%d”,p,x,z);
p=(++x) + (y––)– (z––);
printf(“\n P=%d X=%d Y=%d Z=%d”,p,x,y,z);
}
Output
P=4 X=2 Y=3
P=5 X=3 Z=2
P=5 X=4 Y=2 Z=1

2.26 TERNARY OPERATOR (CONDITIONAL OPERATOR)


C consists of a very special operator known as ternary or conditional operator and is
represented by ? : The syntax is

expression1 ? expression2 : expression3;

and general usage is as

variable = expression1 ? expression2 : expression3;


OVERVIEW OF C LANGUAGE 69

Since it contains 3 expressions it is called ternary. The above statement is evaluated


as follows :
(i) Expression1 is evaluated first.
(ii) If it is true or non-zero, expression2 is evaluated and its value assigned to the
variable.
(iii) If expression1 is false or zero, expression3 is evaluated and its value assigned to
the variable.
(iv) Either expression2 or expression3 will be evaluated, but never both.

Example 2.25

Consider the following statements :


n = 5;
m = 10;
big = (n > m) ? n : m;

Here n > m is evaluated first giving the result ‘false’. Since the expression is false
the value of m is assigned to big. Thus big = 10. The same can be written in the form of
if else statement as follows :
if(n > m)
big = n;
else
big = m;

Some more examples :


(10 == 8) ? 2 : 4 //result is 4 since 10 is not equal to 8
(10>8) ? 2 : 4 //result is 2 since 10 is greater than 8
(10==8+3) ? 2 : 4 //result is 4 since 10 is not equal to 11

Example 2.26
/*Program to find largest of 2 numbers*/
#include<stdio.h>
main()
{
int n,m,big;
clrscr();
printf(“\n Enter two integer numbers :”);
scanf(“%d %d”,&n,&m);
big=(n>m)?n:m;
printf(“\n The largest of %d and %d is : %d”,n,m,big);
}
Output
Enter two integer numbers :10 70
The largest of 10 and 70 is : 70
70 PROBLEM SOLVING TECHNIQUES USING C

Example 2.27
/* Program to find whether a number is even or odd */
#include<stdio.h>
main()
{
int x;
clrscr();
printf(“\n Enter a number :”);
scanf(“%d”,&x);
(x % 2 == 0) ? printf(“\n %d is even”,x):printf(“\n %d is odd”,x);
}

Output
Enter a number :17
17 is odd
Enter a number :40
40 is even

Program 2.28
/* Program to find the highest marks of a student in 4 Exams */
#include <stdio.h>
#include <conio.h>
main()
{
int m1, m2, m3, m4, highest;
clrscr();
printf("\n Enter the marks in 4 papers :\n");
scanf("%d %d %d %d", &m1, &m2, &m3, &m4);
highest = m1 > m2 ? m1 : m2 ;
highest = highest > m3 ? highest : m3 ;
highest = highest > m4 ? highest : m4;
printf("\n Highest marks in 4 papers = %d",highest);
return;
}

Output
Enter the marks in 4 papers :
56 74 66 60
Highest marks in 4 papers = 74
OVERVIEW OF C LANGUAGE 71

2.27 SPECIAL OPERATORS


C consists of some special operators. They are as shown in Fig. 2.15. The operators
&, *, . and  will be discussed in chapter 8.

Operator Description

, Comma operator
sizeof size in bytes
& address of operand UV used for po int er data type
* accessing value at that address W
. dot operator UV used for member selection
 arrow operator W
Fig. 2.15 : Special Operators

2.27.1 The Comma Operator


(i) The comma operator is used to separate a list of expressions given as a single
expression.
(ii) The lists with commas are always evaluated from left to right.
(iii) The value of the right most expression becomes the final value of the combined
expression.
(iv) The syntax is of the form :

variable = exp1, exp2, ...... expn;

For example, the statement :


result = (a = 5, b = 10, a + b);
 first assigns 5 to a i.e., a = 5
 next assigns 10 to b i.e., b = 10
 and finally assigns the value of a + b i.e., 10 + 5 = 15 to result.
(v) The comma operator needs parentheses, since it has the lowest precedence
compared to all other operator.
(vi) The comma operator is used in for( ) loops to separate more than one expression.
It is possible to write :

for (exp1a, exb1b; exp2; exp3a, exp3b)statement;

(vii) It can also be used in while loops to separate more than one expression. For
example:
while(textchar=getchar( ),textchar ! = ‘\n’)
putchar(textchar);
72 PROBLEM SOLVING TECHNIQUES USING C

In this example, the end condition for input is checked first and then it waits
for input of a character. The program terminates as soon as the enter key is
pressed.
(viii) A block of code within braces can be written in one line by using the
comma operator. For example, the program segment :
{
temp=n;
n=m;
m=temp;
}

may be replace by
temp = n, n = m, m = temp;

Example 2.29

/* Program to show usage of comma operator in a for loop */

#include<stdio.h>
main()
{
int i,j;
clrscr( );
printf(“\n Odd Even”);
for(i=1 , j=2; j<=10 ; i+=2 , j+=2)
printf(“\n %d %d”,i , j);
}

Output
Odd Even
1 2
3 4
5 6
7 8
9 10

2.27.2 The sizeof operator


(i) The sizeof operator returns the size in bytes of the operand on the right.
(ii) The syntax is

sizeof(n)

where n can be a variable, a constant or a data type.


OVERVIEW OF C LANGUAGE 73

(iii) It is a unary operator which associates from right to left.


(iv) The size of operator is used to determine the size of an array or a structure. It is
also used for dynamic memory allocation of variables.

Example 2.30
/* Program to show usage of sizeof operator */
#define STRING “Usage of sizeof Operator”
#include <stdio.h>
main()
{

char a = ‘p’;

clrscr();

printf(“\n The size of char is : %d \n”,sizeof(char));

printf(“\n Therefore the size of char a is : %d \n”,sizeof(a));

printf(“\n However the size of ‘p’ is : %d \n”,sizeof(‘p’));

printf(“\n STRING : \”%s\” \n”,STRING);

printf(“\n The number of bytes in STRING is : %d \n”,sizeof STRING);

printf(“\n The size of short is : %d \n”,sizeof(short));

printf(“\n The size of int is : %d \n”,sizeof(int));

printf(“\n The size of long is : %d \n”,sizeof(long));

printf(“\n The size of float is : %d \n”,sizeof(float));

printf(“\n The size of double is : %d \n”,sizeof(double));

getch();

Output

The size of char is :1

Therefore the size of char a is :1

However the size of ‘p’ is :2

STRING : “Usage of sizeof Operator”

The number of bytes in STRING is : 25

The size of short is :2

The size of int is :2

The size of long is :4

The size of float is :4

The size of double is :8


74 PROBLEM SOLVING TECHNIQUES USING C

2.28 BITWISE OPERATORS


C supports a powerful set of operators known as bitwise operators. The bitwise
operators are used for controlling and interacting with hardware and also for
manipulating data at the bit level.
The Bitwise operators are as shown in Fig. 2.16.

Operator Description

& bitwise AND


| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one’s complement

Fig 2.16 : Bitwise Operators

(i) Bitwise operators cannot be applied to float or double. They can be applied to
integers only.
(ii) All except ~ operator are used in binary operations. Tilde (~) is a unary
operator.
(iii) Bitwise operators perform bitwise logical AND, bitwise logical OR, bitwise
exclusive OR, bitwise shift left and shift right.
(iv) Bitwise operators work on their operands bit by bit starting from the least
significant bit. The truth table for logical bitwise operations is as shown in
Fig. 2.17 True is taken to be 1 and false as zero.

Operand1 Operand2 x&y x|y x^y


x y
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Fig 2.17 : Truth table for logical Bitwise Operations

2.28.1 Bitwise AND Operator


The Bitwise AND operator is represented by the symbol & (ampersand).
The result of AND operation is 1 if both operand bits are 1, otherwise, the result is zero.
Further, the AND operation is done on the binary representation of the operands.
OVERVIEW OF C LANGUAGE 75

Example 2.31

4 & 5 results in 4
i.e., binary value of 4 is 0100
binary value of 5 is 0101

After AND operation 0100 i.e., 4

Bitwise & operator is used to check whether a particular bit is 0 or 1. Consider the
number 21. Its bit pattern is represented by
0001 0101
To check whether the fourth bit is 0 or 1, AND operation must be done with
another operand whose value must be 24 i.e., 16, which can be represented as
00010000.

Therefore, 0001 0101


0001 0000 & mask
0001 0000

result shows that 4th bit is 1 since the resultant value is 16.

Example 2.32
/*Program to test whether a given number is even or odd using bitwise & operator */
#include<stdio.h>
main()
{
int n;
clrscr();
printf(“\n Enter a number :”);
scanf(“%d”,&n);
if(n&1) /*ANDing with LSB*/
printf(“\n Number is odd “);
else
printf(“\n Number is Even “);
return;
}
Output
Enter a number :8
Number is Even
Enter a number :9
Number is odd
76 PROBLEM SOLVING TECHNIQUES USING C

2.28.2 Bitwise OR Operator


The bitwise OR Operator is represented by the symbol | (vertical bar). It is also
known as inclusive OR. The result of a bitwise OR operation is 1 if either or both
corresponding bits has a value 1. Otherwise it is zero.

Example 2.33

Consider x = 4, y = 9
x is 0000 0100 4
y is 0000 1001 9
x|y is 0000 1101 i.e., 13

The bitwise OR is used to set a particular bit on (set to 1).

2.28.3 Bitwise Exclusive OR Operator


This operator is represented by the symbol ^ and is known as Exclusive OR
operator. The result of a bitwise XOR operation is 1 if one of the corresponding bits is 1,
otherwise it is 0.

Example 2.34
Consider the values x = 4, y = 9.
x is 0000 0100 4
y is 0000 1001 9
x^y is 0000 1101 i.e., 13

2.28.4 Bitiwse Complement Operator


The complement operator is represented by ~(tilde) and is also known as one’s
complement operator. It inverts all the bits. Thus all the zeros become 1 and all the ones
become 0.

Example 2.35

Consider x = 4
x is 00000100
~x is 11111011

2.28.5 Bitwise Shift Operator


The shift operators are used to push the bit patterns to the right or left by the
number of bits given by their right operand.
OVERVIEW OF C LANGUAGE 77

The Right shift operator is of the form :

expression>>n

where n is the number of bit positions to be shifted. However the rightmost n bits
are lost. Further the left most n bits which are vacant will be filled with zero. For example
x>>4 shifts all bits by 4 places to the right.

Example 2.36

Consider an unsigned integer x with bit pattern


0100 0100 0101 1100

when x>>3 000 0 1000 1000 1011

Vacant Positions

when x>>5 0000 0010 0010 0010

Vacant Positions

The Left shift operator is of the form :

expression<<n

where n is the number of bit positions to be shifted. The left most n bits are lost and
the rightmost n bits are vacated and filled with zeros.

Example 2.37

Consider the unsigned integery y with bit pattern


0110 0111 1001 0011
Therefore, y<<1 gives 1100 1111 0010 0110
Vacant positions
y<<5 gives 1111 0010 0110 0000

Vacant positions

Shift operators are used for multiplication and division by 2. For example, the
statement.
x = y << 2;
78 PROBLEM SOLVING TECHNIQUES USING C

shifts two bit to the left in y. Further the value of x is equal to y multiplied by 2 2.
Similarly, the statement
x = y >> 2;

shifts the bits in y to the right by 2. Also the value of x is equal to y divided by 22.

Example 2.38
/* Program to show usage of bitwise operations */
#include<stdio.h>
main()
{
int x,y , w=–1;
clrscr();
printf(“\n Enter the two integers:”);
scanf(“%d %d”,&x,&y); // x = 24
printf(“\n w= %d One’s Compliment= ~w = %d \n” ,w,~w);
printf(“\n x & y = %d \n” ,x & y);
printf(“\n x | y = %d \n” ,x | y);
printf(“\n x ^ y = %d \n” ,x ^ y);
printf(“\n x << 2 = %d \n” ,x<<2); // x * 2 2 = 24  4 = 96
printf(“\n x >> 2 = %d \n” ,x>>2); // x/22 = 24/4 = 6
getch();
return;
}
Output
Enter the two integers:24 9
w= –1 One’s Compliment= ~w = 0
x&y=8
x | y = 25
x ^ y = 17
x << 2 = 96
x >> 2 = 6

2.29 EXPRESSIONS
Valid expressions are a combination of operators, constants and variables.
They may also include function calls which return values. There are 6 types of expressions
which are :
 Constant
 Arithmetic
 Relational
 Logical
OVERVIEW OF C LANGUAGE 79

 Pointer and
 Bitwise expressions
Expressions which are a combination of the above type of expression are known as
compound expressions.
Constant Expressions contain only constant values.
Arithmetic Expressions consist of a valid combination of variables, constants and
arithmetic operators.
Relational Expressions contain a valid combination of variables, constants,
relational operators and arithmetic expressions. They generally return results of type true
or false.
Logical Expressions are a valid combinations of two or more relational
expressions using logical operators. They return either true or false.
Pointer Expressions return address values.
Bitwise Expressions are used for bitwise manipulation of data using the bitwise
operators.

2.30 STATEMENTS
In general a statement is a part of the program that can be executed.
It specifies an action.
 Statements are the smallest executable unit of a program.
 All statements must be terminated with a semicolon.
 Block statements are blocks of code enclosed within a pair of braces { }.
C divides the statements into the following groups :
(i) Selection
(ii) Iteration
(iii) Jump
(iv) Label
(v) Expression and
(vi) Block statements
Selection statements include if ( ) and switch.
Iteration statements consist of while, do-while and for. They are also known as
looping statements.
Jump statements are break, continue, goto and return.
Label statements consist of case, default and goto labels.
Expressions statements are composed of a valid expression.
80 PROBLEM SOLVING TECHNIQUES USING C

Block statements, also known as compound statements are made up of a sequence


of statements within braces.

2.31 EVALUATION OF EXPRESSIONS


 To evaluate an expression, the given algebraic expression must be converted to a
C expression.
 Then it must be written in the form of assignment statement.
 All the variables on the right hand side must be assigned values before
evaluation.
 No operator is assumed.
 No operator for exponentiation.
Fig. 2.18 shows a few examples of mathematical expressions and their equivalent C
expressions.

Mathematical expression C expression

1. ab + cd a*b + c*d
2. (a+b) (a–b) (a+b)*(a–b)
a
3. d (a/b) + d
b

2x 2  3x  1
4. (2*x*x + 3*x – 1)/10
10

 b  b2  4ac
5. root  root=(–b+sqrt(b*b–4*a*c))/(2*a)
2a

b
6. a2   c2 a*a – b/2 + c * c
2

Fig. 2.18 : Conversion of Expression

2.32 PRECEDENCE OF ARITHMETIC OPERATORS


Any arithmetic expression is evaluated according to the rule of precedence of
operators. For example in the expression.
4*5/2

Evaluation takes place from left to right i.e.,


First 4 is multiplied by 5 and the result 20 is divided by 2.
 The order in which the expression is evaluated depends on the hierarchy of
operators (Fig. 2.19).
OVERVIEW OF C LANGUAGE 81

Precedence level Operators Associativity


1 () Left to right
2 unary Right to left
3 *,/,% Left to right
4 +, – Left to right

Fig. 2.19 : Hierarchy of Arithmetic operators

 In an arithmetic expression, the expression enclosed in parentheses is evaluated


according to the precedence.
 In the case of nested parentheses, the inner most parentheses is evaluated first
and the evaluation continues outwards.
 When two operators with the same precedence are encountered, the evaluation is
done from left to right as in the above example. This is known an associativity.
 Parentheses can be used to change the order of evaluation.

Example 2.39

Consider the equation

 b  b2  4ac
x1 
2a
given a = 1, b = 4, c = 4
The equivalent expression in C is :
x1 = (–b + sqrt (b*b – 4*a*c))/(2*a)
= ((–4) + sqrt(4*4 – 4*1*4))/(2*1) //Substitution
= (–4 + sqrt (4*4 – 4*1*4))/(2*1) //Evaluates inner most parentheses
= (–4 + sqrt (16 – 4*4))/(2*1)
= (–4 + sqrt (16 – 16))/(2*1)
= (–4 + sqrt(0))/(2*1) //Evaluates function
= (–4 + 0)/(2*1) //Outer parentheses
= –4/(2*1)
= –4/2
x1= –2
82 PROBLEM SOLVING TECHNIQUES USING C

Example 2.40

Consider the expression


(–5*2/(6+4–2) + (2/3+5))
The order of evaluation would be
= (–5 * 2 / (6 + 4 – 2) + (2 / 3 + 5) )
= (–5*2/(10–2)+(2/3+5))
= (–5*2/8+(2/3+5))
= (–5*2/8+(0+5))
= (–5*2/8+5)
= (–10/8+5)
= –1+5
=4

/*Program to Evaluate a given expression */


#include <stdio.h>
main()
{
int result;
clrscr();
printf("\n The given expression is: (–5*2/ (6+4–2) + (2/3 + 5))");
result = (–5*2/ (6+4–2) + (2/ 3+5));
printf("\n Result of Evaluation : %d",result);
getch();
return;
}
Output
The given expression is : (–5*2/(6+4–2) + (2/3+5))
Result of Evaluation : 4

 Whenever more than one set of parentheses appear next to each other (not
nested) then the order of evaluation is from left to right i.e., the left most set is
evaluated first and the right most set of parentheses is evaluated last.
 Parentheses can be used whenever in doubt about the precedence of operators. It
also improves the understandability of the program.
OVERVIEW OF C LANGUAGE 83

Example 2.41
Consider the expression :
++x – y++ where x = 6, y = 2
++x – 2 [unary operators (from R to L) :
First y = 2, next y = 3 (post increment)]
7 –2 [Unary operators :
First x = 6, x = 7 (pre–increment)]
5 [Subtraction]

2.33 PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


The precedence of operators comes into effect whenever there are more than one
operators involved in the expression to be evaluated.
 There are many levels of precedence, each containing one or more operator.
 The operator with the highest precedence level is evaluated first.
 Operators in the same level are evaluated either from left to right or right to left
depending on their associativity. Associativity determines the operations to be
performed from right and from left, when several operators of the same priority
level exist in the same expression.
 The order of precedence and associativity of operators are two very important
aspects of evaluation. For example, consider the statement
(a < 10&& a + b > 15)

where a = 20, b = 1.
The order of evaluation will be as follows.
(i) Since + operator has the highest priority in the expression, addition is computed
first :
a < 10 && 21 > 15

(ii) Both the relational operators have higher priority compared to the logical operator
&&. Here the associativity of relational operators has to be considered which is left
to right. Thus :
20 <10 && 21 > 15
False && True

(iii) The result of logical && is false or 0.


A complete operator precedence summary is listed in Fig. 2.20, from highest to
lowest.
84 PROBLEM SOLVING TECHNIQUES USING C

Operator Operator category Associativity Rank


() Function call/Innermost parenthesis L to R 1
[] Array element
. member selection
+ unary plus R to L 2
– unary minus
++ increment
–– decrement
! logical Not
~ One's complement
* Pointer reference
& Address of
sizeof size of a variable
(type) cast operator
*, /, % Multiplication, division and remainder L to R 3
+, – Addition and subtraction L to R 4
<< , >> Left shift and Right shift L to R 5
<,<=, >,>= Relational operators L to R 6
==, != Equality operators L to R 7
& Bitwise AND L to R 8
^ Bitwise XOR (Exclusive OR) L to R 9
Bitwise OR (Inclusive OR) L to R 10
&& Logical AND L to R 11
|| Logical OR L to R 12
?: Conditional operator R to L 13
=, Assignment R to L 14
*=, /=, operators and
%=, += Abbreviated
–= assignment
&=, ^=, operators
!=, <<=, >>=
, Comma operator L to R 15

Fig. 2.20 : Operator Precedence

2.34 SOME COMPUTATIONAL PROBLEMS


During computation of mixed mode expressions, some approximations occur leading
to grave errors. The three major computational problems are as follows:
OVERVIEW OF C LANGUAGE 85

 Consider the expression:


1 1 1
 
3 3 3
The result must be equal to 1. However when written in the form of a C
expression.
(1.0/3.0) + (1.0/3.0) + (1.0/3.0)

Round-off errors occur in every division and results in errors.


 Division by zero is another computational error. Any number divided by zero
results in abnormal termination of the program. Therefore care must be taken to
avoid zero value in the denominator.
 Overflow and underflow errors are the third type of computational problem. Care
must be taken to make sure that the operands are of the correct data type and
range.

2.35 TYPE CONVERSIONS (IMPLICIT)


In mixed-mode Arithmetic, the operands are of different types. The evaluation of
such expressions strictly follows rules of type conversion. Generally, when the operands
are of different types, the lower type is converted to higher type and the resultant value is
of higher type. The rules of conversion are as shown in Fig. 2.21.

Operands Conversion Result


float, double converts float to double double
float, int converts int to float float
chars or shorts both converted to int int (signed or unsigned)
int, short converts short to int int
int, long converts int to long long
unsigned, int converts int to unsigned unsigned

Fig. 2.21 : Rules of Type Conversion

The above rules of conversion are applied while evaluating an arithmetic expression
on the right hand side of an assignment statement.
The following conversions can occur (Fig. 2.22) when the resultant value on the right
hand side and the variable on the left hand side are of different types.
86 PROBLEM SOLVING TECHNIQUES USING C

Assignment Conversion Result

int = float converts float to int by int x;


truncating the fractional part float y = 25.5543;
x = y;
value of x is 25

float = int converts int to float float y ; y = 10;


by adding zeros to the value of y is
fractional part 10.000000

double = float converts float to double float x = 5.123456;


by padding the fractional double y; y = x;
part with zeros. the value of y is
5.123456

float = double double value is rounded to float x;


the precision of float before double y = 2.56789765;
truncating x = y;
the value of
x is 2.567899
int = char assigns the ASCII code of int x; x = ‘A’
char to int value of x is 65

char = int if the integer value falls in char a;


the range of ASCII codes of a = 65;
characters, the corresponding value of a is ‘A’
character will be assigned to char

int = long int drops the extra higher order bits long x = 12345678;
which is wrong int y; y = x;
The value of y is 24910

Fig. 2.22 : Types Conversions in assignment statements

2.36 TYPE CASTING (EXPLICIT CONVERSION)


The above mentioned type conversions are automatic. However, a user can convert
data explicitly by type casting. Its general form is :

(data type) expression

where expression may be a variable or an expression. Some examples are illustrated in


Fig. 2.23.
OVERVIEW OF C LANGUAGE 87

Type casting Conversion


n1 = (int)25.5 25.5 is converted to integer by truncating the functional
part i.e., 25
n2 = (int)20.5/(int)5.5 Numerator & denominator are converted to integer
resulting in 20/5 = 4
n3 = (double)total/kount total is converted to double and then division is done.
n4 = (int)(p + q) sum of p & q is converted to int.
n5 = (int)p + q This example is different from the previous one. Here
only p is converted to int and added to q.

Fig 2.23 : Type Casting Examples

 Type casting is a unary cast operator.


 The operand of a cast operator can be an expression or a variable.
 The cast operator does not change the value of its operand permanently. The
operand acquires the type within parentheses only for the current calculation.
 The cast operator has an associativity of right to left and a priority just below
the parentheses operator.
 Casting operator can be used to round off a given value. For example, to round off
an amount of Rs.42.70 i.e., Rs.42 and 70 paise to the nearest rupee the formula
amount = int (x + 0.5)

can be used where x = 42.7. The resultant amount would be 42.7 + 0.5 = 43.2 and int (43.2)
gives 43. Further if x = 42.3 then resulting amount would be 42.3 + 0.5 = 42.8 = 42.

Example 2.42
/* Program to find the summation of the series
S=1+1/2+1/3+----+1/n using cast operator */
#include<stdio.h>
main()
{
float s=0;
int n,i;
clrscr();
printf("\n Enter the value of n :");
scanf("%d",&n);
for(i=1;i<=n;i++)
s=s+1/(float)i;
printf("\n Sum of series : %6.3f " , s);
}
Output
Enter the value of n :3
Sum of Series : 1.833
88 PROBLEM SOLVING TECHNIQUES USING C

2.37 LIBRARY FUNCTIONS


C contains a number of library functions that carry out various commonly used
operations or calculations. These library functions are grouped together as object programs
in separate library files. The library files are supplied as part of C/C++ compiler.
 A library function is accessed by writing the function name, followed by a list of
arguments that represents information being passed to the function.
 The arguments must be enclosed in parentheses and separated by commas.
 The arguments can be constants, variables or expressions.
 A function that returns a data item can appear anywhere within an expression,
in place of a constant or a variable or an array element.
Mathematical Functions (Math.h)
The most common and most popular mathematical functions are available in the
header file called math.h.
All arguments x, y in the mathematical functions are assumed to be double.
All functions return double as shown in Fig. 2.24.

Functions Purpose Usage


sin (x) sine of x, x in radians d = 60 in degrees, convert
to radians
cos (x) cosine of x, x in radians x = d*3.14159/180
tan (x) tangent of x, x in radians y = sin (x) = 0.866025
asin(x) inverse sine of x x = 1.00
acos (x),atan(x) inverse cosine of x & tangent to x y = asin (x) = 1.570796
sinh(x) hyperbolic sine of x y = sinh(x) = 1.175201
acosh(x),atanh(x) hyperbolic cosine of x &
hyperbolic tangent of x
exp (x) e raised to the power of x (e=2.718282) y=exp(2.5)=e2.5= 12.182494
log (x) natural logarithm of x(base e), x>0 y = log(3.0) = loge3.0=1.098612
log10(x) common logarithm of x, y=log10(3.0)=loge3.0
(base 10), x > 0 = 0.477121
pow(x,y) x raised to the power of y y = pow(3,4)= 34 =81.000000
sqrt(x) square root of x,x >=0 y = sqrt(3.0) = 3 =1.732051
fabs(x) absolute value of x (float) y = fabs(–3.14) = 3.14000
abs(int i) absolute value of integer n = abs(–20) = 20
ceil(x) rounds x up the nearest y = ceil (2.339) = 3
integer y = ceil (–3.339) = –3
floor (x) rounds x down to the y = floor(2.339) = 2
integer y = floor (–3.339) = –4

Fig. 2.24 : Math Functions


OVERVIEW OF C LANGUAGE 89

To use mathematical functions shown in the above table, math.h header file must
be included.

Example 2.43
/*Program to show usage of Library functions using math.h */
#include <stdio.h>
#include <math.h>
main( )
{
int d=60;
double x , y;
clrscr();

/* sin x , cos x , tan x */


x = d*3.14159/180.0;
y = sin(x);
printf("\n x in Degrees = %d\n",d);
printf("\n x in radians = %f\n",x);
printf("\n sin(x) = %f cos(x) = %f tan(x) = %f\n", y,cos(x),tan(x));

/* asin x, acos x, atan x */


x = 1.00;
y = asin(x);
printf("\n x in radians = 1.00\n");
printf("\n asin(x) = %lf acos(x) = %lf atan(x) = %lf\n", y,acos(x),atan(x));

/* sinh x, cosh x, tanh x */


x = 1.00;
y = sinh(x);
printf("\n sinh(x) = %lf cosh(x) = %lf tanh(x) = %lf\n", y,cosh(x),tanh(x));

/* exp x , lox x, log10 x, power x, sqrt(x), abs(x) */


printf("\n e raised to 2.5 = %f\n",exp(2.5));
printf("\n Natural log(3.0) = %f common log10(3.0) = %f\n",log(3.0),log10(3.0));
printf("\n pow(3,4) 3 raised to 4 = %f\n",pow(3,4));
printf("\n square root of 3.0 = %f\n",sqrt(3.0));
printf("\n fabs(–3.14) absolute float value = %f\n",fabs(–3.14));
printf("\n ceil(2.339) rounded upto nearest integer = %f\n",ceil(2.339));
printf("\n ceil(–3.339) rounded upto nearest integer = %f\n",ceil(–3.339));
printf("\n floor(2.339) rounded down to nearest integer = %f\n", floor(2.339));
printf("\n floor(–3.339) rounded down to nearest integer = %f\n",floor(–3.339));
getch();
return;
}
90 PROBLEM SOLVING TECHNIQUES USING C

Output
x in Degrees = 60
x in radians = 1.047197
sin(x) = 0.866025 cos(x) = 0.500001 tan(x) = 1.732047
x in radians = 1.00
asin(x) = 1.570796 acos(x) = 0.000000 atan(x) = 0.785398
sinh(x) = 1.175201 cosh(x) = 1.543081 tanh(x) = 0.761594
e raised to 2.5 = 12.182494
Natural log(3.0) = 1.098612 common log10(3.0) = 0.477121
pow(3,4) 3 raised to 4 = 81.000000
square root of 3.0 = 1.732051
fabs(–3.14) absolute float value = 3.140000
ceil(2.339) rounded upto nearest integer = 3.000000
ceil(–3.339) rounded upto nearest integer = –3.000000
floor(2.339) rounded down to nearest integer = 2.000000
floor(–3.339)rounded down to nearest integer = –4.000000

REVIEW QUESTIONS

Short Answer Questions


1. List any 2 features of C language. (2008)
2. ‘C’ is a middle level language. Justify. (2008)
3. Write the basic structure of a C program. (2011)
4. Why is ‘C’ called a free-form language ?
5. Write any 4 applications of C.
6. Write the character set of C.
7. What are C tokens? Explain.
8. What do you mean by trigraph characters ?
9. What is a comment statement ? Give its syntax.
10. What is the difference between an identifier and a keyword ?
11. What is the programming style followed in a C program ?
12. Write the different steps followed, in the execution of a C program.
13. What is a constant ?
14. What is a variable ?
15. What is an identifier ?
16. List the simple data types in C. (2010)
OVERVIEW OF C LANGUAGE 91

17. What is the difference between an integer constant and a float constant.
18. How do you represent an octal number and a hexadecimal number in C ?
19. What is the difference between ‘A’ and “A” ?
20. What is a keyword ? Mention the important keywords in C.
21. What is the difference between a character constant and a string constant ?
22. What are modifiers used for ? Explain.
23. Give the purpose of Escape sequence characters.
24. How do variables and symbolic constants differ ?
25. What is an operand and an operator?
26. What is an expression?
27. What are unary operators?
28. Give examples of unary operators.
29. What are arithmetic binary operations? (2011)
30. What is the difference between unary and binary operators?
31. Which operator is used both as a binary operator and unary operator?
32. What is the numerical equivalent to true and false in “C”?
33. What is the difference between prefix and postfix increment operators?
34. What is the difference between = and = = operators? (2011)
35. Convert the following mathematical expressions into C arithmetic expression.
(a) y = |(a + b) / (c – d)|1/a

(b) x = 3
sin a a b
36. What do you mean by type casting?
37. What is associativity?
38. What is the difference between the operators / and %?
39. What is operator precedence?
40. What are the precedence levels of arithmetic operators?
41. What is an expression? What are its components?
42. Why are parentheses used within an expression?
43. How can you determine the number of bytes allocated to each data type in C?
44. Discuss the equality operators and their usage.
45. What are library functions and how are they useful?
46. What is the difference between pre-increment and post-increment operations?
47. What is the function of sizeof operator? Mention any one application of the sizeof
operator.
92 PROBLEM SOLVING TECHNIQUES USING C

48. Explains the following mathematical functions with examples:


(a) floor ( )
(b) ceil ( )
49. Explain the following mathematical functions with examples:
(a) fmod ( )
(b) fabs ( )
50. What is the function of bitwise AND operator?
51. Explain bitwise (OR) operator?
52. What does bitwise XOR operator do?
53. Explain the complement operator with an example.
54. How is the comma operator used ?
55. Explain type casting with an example.
56. What is a ternary operator ? Explain with an example. (2012)

Long Answer Questions


1. What are library functions and how are they useful ? (2011)
2. Explain the different types of constants and variables in C. Illustrate with examples.
(2011)
3. Explain different data types. (2010)
4. What is a variable ? Summarize the rules for formulating variable names. (2010)
5. Explain conditional and bitwise operators with examples. (2008)
6. List out built-in mathematical functions in C language. (2008)
7. Write any 5 escape sequence characters in C. (2008)
8. Explain assignment statements. How is it different from algebraic expression ?
Justify with examples.
9. What are the different ways of assigning values to variables? Illustrate with
examples.
10. Explain symbolic constants with the help of an example.
11. Explain the 5 arithmetic operators.
12. What is the order of evaluation of an expression containing nested parentheses?
Illustrate with an example.
13. What are increment and decrement operators? Explain with examples.
14. Explain the different relational operators.
15. Describe the different logical operators, and their hierarchy.
OVERVIEW OF C LANGUAGE 93

16. How can you write multiple assignment and what is the order of their evaluation ?
Illustrate with an example.
17. What is the difference between ternary operator and if-else statement?
18. Discuss the function of size of operator with an example.
19. Explain the left shift and right shift operators.
20. What are coding constants ? Explain.

Programming Assignment
1. Determine which of the following are invalid identifiers. Justify your answer.
(a) $sum (b) return (c) Total marks (d) 123–45
2. Determine which of the following are invalid integer constants and why?
(a) 0.56 (b) 25,356 (c) 8*3e–12
(d) 75E+2 (e) “12345” (f) 4*5
3. Find errors if any in the following:
(a) int a; (b) float VALUE; (c) exponent alpha;
(d) char = p, q;(e) short charm; (f) long int x; counter;
(g) long float fact;
4. Find which of the following are valid character constants:
(a) ‘b’ (b) ‘*’ (c) ‘\t’ (d) ‘/n’ (e) ‘tab’
(f) ‘\\’ (g) ‘\0’ (h) ‘123’ (i) ‘\v’
5. Find which of the following are valid string constants:
(a) ‘9:30 A.M.’ (b) “AGE:” (c) “x*y = z;”
(d) “10.5E + 20” (e) “Good bye, Bangalore”
(f) “The teacher said, “Class dismissed.”
6. Write declaration for each variable:
(a) integer variables: p, q
(b) floating point variables: sum1, sum2
(c) character variables: yes, no, why
(d) long integer variable: Kounter
(e) short integer variable: flag
(f) double precision: root
(g) unsigned integer: books
7. Write variable declaration and assign the given values for the following:
(a) floating point variables: x = 4.5, y = 5.20056
(b) double precision variables: x1 = 1.5*10–20, y1 = – 4.2*10+5
(c) character precision variables: C1 = ‘A’, C2 = ‘*’
(d) integer variables: n1 = 621 (octal), m2 = fff1 (hexadecimal)
(e) long integer variables: maxi = 123456789
94 PROBLEM SOLVING TECHNIQUES USING C

8. Write the macro definition for the following:


Constant Value
a) FACT – 21
b) BEGIN {
c) END }
d) NAME RAMA
e) AMOUNT “Rs.200”
9. Write the equivalent C expressions for the following:

L (a  b) OP 1
tan 1 
i) y= M ii) x= 3
MN    PQ ab

10. Find the value of each arithmetic expression given three integer variables. a = 2,
b = 4, c = 6.
(a) 12 * b + 2 * (a + c) (b) b * (a % c)
(c) a * (b/c) (d) a % b + c % b (e) – 12 % b

11. Determine the value of each expression given 3 character type variables.
c1 = ‘A’, c2 = ‘1’, c3 = ‘ ‘ (use ASCII character set)
(a) c1 + c2 + c3 (b) c2 % c1
(c) ‘4’ + c2 (d) ‘2’ + ‘4’ (e) c3 + ‘#’

12. Correct the errors, if any:


(a) m=++b–5 (b) y = (100) ; (c) 1.0 = 50/5;
(d) a=b++–c*2 (e) x = y = z = 0.15, 10, – 5;

13. Find the value of the logical expressions where a = 1, b = 2, c = – 3


(a) b < = a && c > = a (b) a > b && a > c
(c) a = = b || a < b (d) a < 15 && b > 0 || a < 0
(e) 2.0/b = = 0.0 && b/2.0 ! = 0.0

14. Given the initial values:


int i = 1, j = 2, k;
float x = 0.1, y = – 0.1, z;
char a, b, c = ‘1’, d = ‘2’;

Determine the value of each statement:


(a) i = j = 2.5 (b) j* = 2 % 5 (c) k + = (c – 10)
(d) k = (j > 5) ? i : j (e) z = (y < = 0) ? y : 0

15. Given int i = 1, j = 2;


double x = 0.01, y = – 0.005;
OVERVIEW OF C LANGUAGE 95

Find the value of following expressions containing library functions.


(a) abs (i + j/10) (b) log (exp (x))
(c) fabs (x – y) (d) sqrt (x * x + y * y)
(e) (sin (x) + cos (y)) (f) ceil (x – y)
(g) floor (x + y) (h) pow (x + y, 2.0)
(i) sin (x/y) (j) ceil (x)
16. Convert the algebraic expressions to C statement
2m1 m 2
(a) area = r2 + 2rh (b) force = m  m g
1 2

 b  b2  4ac
(c) tri-area = s( s  a )( s  b)( s  c ) (d) x1 = 
2a
(e) side = a 2  b2  2ab cos ( x )

17. Give the output of the following program


# include <stdio.h>
main ( )
{
int x = 1, y = 2, z = 3, w;
w = x % y + y % x – z % x – x % z;
printf (“\n %d”, w);
w = x/z + y/z + (x + y) / z;
printf (“\n %d”, w);
w = z/y/y/x + z/y/ (y/x);
printf (“\n %d”, w);
return;
}

18. Find the output of the following program


# include <stdio.h>
main ( )
{
int x, y, z;
x = 2 * 30 + 4 * (5 – 6);
printf (“\n %d”, x);
y = 2 * 3 * (4/20 * 12);
printf (“\n %d”, y);
z = – 2 * – 10/ – 5 % – 7;
printf (“\n %d”, z);
x = 150 % (5 * (12 % 2 % 4 * (16/3)));
printf (“\n %d”, x);
y = – 4 * – 3/ –2 % 6 – 5 + (– 7);
printf (“\n %d”, y);
96 PROBLEM SOLVING TECHNIQUES USING C

z = 8/2/3 * 4 * 5 % 6 % 7 % 2;
printf (“\n %d”, z);
}

19. Give the output of the following program segment.


# include <stdio.h>
main ( )
{
int x, y, z;
printf (“\nx = %d\n”, x = (y = 2 * (z = 12/10)) % 5);
printf (“\nx = %d\n”, 2 * (x = y % (z = 2 * (x = 5))));
printf (“\nx = %d\n”, x = 2 * (x = z % (y = x = 3 *
(z = 10% (x = 3 * (y = 12/ (z = 5)))))));
}

20. Find the output of the following program segment


# include <stdio.h>
main ( )
{
int x = 1, y = – 2, z = 3, w = – 10, s = 20, t = 30;
x + = (y – = (z * = (w / = (s % = t))));
printf (“\nx = %d y = %d z = %d w = %d w = %d\n. s = %d
t = %d\n”, x, y, z, w, s, t);
t + = s – = w * = z * = y p % = x;
printf (“\nx = %d y = %d z = %d\n w = %d s = %d t = %d\n”, x, y, z, w, s, t);
}

21. Find the output of the following program


# include <stdio.h>
main ( )
{
int x = 6, y = 2, z = 10, w;
w = ++ x – y ++ ;
printf (“\nw = %d x = %d y = %d\n”, w, x, y);
w = ++ x % ++ y % ++ z % w –– ;
printf (“\nw = %d x = %d y = %d z = %d\n”, w, x, y, z);
w = ++ z % – – y;
printf (“\nw = %d y = %d z = %d\n”, w, y, z,);
w = ++ w/ ++x/y –– ;
printf (“\nw = %d x = %d y = %d\n”, w, x, y);
return;
}

___________

View publication stats

You might also like