FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
CS3251-_PIC
1. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 1
DEPARTMENT OF HUMANITY AND SCIENCE
R2021 - SEMESTER II
CS3251 – PROGRAMMING IN C
KEY / CLASS NOTES
Through
PERSONALIZED LEARNING(PL)
2. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 2
UNIT I - BASICS OF C PROGRAMMING
PERSONALIZED ASSESSMENT LEARNING
SYLLABUS
UNIT I BASICS OF C PROGRAMMING 9
Introduction to programming paradigms – Applications of C Language - Structure of
C program - C programming: Data Types - Constants – Enumeration Constants -
Keywords – Operators: Precedence and Associativity - Expressions – Input / Output
statements, Assignment statements – Decision making statements - Switch statement -
Looping statements – Preprocessor directives - Compilation process.
TOTAL TOPICS: 15
1.INTRODUCTION TO PROGRAMMING PARADIGMS
1.1 Introduction to programming
Program : What is Program?
There is a close analogy between learning English language and learning C
language.
3. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 3
The classical method of learning English is to first learn the alphabets used in the
language, then learn to combine these alphabets to form words, which in turn are
combined to form sentences and sentences are combined to form paragraphs.
Learning C is similar and easier.
Instead of straight-away learning how to write programs, we must first know what
alphabets, numbers and special symbols are used in C, then how using them
constants, variables and keywords are constructed, and finally how are these
combined to form an instruction.
A group of instructions would be combined later on to form a program.
So a computer program is just a collection of the instructions necessary to solve a
specific problem. The basic operations of a computer system form what is known as
the computer’s instruction set. And the approach or method that is used to solve the
problem is known as an algorithm.
Computer Program : What is Computer Program ?
A set of related instructions or Code that does specific set of tasks using Computing
machine or Computer is called Program.
Example:
void main()
{
printf(“Added values of %d and %d = %d , 5,6, 5+6);
4. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 4
}
The above C code does only one specific task called Display a message with addition of
specific numbers such as 5 and 6 is 11 on the output window of a C runtime.
What is Programming?
An action or a set of actions that makes the Code or program ready for execution is
called Programming.
Example:
When an individual so called Programmer types the above code using any text editor
such as notepad or C Run time IDE (Integrated Development Environment) and Compile –
Verification of Syntax and then finally runs or executes that compiled code is called
programming of above C code or simply called C coding.
Types of Programming Languages
So for as programming language concern these are of two types.
1) Low level language
2) High level language
1. Based on Development of Computer Language generations, we have 1st
Generation,
2nd
Generation, 3rd
Generation and 4th
Generation Languages.
2. Thus C is the one of the 3rd
Generation Languages and also called High level
Language and Structures Query Language (SQL) is the 4th
generation Language.
The 1st
generation Language is the Low level Language which uses only 0’s and 1’s
and Assembly Language which uses Mnemonics or short names are called 2nd
generation Languages.
Low level language:
Low level languages are machine level and assembly level language. In machine
level language computer only understand digital numbers i.e. in the form of 0 and 1.
So, instruction given to the computer is in the form binary digit, which is difficult to
implement instruction in binary code.
This type of program is not portable, difficult to maintain and also error prone.
The assembly language is on other hand modified version of machine level
language.
Where instructions are given in English like word as ADD, SUM, MOV etc.
It is easy to write and understand but not understand by the machine. So the
translator used here is assembler to translate into machine level.
Although language is bit easier, programmer has to know low level details related to
low level language.
5. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 5
In the assembly level language the data are stored in the computer register, which
varies for different computer. Hence it is not portable.
High level language:
These languages are machine independent, means it is portable.
The language in this category is Pascal, Cobol, Fortran etc. High level languages are
understood by the machine.
So it needs to translate by the translator into machine level.
A translator is software which is used to translate high level language as well as low
level language in to machine level language.
Three types of translator are there:
1. Compiler
2. Interpreter
3. Assembler
Compiler and interpreter are used to convert the high level language into machine
level language.
The program written in high level language is known as source program and the
corresponding machine level language program is called as object program.
Both compiler and interpreter perform the same task but there working is different.
Compiler read the program at-a- time and searches the error and lists them.
If the program is error free then it is converted into object program. When program
size is large then compiler is preferred.
Whereas interpreter read only one line of the source code and convert it to object
code.
If it check error, statement by statement and hence of take more time.
1.2 Introduction to C
C is a programming language developed at AT & T’s Bell Laboratories of USA in
1972.
It was designed and written by a man named Dennis Ritchie.
The language was formalized in 1988 by the American National Standard Institute
(ANSI).
C is a successor of B language.
By 1973 UNIX OS almost totally written in C.
Today C is the most widely used System Programming Language.
Most of the state of the art software has been implemented using C.
Compiler vendors to release their ANSI C compilers and for them to become
ubiquitous.
It was initially designed for programming UNIX operating system.
6. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 6
1.3 Use of C
a) Now the software tool as well as the C compiler is written in C.
b) Major parts of popular operating systems like Windows, UNIX, Linux is still written
in C.
c) This is because even today when it comes to performance (speed of execution)
nothing beats C.
Why to use C ?
C was initially used for system development work, in particular the programs that
make-up the operating system.
C was adopted as a system development language because it produces code that runs
nearly as fast as code written in assembly language.
Some examples of the use of C might be:
a) Operating Systems
b) Language Compilers
c) Assemblers
d) Text Editors
e) Print Spoolers
f) Network Drivers
g) Modern Programs
h) Data Bases
i) Language Interpreters
j) Utilities
2. APPLICATIONS OF C LANGUAGE
The C language has its own set of features that makes difference with other Programming
languages.
Some of the Applications of C Language are as follows:
1. C Language is a Procedural Language.
2. C Language is Fast and Efficient.
3. C Language is also called Middle-Level Language.
4. The main features of C language include low-level access to memory, simple set of
keywords, and clean style, these features make C language suitable for system
programming like operating system or compiler development.
5. The operating system’s extend is achieved with the help of C Language is to work
with new devices one needs to write device driver programs. These programs are
exclusively written in C.
6. C Language Libraries with rich Functions.
7. C seems so popular is because it is reliable, simple and easy to use.
8. Often heard today is – “C has been already superseded by languages like C++, C#
and Java.
7. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 7
9. C Language structure promotes Modularity.
10.C Language statically Type.
11.General-Purpose Language.
12.Rich set of built-in Operators.
3. STRUCTURE OF A C LANGAUGE PROGRAM
The general structure of a C Language program is as follows:
1) Comment line(s)
2) Preprocessor directive(s)
3) Global variable declaration(s)
4) main function( ) declaration
1) Comment line(s)
Comments are the non-executable C statement or C command during the running of C
Code.
It indicates the purpose of the program.
It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the program.
It is useful in explaining the program and generally used for documentation.
It is enclosed within the decimeters. Comment line can be single or multiple line but
should not be nested.
It can be anywhere in the program except inside string constant & character
constant.
Types of Comments
a) Single Line Comment
Single line comment is that it starts and ends on a single line.
C single line comment starts from // and ends till the end of that line.
It is represented using the symbols: / / (double back slash) followed b sequence of
other symbols.
8. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 8
Example:
// A single line comment example is here
void main()
{
// This is a single line comment.
}
b) Multiline Comment
A multiline comment is that it starts in one line and it will end after n-number lie
spread where n- is the number lines.
It is represented using the symbols : / * ( a single back slash followed by sequence
of text spread in multiple lines.
That is, C multiline comment is between /* and */.
Example:
/* This
is
Multiple
Comment
*/
void main {
/* This
is
a
Multiline
Comment.
*/
}
Note that these two comments can make a very useful combination.
2) Preprocessor Directive(s)
It is a task done by C compiler before the start of the compiling the C Language Code.
The keyword Preprocessor insists that tasks done before compilation through Computer
Processor.
Two types of Preprocessor Directives
1) # include
9. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 9
2) # define
1) #include
It includes the designated header file ( filename.h) located anywhere from the
current drive.
#include<stdio.h> tells the compiler to include information about the standard
input/output library.
The stdio.h (standard input output header file) contains definition &declaration of
system defined function such as printf( ), scanf( ), pow( ) etc.
Generally printf() function used to display and scanf() function used to read value.
2) #define
It defines a new name for the constant value.
It is also used in symbolic constant such as #define PI 3.14(value).
That is,
#define PI 3.14
The above statement defines the name PI for the constant value 3.14.
Thus, we can use PI instead of 3.14 after this , anywhere in the current program.
3) Global Declaration(s):
This is the section where variable are declared globally so that it can be access by all the
functions used in the program. And it is generally declared outside the function.
4) main function( ) declaration
main() function
It is the user defined function and every function has one main() function from
where actually program is started and it is encloses within the pair of curly braces.
The main( ) function can be anywhere in the program but in general practice it is
placed in the first position.
Syntax:
Variations of main() function:
1) Simple main() function
void main()
{
10. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 10
Statement(s)
……..
}
2) main() function with retruns value to called function
The main ( ) function return value when it declared by data type as :
int main( )
{
return 0;
}
3) main() function with other function
void main()
{
Local variables;
Statements;
…
}
--user defined function declaration
retrun_type function_name( parameter(s)
{
Local variables;
Statements;
….
}
}
4) main() function does not return any value
The main function does not return any value when void (means null/empty) as
void main(void ) or void main()
{
printf (“C language”);
}
Output: C language
11. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 11
Note:
a) The program execution starts with opening braces and end with closing brace.
b) In between the two braces declaration part as well as executable part is mentioned.
c) At the end of each line, the semi-colon is given which indicates statement termination.
C program Example
//First c program with return statement
#include <stdio.h>
int main (void)
{
printf ("welcome to c Programming language.n");
return 0;
}
Output:
welcome to c programming language.
4. C PROGRAMMING: DATA TYPES
4.1 C Program Constructs or C Language Basics or C Tokens
The C language has program constructing parts or Tokens which are used during the
development of even a simple C program.
The following are the C tokens or C Language basics:
1. Character Set
2. Identifiers
3. Keywords
4. Data types
5. Constants
6. Variables and it's declaration
7. Operators and Expressions
Character Set
An allowed set of symbols which will be used to form any program elements such
as identifier, Variable name, constant, method name, etc. is called Character set of
C.
The following are the categories of symbols allowed in one version of C Language:
a) Numerals: 0 to 9 = 10
b) Alphabets: a to z
A to Z = 52
c) Special :
12. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 12
i) Operators: + - * / %
ii) brackets: [ ] ( ) { }
iii) Separators: , . ; :
iv) Quotes : ' "
v) Others: / | ~ & ! #
= < > ^ space
Note: The character set varied based versions of Language.
The above list is the one (C compiler) version's character set.
Identifiers:
A name that identifies any program elements such as variable, constant, Function
name, etc.
An identifier must begin with a letter, a dollar sign ($), or an underscore (_);
subsequent characters may be letters, dollar signs, underscores, or digits.
Uses of identifiers
Identifiers are used for variable names.
An identifier may be any sequence of uppercase and lowercase letters, numbers, or
the underscore and dollar-sign characters.
Identifiers must not begin with a number.
C Identifiers are case-sensitive.
Types of Identifiers
There are 2 types of Identifiers.
They are:
a) Standard Identifiers
b) User-defined Identifiers
a) Standard Identifiers
Those names that have a special meaning or a special note inside a C
compiler is called Standard Identifiers.
Example:
scanf
printf
getchar
Explanation:
Note that the above names are the names of standard functions of C Input
and /or Output. But they are only predefined identifiers.
b) User-defined Identifiers
Those names that are created by the programmer is called user-defined Identifiers
Thus a set of rules are exists within the C compiler in the form of Code that validated
the user-defined names or identifiers.
13. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 13
The following code illustrates some examples of valid identifiers:
void main {
int ATEST, count, i1, this_is_a_test;
}
}
The following code shows invalid variable names include:
void main {
int 2count, h-l, a/b,
}
Some examples are:
foobar // legal
Myclass // legal
$a // legal
3_a // illegal: starts with a digit
!theValue // illegal: bad 1st char
Note:
i) Identifiers are case sensitive.
For example, myValue and MyValue are distinct identifiers.
Rules forming an user-defined an identifier:
i) It should start with alphabet. But other subsequences may alphabet or
numerals or and an underscore( - ).
ii) It should not be a keyword or reserved words.
iii) Maximum length allowed is 1 to 255. However, the first 8 characters
must be different in case you form two identifiers.
For eg. filemanager1
filemanager2
iv) Only ( _ ) underscore special symbols is allowed.
Note:
a. However, there some rules that might be introduced in advanced versions of C
compiler.
b. You are required to refer the which version of Compiler that your are using for your
coding.
4.3 C DATA TYPES
14. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 14
4.3.1 Introduction Data Types
The data types are the group heading for major set of value types allowed in C
Language.
The data type lets to group various related values.
C has major set of different data types.
What is Data type?
Data types are the group heading for a particular set of values.
Each group falls under certain range of specific set of values.
For example,
A set of Integral values forms a data type called int which will gets only whole
numbers.
4.3.2 Types of Data types
There are four variations of Data types in C.
They are:
1) Primary or Standard or Primitive or Simple data types
2) Derived or Extended data types from Standard type(s)
3) Userdefined data types
3) Special Data types. - void
4.3.2.1 Standard or Primitive data types in C
C defines four simple data types:
a) int
b) float
c) double
d) char
C simple (data) types or C primitive data types can be put in four groups:
Simple types in C
Data type group Data type in C
Integers short, int, and long
Floating-point numbers float and double,
Characters Char
Primitive Data Types and their Effective Sizes
15. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 15
Type
Effective Representation Size
(bits)
Size in Bytes ( varies based
computer & compiler version)
Int 32 or 16 (based on the type of
Computer machine used 16 bits or
32 bits)
4 or 2
Float 32 4
double 64 8
Char 16 (UNICODE format) 2 or 1
Need of standard Primitive Types
The C language has the following primitive types and each has it’s own place in a C
coding:
a) Represent whole numbers: int
b) Represent Real numbers: float and double
c) Represent Characters: char ( which has equivalent numeric value called ASCII code)
Primitive Type Description Range
Char 16 bits (UNICODE) -128 to +127
Int 32 bits - 2,147,483,648 to +
2,147,483,647
Float 32 bits IEEE 754-1985 3.14 E-38 to 3.14E+38
Double 64 bits IEEE 754-1985 1.7E-308 to 1.7E+308
4.3.2.1.1 Augments for Data types
The augments that adds additional functionality and range limits set to the simple C data
types.
There are four augments that adds additional functionality to standard data types.
a) signed – an augment type that includes the value sign ( + - positive , - -negative before
the numeric values.
b) unsigned -an augment type that excludes the value sign ( + - positive , - -negative
before the numeric values.
c) short - an augment type that short range of decimal values up to int data type range.
d) long - an augment type that doubles the range..
Note:
1) The augments signed and unsigned have impact on range of values.
2) Default augment is signed.
For example :-
int i; OR signed int i ; are same.
3) If unsigned is used, the value range will be doubled,
For example :-
16. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 16
unsigned int i;
have impact on range values of int ( integer range) into double.
Reason : The negative range is removed in front (left side) and padded in right (right
side)
signed int - 2,147,483,648 to + 2,147,483,647
unsigned int + 2,147,483,647
2,147,483,648
---------------------
4,29,496,7295
______________
What could be the value ranges for following?
unsigned char ?
unsigned float ?
unsigned double ?
Type Effective Representation Size (bits)
short 16
long 64
double 64
Summary of Standard or Primitive Types in C
The C language has the following primitive types:
a) Represent numbers, characters and Integers:
char, short int, int, unsigned int, long int , unsigned long int
b) Represent real numbers:
float ,double , long double
c) Represent Characters:
char , unsigned char
Primitive Type Description Range values
char 1 Byte - 8bits -128 to +127
or 16 bits – 2 Bytes
( for UNICODE format)
short int 2 Bytes - 16 bits -32,767 to +32,767
int 4 Bytes - 32 bits -2,147,483,648 to
+2,147,483,647
Long int 8 Bytes - 64 bits -9,223,372,036,854,775,808 ..
to
17. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 17
+9,223,372,036,854,775,807
..
float 4 Bytes - 32 bits 3.14 E-38 to +3.14 E+38
double 8 Bytes - 64 bits 1.7 E-308 to +1.7 E+308
Data type Range of values
short -32,768 .. 32, 767 (16 bits) (-(2^15) to (2^15)-1 )
int -2,147,483,648 .. 2,147,483,647 (32 bits) (-(2^32) to (2^32)-1 )
long -9,223,372,036,854,775,808 .. ... (64 bits) (-(2^63) to (2^63)-1 )
float +/-10-38 to +/-10+38 and 0, about 6 digits precision
double +/-10-308 to +/-10+308 and 0, about 15 digits precision
char Unicode characters (generally 16 bits per char)
4.3.2 Derived Data Types
C Language facilitates making of extended data types from it’s primitive data types.
Thus C Language feature has been enhanced by making use of those derived types.
There four major derived data types allowed in C.
They are:
a) arrays
b) structures
c) union
d) pointers
a) arrays
Arrays are groups of related data types as a single type.
Arrays data types can be extended from int, float, char and double and thus we gets,
i) int array
ii) float array
iii) char array
iv) double array
b) Structures
Structures are groups of unrelated data types as a single type.
A single variable with qualifier operator called struct oprator (.) to be used to refer
individual members of structure group.
c) Union
Union is a special type which is capable of sharing the available memory to the
given additional union variable.
But it uses the maximum length of list of union types and so that at a time, a single
variable is in use.
18. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 18
d) Pointers
Pointer is a special data type used to access the memory directly.
This is possible with pointer operator such as “ * ” where adds meaning that
“address of” at its declaration point and “value at” in the C statement part.
4) Special Data type (void)
C Language handles all the situation where a “ null” value in its position will be
referred with the help of a special variable called void.
Void keyword adds special meaning that “nothing to be done” or “nothing to be
returned”.
4.4 VARIABLES
4.4.1 What are C variables?
Variables are memory location in computer's memory to store data.
To indicate the memory location, each variable should be given a unique name
called identifier.
Variable names are just the symbolic representation of a memory location.
4.4.2 Rules for forming Variable names
Note:
The rules of an identifier is same for the Variable name, since a variable name must
a valid user_defined identifier.
Rules for forming variable name in C
a) Variable name can be composed of letters (both uppercase and lowercase letters),
digits and underscore '_'and ‘$’ only.
b) The first letter of a variable should be either a letter or an underscore( _ ) or dollar
($). But, it is discouraged to start variable name with an underscore though it is
legal. It is because, variable name that starts with underscore can conflict with
system names and compiler may complain.
c) The length of a variable must be 1to the maximum of 255. . However, the first 31
characters of a variable are discriminated by the compiler. So, the first 31 letters of
two variables in a program should be different.
d) The keyword or reserved words are not allowed.
Variable Vs Identifiers
19. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 19
All variables must be valid identifiers but all identifiers need not be variables.
Memory blocks are named using variables where as the name itself is provided by
identifiers only.
Examples of variable name:
Valid:
sum, car_no,
count etc.
Invalid:
sum+
Reason : + is not allowed symbol.
int num;
Here, num is a variable of integer type.
In C programming, declare variable before using it in the program.
Declaration of variable
C has a concept of 'data types' which are used to define a variable before its use.
The definition of a variable will assign storage for the variable and define the type of
data that will be held in the location.
[storage_class] [augment] data_type V1, V2, . . . Vn[ =value1, value2, … valuen] ;
Where
storage_class is a storage specifier which decides the scope of the variable.
Note: scope decides the Time duration in which the variable is in live and the places where
these variables are allowed to use.
auto [automatic]
extern [external]
static
register
are the storage classes allowed.
Augment may any one of four type such as
signed
unsigned
short
long
Examples:
Valid : auto signed int i; is equivalent to
int i;
20. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 20
Invalid : unsign int k;
Reason : unsign is a not a augment allowed in C.
5. CONSTANTS
5.1 Introduction to C Constants
Constants refer to fixed values that do not change during the execution of a program.
Constant is a any value that cannot be changed during program execution.
In C, any number, single character, or character string is known as a constant.
A constant is an entity that doesn’t change whereas a variable is an entity that may
change.
For example, the number 50 represents a constant integer value.
The character string "Programming in C is fun.n" is an example of a constant character
string.
C constants can be divided into two major categories:
a) Primary Constants
b) Secondary Constants
These constants are further categorized as
Types of Primary Constants
a) Numeric constant
(i) Integer constant
(ii) Real constant
b) Character constant
(i) Single character constant
(ii) String constant
a) Numeric Constants
21. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 21
i) Integer constants
Integer constants are the numeric constants(constant associated with number) without any
fractional part or exponential part.
There are three types of integer constants in C language, which are used to represent the
values with special range.
a) decimal constant(base 10)
b) octal constant(base 8) and
c) hexadecimal constant(base 16) .
a) Decimal digits: 0 1 2 3 4 5 6 7 8 9
b) Octal digits: 0 1 2 3 4 5 6 7
c) Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
ii) Floating-point constants
Floating point constants are the numeric constants that have either fractional form or
exponent form.
For example:
-2.0
0.0000234
-0.22E-5
Note: Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022 floating –point Constants
b) Character constants
i) Single Character Constant
Character constants are the constant which use single quotation around characters.
For example: 'a', 'l', 'm', 'F' etc.
ii) String (character) Constant
String constants are the constant which use double quotation around characters.
For example: “ab” “hello” “John” etc.
Single Character Constant Vs String (character) Constant
Sl No Single Character String (character)
1 use single quotation around
character
use double quotation around characters
2 Length: 1 Length : Minimum 1 maximum: 255
3 Memory Length: 1 Byte Memory Length: Minimum 1 Byte
4 For example: 'a', 'l', 'm', 'F' etc. For example: “ab” “hello” “John” etc
22. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 22
LITERALS in C Language
What are Literals?
Literals are the constant values assigned to the constant variables.
We can say that the literals represent the fixed values that cannot be modified. It also
contains memory but does not have references as variables.
For example, const int =10; is a constant integer expression in which 10 is an integer
literal.
A constant value is a literal representation of a data type.
Note: The values of literals are used to represent the different range of values with
qualifier to designate short range with special symbol before the start digit.
For example ,
The literal 08 designates octal Integer representation of Integral literal 8.
Integer Type Family
Integer types
a) Integer Decimal(base ten) Literals
b) Octal (base eight) integer literals
c) Hadecimal (base 16) integer literals.
d) short type
e) int type
f) long int type
Integer types
C defines three integer types: short, int, and long.
Integer types are signed, positive and negative values.
The width and ranges of these integer types vary widely, as shown in this table:
Integer Types
Name Width Range
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 -2,147,483,648 to 2,147,483,647
Short 16 -32,768 to 32,767
Integer Decimal(base ten) Literals
The whole number which has combination digits with sign positive or negative
forms integer literal.
The symbols allowed are:
Digits: 0 to9
Special symbols: + -
23. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 23
For example, the following code defines integer literals:
void main()
{
int a = 100;
}
Any whole number value is an integer literal, for examples, 1, 2, 3, 100, 102.
The following code defines a shortvtype variable and assign 0 integer literal to it.
void main()
{
short b = 0;
printf("b is : %d" + b);
}
}
The output generated by this program is shown here:
b is 0
Octal (base eight) integer literals
In C language octal values are denoted by a leading zero.
The symbols allowed are:
Digits: 0 to 7
Special symbols: + -
Thus, 09 will produce an error from the compiler, since 9 is outside of octal's 0 to 7
range.
void main()
{
int i = 010;
printf(”%d”,i);
}
}
The output:
8
hexadecimal (base 16) integer literals.
A hexadecimal constant starts with a leading zero-x, (0x or 0X).
The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
24. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 24
In the following example, we define an integer with hexadecimal integer literal.
void main()
{
int f = 0XFFFFF;
printf(“%f”,f);
}
}
The code above prints out the following:
1048575
short type
short is a signed 16-bit type.
short type value has a range from -32,768 to 32,767.
Here are some examples of short variable declarations:
void main()
{
short s;
short t;
}
}
int type
int type is a signed 32-bit type that has a range from -2,147,483,648 to 2,147,483,647.
void main()
{
int i = 10;
int j = 10;
printf(“%d” ,i+j);
}
}
The output:
20
25. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 25
long type
long is a signed 64-bit type. long type is useful when an int type is not large enough to hold
the value.
void main()
{
long lightspeed;
long days;
long seconds;
long distance;
lightspeed = 300000;
days = 365;
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
printf("In : %ld" + days);
printf(" days light will travel about ");
printf(“%l d” , distance + " km.");
}
}
This program generates the following output:
In 365 days light will travel about 9460800000000 km.
long literal
To specify a long literal, you can append an upper-or lowercase L to the literal.
For example, 0x7ffffffffffffffL or 987654321234567899876L.
void main()
{
long l = 0x7ffffffffffffffL;
printf( "l is %ld” + l);
}
}
The output generated by this program is shown here:
l is 576460752303423487
Floating Point Types
There are two kinds of floating-point types: float and double.
26. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 26
float type represents single-precision numbers.
double type stores double-precision numbers.
a) float type
b) float type literal
c) double type
d) double Floating-Point Literals
float type
Floating-Point Types has whole part and decimal part.
The type float specifies a single-precision value.
float type uses 32 bits of storage.
float type variables are useful when you need a fractional component.
The width and ranges are shown here:
Floating-Point Types
Name Width in Bits Approximate Range
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 1.1E+4932
Here are some example float variable declarations:
void main() {
float high, low;
}
}
float type literal
Floating-point literals in Java default to double precision. To specify a float literal, you
must append an F or f to the constant.
public static void main(String[] argv) {
float f = 1.1f;
System.out.println("f is " + f);
}
}
The output generated by this program is shown here:
f is 1.1
27. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 27
double type
double type is for Double precision.
double type uses 64 bits to store a value.
Here is a short program that uses double variables to compute the area of a circle:
void main()
{
double pi, r, a;
r = 10.8888; // radius of circle
pi = 3.1415926; // pi, approximately
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
The output:
Area of circle is 372.4859596381597
double Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component.
Floating-point numbers can be expressed in either standard or scientific notation.
The following code uses the standard notation.
void main()
{
double d1 = 2.0;
double d2 = 3.14159;
double d3 = 0.6667;
printf("d1 is %f” , d1);
printf ("d2 is %f" d2);
printf ("d3 is %f", d3);
}
The output generated by this program is shown here:
d1 is 2.0
d2 is 3.14159
d3 is 0.6667
28. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 28
Scientific notation
Scientific notation uses a standard-notation, plus a suffix that specifies a power of 10.
The exponent is indicated by an E or e followed.
The exponent can be positive or negative.
void main()
{
double d1 = 6.022E23;
double d2 = 314159E-05;
double d3 = 2e+100;
printf("d1 is %f” , d1);
printf ("d2 is %f" d2);
printf ("d3 is %f", d3);
}
}
The output generated by this program is shown here:
d1 is 6.022E23
d2 is 3.14159
d3 is 2.0E100
You can explicitly specify a double literal by appending a D or d.
The default double type consumes 64 bits of storage.
The float type requires only 32 bits.
void main()
{
double d = 1.1d;
printf("d is %d" + d);
}
}
The output generated by this program is shown here:
d is 1.1
Character
Using Characters
Using char value as integer
Character Literals
Escape sequences for Java char type
Using Characters
29. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 29
char type variables store characters. Java char is a 16-bit type.
The range of a char is 0 to 65,536.
There are no negative chars.
Characters in Java can be converted into integers and manipulated with the integer
operators.
C uses ASCII (American Code for Information and Interchange) to represent
characters.
Here is a program that demonstrates char variables:
Void main() {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
printf("ch1 and ch2: %c, %c, ch1, ch2 );
printf (“%c %c ”, ch1 , ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y
ch1 is assigned the int value 88, which is the ASCII and Unicode value that represents the
letter X.
Using char value as integer
You can operate on char type variables as if they were integers. For example, consider the
following program:
void main()
{
char ch1;
ch1 = 'X';
printf( "ch1 contains %c" + ch1);
ch1 = (char)(ch1 + 1); // increment ch1
printf( "ch1 is now %c " + ch1);
}
}
In the program, ch1 is first given the value X. Then, ch1 is incremented.
This results in ch1 containing Y, the next character in the ASCII (and Unicode)
sequence.
30. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 30
You have to cast ch1 + 1 back to char type since after adding 1 to ch1 the result
becomes int type.
The output generated by this program is shown here:
ch1 contains X
ch1 is now Y
Character Literals
A literal character is represented inside a pair of single quotes.
void main()
{
char ch = 'a';
printf(“ch is %c" + ch);
}
}
The output generated by this program is shown here:
ch is a
All of the visible ASCII characters can be directly entered inside the quotes, such as 'a', 'z',
and '@'.
void main()
{
char ch = '@';
printf( "ch is %c" + ch);
ch = '#';
printf( ("ch is " + ch);
ch = '$';
printf( "ch is %c" + ch);
ch = '%';
printf("ch is " , ch);
}
}
The output generated by this program is shown here:
ch is @
ch is #
ch is $
ch is %
31. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 31
Escape sequences for C char type
Escape sequences are for characters that are impossible to enter directly.
To enter the single quote character itself, you 'escape' it by placing a backslash in
front of it.
void main()
{
char ch = ''';
printf( "ch is %c " , ch);
}
}
The output generated by this program is shown here:
ch is '
The following table shows the character escape sequences.
Escape Sequence of C
Escape Sequence Description
' Single quote
" Double quote
Backslash
r Carriage return
n New line (also known as line feed)
f Form feed
t Tab
b Backspace
ESCAPE SEQUENCES (BACKSLASH CHARACTER CONSTANTS)
ASCII Value Escape Sequences Meaning
000 0 Null
007 a Audible alter (bell)
008 b Backspace
009 t Horizontal tab
010 n New line
011 v Vertical tab
012 f Form feed
013 r Carriage return
32. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 32
034 ” Double quote
039 ’ Single quote
063 ? Question mark
092 Backslash
Examples
'n' is for the newline character.
For octal notation use the backslash followed by the three-digit number.
For example, '141' is the letter 'a'.
For hexadecimal, you enter a backslash-u (u), then four hexadecimal digits.
For example, 'u0061' is the ISO-Latin-1 'a'.
6. ENUMERATED CONSTANTS
6.1 Enumeration or enum USER DEFINED DATA TYPE
Enumeration or Enum in C is a special kind of data type defined by the user.
It consists of constant integrals or integers that are given names by a user.
The use of enum in C to name the integer values makes the entire program easy to
learn, understand, and maintain by the same or even different programmer.
For example , to process the days of week with constant values such as Sun, Mon, Tue,
Wed, Thu, Fri, Sat , we are formulating an enumeration as
{Sun, Mon, Tue, Wed, Thu, Fri, Sat}
To refer all the 7 –constant values, we relate it with a single variable called
“days_of_week” by declaring an enum variable as:
enum days_of_week {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
enum days_of_week;
Where
Sun, Mon, Tue, Wed, Thu, Fri, Sat are called enumerators
enum is the keyword
Days_of_week is enum variable
6.2 Syntax to Define enum in C
An enum is defined by using the ‘enum’ keyword in C, and the use of a comma separates
the constants within.
The basic syntax of defining an enum is:
enum enum_name{int_const1, int_const2, int_const3, …. int_constN};
33. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 33
In the above syntax, the default value of int_const1 is 0, int_const2 is 1, int_const3 is 2, and
so on.
However, you can also change these default values while declaring the enum.
Enumerated Type Declaration to Create a Variable
Similar to pre-defined data types like int and char, you can also declare a variable
for enum and other user-defined data types.
Here’s how to create a variable for enum.
The steps are there for enum declaration:
a) enum type declaration
b) enum variable declaration
a) enum type declaration
The following declaration define the enum
enum type (true, false); //declaring the enum
enum type e; //creating a variable of type
Suppose we have declared an enum type named type; we can create a variable for that data
type as mentioned above.
We can also converge both the statements and write them as:
enum type (true, false) e;
For the above statement, the default value for true will be 1, and that for false will be 0.
How to Create and Implement Enum in C Program?
Now that we know how to define an enum and create variables for it, let’s look at some
examples to understand how to implement enum in C programs.
Example 1: Printing the Values of Weekdays
#include <stdio.h>
enum days{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main(){
// printing the values of weekdays
34. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 34
for(int i=Sunday;i<=Saturday;i++){
printf("%d, ",i);
}
return 0;
}
Output:
In the above code, we declared an enum named days consisting of the name of the
weekdays starting from Sunday.
We then initialized the value of Sunday to be 1. This will assign the value for the
other days as the previous value plus 1.
To iterate through the enum and print the values of each day, we have created a for
loop and initialized the value for i as Sunday.
Example 2: Assigning and Fetching Custom Values of Enum Elements
#include<stdio.h>
int main(){
// Initializing a variable to hold enums
enum containers{
cont1 = 5,
cont2 = 7,
cont3 = 3,
cont4 = 8
};
enum containers cur_cont = cont2;
printf("Value of cont2 is = %d n", cur_cont);
cur_cont = cont3;
printf("Value of cont3 is = %d n", cur_cont);
cur_cont = cont1;
printf("Value of hearts is = %d n", cur_cont);
return 0;
}
Output:
35. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 35
We have declared an enum named containers with four different containers as the
elements in the above code.
We have then given custom values to the elements and initialized the variable for the
enum multiple times to print the relevant output.
The steps to make use of enum in C Coding are
1)Enumeration:
We formulate an enumeration as
enum day_of_week {Sun, Mon, Tue, Wed, Thu, Fri, Sat}
As part of declaration the positional sequence number starting from 0 to n-1 where n
is the number of enumeration values will be assigned as:
Sun 0 Mon 1 Tue 2 Wed 3 Thu 4 Fri 5 Sat 6
2) Instantiation
enum days_of_week;
3) Using a C code
days_of_week = Wed;
Thus, days-of_week get the sequence value 3.
Also printf(“%d”, days_of_week[5]); will display Fri as output.
Why Do We Use Enums in C?
We use enums for constants, i.e., when we want a variable to have only a specific set
of values.
For instance, for weekdays enum, there can be only seven values as there are only
seven days in a week. However, a variable can store only one value at a time.
We can use enums in C for multiple purposes; some of the uses of enums are:
To store constant values (e.g., weekdays, months, directions, colors in a rainbow)
For using flags in C
While using switch-case statements in C
36. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 36
7. Keywords
Keywords are the reserved names within a particular version of a Compiler.
Keywords and reserved words may not be used as identifiers.
List of Keywords vary based on the version of compilers that you use.
Keywords Vs Standard Identifiers
A keyword is a name or word which is defined by the programming language.
The standard identifier is a name or word which meaning is defined by the
programming language.
Keywords must not be used as Variables
But Standard Identifiers should not be used as a variables.
Note:
Your refer any C programming text book . The complete list of keywords were
listed in the Appendix.
A sample list of C Keywords or Reserved Words are as follows:
if switch case while do for break
continue goto else case auto extern
static register signed unsigned int float
double char struct union enum typedef
file const byte short long return
sizeof volatile default
A sample list of C standard identifiers is:
scanf printf getchar putchar gets puts
fread fwrite fscanf fprintf
rnd sqrt
clrscr gotoxy
Note : All the predefined function names that are declared under any particular
header file falls under standard identifiers
8. OPERATORS : PRECEDENCE AND ASSOCIATIVITY
8.1 Introduction to Operators and Operands
Operands
A constant or an assigned value or a Literal that is used for performing the predefined
operations on the specific Operator is called operand.
Operators
37. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 37
Operators are the symbol which operates on value or a variable.
8.2 Categories of Operators
Sometime operators are divided according numbers of operands.
So there are three categories of operators as follows:
Types of Operators in C
There are mainly operators in C as following:
1) Arithmetic Operators
2) Relational Operators
3) Logical Operators
4) Assignment Operators
5) Increment and Decrement operators
6) Bitwise Operators
7) Sizeof Operators
8) Comma operators
9) Type cast operator
10) Conditional operators or ternary operators
S.no Types of Operators Description
1 Arithmetic_operators These are used to perform mathematical
calculations like addition, subtraction,
multiplication, division and modulus
2 Assignment operators These are used to assign the values for the
variables in C programs.
3 Relational operators These operators are used to compare the value
of two variables.
4 Logical operators These operators are used to perform logical
operations on the given two variables.
38. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 38
5 Bit wise operators These operators are used to perform bit
operations on given two variables.
6 Conditional (ternary) operators Conditional operators return one value if
condition is true and returns another value is
condition is false.
7. Increment / decrement operators These operators are used to either increase or
decrease the value of the variable by one.
8 Special operators &, *, sizeof( ) and ternary operators
1) Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra.
The following table lists the arithmetic operators:
Operator Result
+ Addition
- Subtraction (unary minus)
* Multiplication
/ Division
% Modulus
Given table shows all the Arithmetic operator supported by C Language. Lets
suppose variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0
2) Relational Operators
The relational operators determine the relationship between two operands.
The relational operators are:
Operator Result
39. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 39
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Which can be used to check the Condition, it always return true or false. Lets suppose
variable A hold 8 and B hold 3?
3) Logical Operators
The logical operators operate only on Boolean operands.
Which can be used to combine more than one Condition?.
Suppose you want to combined two conditions A<B and B>C, then you need to use
Logical Operator like (A<B) && (B>C).
Here && is Logical Operator.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
40. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 40
Operator Result
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
? : Ternary if-then-else
Truth table of Logical Operator
C1 C2 C1 && C2 C1 || C2 !C1 !C2
T T T T F F
T F F T F T
F T F T T F
F F F F T T
4) Assignment Operators
The assignment of value to a single variable.
We can do multiple assignments of values to assign and perform a set of special
Assignment Operations.
C has three types of Assignment operations:
a) Simple Assignment
b) Multiple Assignments
c) Special Assignment
a) Simple Assignment
Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True
41. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 41
Syntax:
[data-type] variable-name = value;
b) Multiple Assignment
Syntax:
data-type Variable_n = Variable_n-1 = Variable_n-1 = … Variable_1;
c) Special Assignment
Special Assignment are possibly using ARITHMETIC OPERATORS (+ - * / % ) together
with Assignment Operator ( = )
Syntax:
[data-type] variable-name [+ - * / % ] = value;
include <stdio.h>
int main()
{
`
w/*Declaration of C variables with default assignment values – Simple Assignment
*/
int a = 7,b,c;
int Total = 21;
printf(" INITIAL Values of a= %d , b =%d and c=%dn", a,b,c );
/* MULTIPLE ASSIGNMENT */
c=b=a;
/* Here value of a has been copied or replicated into other two variables such as b and c.
*/
/* Special Assignment are possibly using ARITHMETIC OPERATORS (+ - * / % )
together with Assignment Operator ( = )
*/
printf(" CURRENT Values of a= %d , b =%d and c=%dn", a,b,c );
printf(" CURRENT Values after SPECIAL ASSIGNMENT are:n”);
printf(" Value of the Total = %d n", Total += a );
printf(" Value of the Total = %d n", Total -= a );
42. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 42
printf(" Value of the Total = %d n", Total *= a );
printf(" Value of the Total = %d n", Total /= a );
printf(" Value of the Total = %d n", Total %= a );
return 0;
}
The operands of the arithmetic operators must be of a numeric type.
Which can be used to assign a value to a variable?
Lets suppose variable A hold 8 and B hold 3.
5) Bitwise Operators
C Bitwise operators can be applied to the integer types: long, int, short, char, byte.
Bitwise Operators act upon the individual bits of their operands.
Bitwise Operators
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
a=b Value of b will be assigned to a
43. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 43
Operator Result
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
Bit operations
Applied to char, int, short, long
And &
Or |
Exclusive Or ^
Left-shift <<
Right-shift >>
one's complement ~
Bit Count
/*
count the 1 bits in a number
e.g. bitcount(0x45) (01000101 binary) returns 3
*/
int bitcount (unsigned int x) {
int b;
for (b=0; x != 0; x = x >> 1)
if (x & 01) /* octal 1 = 000000001 */
b++;
return b;
}
6) Conditional (ternary) operators
If any operator is used on three operands or variable is known as Ternary Operator.
It can be represented with ? : .
It is also called as conditional operator
Advantage of Ternary Operator
Using ?: reduce the number of line codes and improve the performance of application.
44. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 44
Syntax:
Expression 1? Expression 2: Expression 3;
In the above symbol expression-1 is condition and expression-2 and expression-3 will be
either value or variable or statement or any mathematical expression.
If condition will be true expression-2 will be execute otherwise expression-3 will be
executed.
Conditional expressions
expr1? expr2:expr3;
if expr1 is true then expr2 else expr3
f r (i ; i n; i )
printf("%6d %c",a[i],(i%10==9||i==(n-1))?'n':' ');
Example:
find largest number among 3 numbers using ternary operator #include<stdio.h>
void main()
{
int a,b,c,large;
45. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 45
printf(“Enter any three numbers:”); scanf(“%d%d%d”,&a,&b,&c);
large=a>b?(a>c?a:c):(b>c?b:c);
printf(“The largest number is:%d”,large);
}
Output:
Enter any three numbers: 12 67 98
The largest number is 98
7) Increment Decrement Operators
Increment Operators are used to increased the value of the variable by one and
Decrement Operators are used to decrease the value of the variable by one in
C programs
Both increment and decrement operator are used on a single operand and variable,
so it is called as a unary operator.
Unary operators are having higher priority than the other operators it means unary
operators are executed before other operators.
Increment and decrement operators are cannot apply on constant.
The operators are ++, --
Type of Increment Operator
a) pre-increment
b) post-increment
a) pre-increment (++ variable)
In pre-increment first increment the value of variable and then used inside the expression
(initialize into another variable).
Syntax:
++variable
b) post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another
variable) and then increment the value of variable.
Syntax:
variable++
8) Comma operator
1) Comma as an operator:
46. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 46
The comma operator (represented by the token, ) is a binary operator that evaluates
its first operand and discards the result, it then evaluates the second operand and
returns this value (and type).
The comma operator has the lowest precedence of any C operator, and acts as a
sequence point.
/* comma as an operator */
int i = (5, 10); /* 10 is assigned to i*/
int j = (f1(), f2()); /* f1() is called (evaluated) first followed by f2().
The returned value of f2() is assigned to j */
2) Comma as a separator:
Comma acts as a separator when used with function calls and definitions, function
like macros, variable declarations, enum declarations, and similar constructs.
Why do we use the comma operator in C language?
The comma operator is basically a binary operator that initially operates the first
available operand, discards the obtained result from it, evaluates the operands
present after this, and then returns the result/value accordingly.
The comma sign is used for mainly two different purposes in the C language – as an
operator and as a separator.
Thus, its behavior is very different according to where we place/use it in a program.
9) sizeof opearator
It is a compile time unary operator which can be used to compute the size of its
operand.
The result of sizeof is of unsigned integral type which is usually denoted by size_t.
sizeof can be applied to any data-type, including primitive types such as integer and
floating-point types, pointer types, or compound datatypes such as Structure, union
etc.
Usage
sizeof() operator is used in different way according to the operand type.
1. When operand is a Data Type.
When sizeof() is used with the data types such as int, float, char… etc it simply returns the
amount of memory is allocated to that data types.
Let’s see example:
int main()
{
printf("%lun", sizeof(char));
printf("%lun", sizeof(int));
printf("%lun", sizeof(float));
printf("%lu", sizeof(double));
return 0;
}
47. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 47
2. When operand is an expression.
When sizeof() is used with the expression, it returns size of the expression.
Let see example:
#include <stdio.h>
int main()
{
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
return 0;
}
Output:
8
Need of Sizeof () operator
1. To find out number of elements in a array.
Sizeof can be used to calculate number of elements of the array automatically.
sizeof() is a compile time operator. compile time refers to the time at which the
source code is converted to a binary code. It doesn’t execute (run) the code inside
2. To allocate a block of memory dynamically.
sizeof is greatly used in dynamic memory allocation.
For example, if we want to allocate memory for which is sufficient to hold 10 integers and
we don’t know the sizeof(int) in that particular machine.
Operators in C, in Descending Order of Precedence
The operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
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
48. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 48
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right
Type casting in C
An automatic conversion is value into a simple integer then one can type cast long to cast
operator
a) LVALUES
In declaration, it point variables
b) RVALUES
In declaration, it point data item , where data item can be Literals
(constants), Initialized Variables, expressions
Consider the following example where the cast operator causes the division of one
integer variable by another to be performed as a floating-point operation:
#include <stdio.h>
main()
{
int sum = 17, count = 5;
double mean;
mean = (double) sum / count;
printf("Value of mean : %fn", mean );
}
9. EXPRESSIONS
9.1 Introduction to expressions
What is expression in C?
• An expression in C is a combination of operands and operators – it computes a
single value stored in a variable.
• The operator denotes the action or operation to be performed. The operands are the
items to which we apply the operation.
• An expression is a formula in which operands are linked to each other by the use of
operators to compute a value.
• An operand can be a function reference, a variable, an array element or a constant.
Example:
a-b;
49. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 49
In the above expression, minus character (-) is an operator, and a, and b are the two
operands.
9.2 Types of Expressions in C
There are four types of expressions exist in C:
a) Arithmetic expressions.
b) Relational expressions.
c) Logical expressions.
d) Conditional expressions.
Each type of expression takes certain types of operands and uses a specific set of operators.
Evaluation of a particular expression produces a specific value.
For example:
x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is an
expression.
a) Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic
operators. An arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer
expression when it contains only real operands, it is known as pure real expression,
and when it contains both integral and real operands, it is known as mixed mode
expression.
Evaluation of Arithmetic Expressions
The expressions are evaluated by performing one operation at a time.
The precedence and associativity of operators decide the order of the evaluation of
individual operations.
When both the operands are of type integer, then arithmetic will be performed, and
the result of the operation would be an integer value.
For example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.
When both the operands are of type float, then arithmetic will be performed, and the
result of the operation would be a real value.
For example, 2.0/2.0 will yield 1.0, not 1.
If one operand is of type integer and another operand is of type real, then the mixed
arithmetic will be performed.
50. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 50
In this case, the first operand is converted into a real operand, and then arithmetic is
performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first
value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.
b) Relational Expressions
A relational expression is an expression used to compare two operands.
It is a condition which is used to decide whether the action should be taken or not.
In relational expressions, a numeric value cannot be compared with the string value.
The result of the relational expression can be either zero or non-zero value. Here, the
zero value is equivalent to a false and non-zero value is equivalent to true.
c) Logical Expressions
A logical expression is an expression that computes either a zero or non-zero value.
It is a complex test condition to take a decision.
10. INPUT AND OUTPUT STATEMENTS, ASSIGNMENT
STATEMENTS
10.1 Reading and Writing data
a) Reading and Writing Integers
The nature of getting Input values from outside world and store them into the
computer is called Reading Inputs.
Then the opposite operation where data are written or printed on screen is the
writing process.
Thus the type of values that are handled during Reading and Writing process decides
the type of C statements to be used.
ANSI standard has defined many library functions for input and output in C
language.
Functions printf() and scanf() are the most commonly used to display out and take
input respectively.
b) Reading and Writing Floating point
float single-precision floating-point
double double-precision floating-point
long double extended-precision floating-point
c) Reading and Writing character
51. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 51
Reading of Characters are simple Input process where each input (read) is implemented
using Character input Stateme
‘a‘, ‘t’, ‘n’, ‘0’, etc. are character constants
strings: character arrays
− (see <string.h> for string functions)
− "I am a string"
− always null (‘0’) terminated.
− 'x' is different from "x"
10.2 Input or reading data in C
The following is the C Input statements or Input functions allowed:
a) Single Character Input
b) String Input
c) Complicated Input
a) Single Character Input
1) getchar()
2) gets()
3) scanf()
There are 3-types of Single character input statements or functions in C :
1) getchar():getchar() is used to get or read the input (i.e a single character) at run
time.
Syntax:
character_variable =getchar();
Example :
char ch;
ch = getchar();
2) getch(): getch() is used to get a character from console but does not echo to the
screen
Syntax:
getch();
Example :
getch();
3) getche(): reads a single character from the keyboard and echoes it to the current text
window, using direct video or BIOS.
52. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 52
Syntax:
getche();
Example :
getche();
b) String Input Statement
gets(): reads characters from the standard input stream until an end-of-line or
character or character sequence is seen, or until the end of file, whichever comes
first.
char name[65];
gets(name);
c) Complicated Input
scanf ( )
[ Int_variable = ] scanf(“c ntr l strings”, arg1, arg2, . . . argn);
Where,
Int_variable will hold the number of input values read from the input device.
arg1, arg2, … argn are declared variables preceded with ‘&’ symbol.
& - symbol designates that “address of”
How scanf() works?
scanf() is controlled by the conversion specification
In the format string starting from left to right.
When called, it tries to locate an item of the appropriate type
In the input data, skipping white-space characters(the space,
Horizontal and vertical tab, form-feed, and new-line character)
Example
#include<stdio.h>
int main()
{
int c;
printf("Enter an Integer :”);
scanf(“%d",&c);
printf(“Entered value for c =%d”,c);
return 0;
}
Output
53. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 53
Enter an Integer: 5
Entered value for c = 5
10.3 Output or writing data in C
Output Functions
a) Single Character output Function
b) String output Function
c) Complicated Input Function
a) Single Character output Function
putchar() : The C library function int putchar(int char) writes a character (an
unsigned char) specified by the argument char to stdout.
Syntax:
putchar(character_variable);
b) String output Function
puts() The C library function int puts(const char *str) writes a string to stdout up to
but not including the null character. A newline character is appended to the output.
c) Complicated Input Function
printf()
printf( ) statement
The printf() statement is an output statement that gets values of given argument(s) from
designated memory location(s), then applies formatting if any.
Finally display them on the screen.
In a summary, display or print the values of arg1, arg2.. argn from the memory into screen.
Syntax:
[int_variable ] printf(“c ntr l strings”, arg1, arg2, . . . argn) ;
Control strings denotes ordinary characters and conversion specifications (%)
%d --- int
%s --- string
%f --- float
Conversion Specification
%[-]m.pX
m: specifies the minimum number of characters to print.
%4d-- _123; %-4--123_
54. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 54
p: depends on the choice of X
X:
-d: decimal form
-e: floating-point number in exponential format
-f: floating-p int number in “fixed decimal” f rmat
-g: either exponential format or fixed decimal format,
depending n the number’s size
Example
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
Output
C Programming
Explanation of how this program works
Every program starts from main() function.
printf() is a library function to display output which only works if
#include<stdio.h>is included at the beginning.
Here, stdio.h is a header file (standard input output header file) and #include is
command to paste the code from the header file when necessary.
When compiler encounters printf() function and doesn't find stdio.h header file,
compiler shows error.
Code return 0; indicates the end of program.
You can ignore this statement but, it is good programming practice to use return 0;.
Example
#include <stdio.h> //This is needed to run printf() function.
int main()
{
int i,j;
float x;
printf("C Programmingnn"); //displays the content inside quotation
printf("i=%d, j=%d. x=%fn", i, j, x);
return 0;
}
Output
55. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 55
Explanation of how this program works
a. Every program starts from main() function.
b. printf() is a library function to display output which only works if
#include<stdio.h>is included at the beginning.
c. Here, stdio.h is a header file (standard input output header file) and #include is
command to paste the code from the header file when necessary.
b) When compiler encounters printf() function and doesn't find stdio.h header file,
compiler shows error.
a. Code return 0; indicates the end of program.
c) You can ignore this statement but, it is good programming practice to use return 0;.
10.3 Formatted Input and Formatted Output
Inside quotation of scanf() and printf() functions , there is a conversion format string "%d"
(for integer).
If this conversion format string matches with remaining argument,i.e, C in this case, value
of c is displayed.
Format Specifier Type of Argument
Input
%c Character Reads a single character
%d or %i Integer Reads a decimal integer
%e or %E or
%f or %g or
%G Floating point Reads a floating point value
%hd or %hi Short integer Reads decimal short integer
%hu Short integer Reads decimal unsigned short integer
%ld or %li Long integer Reads decimal long integer
%le or %lf or Double Reads signed double
%lg
%Le or %Lf or
%Lg Long double Reads signed long double
%lo Long integer Reads an octal long integer
%lu Long integer Reads decimal unsigned long integer
%lx Long integer Reads hexadecimal long integer
%o Octal integer Reads an unsigned octal integer
56. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 56
%s Sequence of characters Reads a string
%u Integer Reads an unsigned decimal integer
%x or %X Hexadecimal integer Reads a unsigned hexadecimal integer
Example 1:
// Program to display output with different output format choices.
#include<stdio.h>
void main()
{
int i = 40;
float x = 839.21;
printf("|%d|%5d|%-5d|%5.3d|n", i, i, i, i);
printf("|%10.3f|%10.3e|%-10g|n", x, x, x);
}
Output:
Example 2:
// Program for different types of Data inputs and display in C
#include<stdio.h>
void main()
{
short int si;
unsigned int ui;
int i;
long int li;
printf("n Enter short Integer value for si=");
scanf("%hd", &si);
printf(" The short integer si= %hdn", si);
printf("n Enter an Integer value for i=");
scanf("%d", &i);
printf(" The integer i= %dn", i);
printf("n Enter long Integer value for li=");
scanf("%ld", &li);
57. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 57
printf(" The long integer li= %ldn", li);
printf(" The an integer ui=");
scanf("%u", &ui); /* reads u in base 10 */
printf("%u", ui); /* writes u in base 10 */
printf(" Enter an octal [0 to 7 digits] integer ui=");
scanf("%o", &ui); /* reads u in base 8 */
printf("The octal [0 to 7 digits] integer ui=%on", ui); /* writes u in base 8 */
printf(" Enter an Hexadecimal [0 to 9 and a to f] integer ui=");
scanf("%x", &ui); /* reads u in base 16 */
printf(" The an Hexadecimal [0 to 9 and a to f] integer ui=%xn", ui);
/* writes u in base 16*/
double db;
long double ldb;
printf(" Enter the an doulbe [ more than 10 digits] db=");
scanf("%lf", &db);
printf(" Enter the long double[ more than 20 digits] ldb=");
scanf("%Lf", &ldb);
printf("The double value = %en", db);
printf("The long double value =%Lfn", ldb);
char ch;
i = 'a'; /* i is now 97 */
ch 65; /* ch is n w ‘a’ */
ch ch 1; /* ch is n w ‘c’ */
printf(" The character value in ch= %cn", ch);
ch ; /* ch is n w ‘c’ */
printf(" The current character value in ch= %cn", ch);
}
Output
58. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 58
10.4 ASSIGNMENT STATEMENTS
10.4 .1 Assignment Statements
The simple C statement is formed with an expression and output variable which
holds the result after the evaluation of it.
The condition for assignment statement is that the syntax must form an algebraic
like expression.
Thus the result of the evaluated expression will be assigned to the output variable.
Syntax:
A simple Assignment statement should have the following syntax:
Variable = value;
Where
Variable is a valid C variable name
value may a constant or an initialized variable Or list of initialized variables or a
valid a expression.
Example:
int a, result;
float f, output;
a= 10;
result = a+5;
59. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 59
f = 2.5;
output = f+ 1.0;
Types of Assignment Statements
C has three types of Assignment statements:
a) Simple Assignment statement
b) Multiple Assignment statement
c) Special Assignment statement
a) Simple Assignment statement
A variable with an expression and/ or initialized variable in the form of algebraic like
equation forms the simple assignment statement.
Syntax:
i) At the declaration point
[data-type] variable-name = value;
ii) At the C program statement (within main() )
variable-name = value;
Example:
int k;
k=k+10;
b) Multiple Assignment statement
i) At the declaration point
Syntax:
data-type Variable_n = Variable_n-1 = Variable_n-1 … Variable_1;
ii) At the C program statement (within main() )
Syntax:
Variable_n = Variable_n-1 = Variable_n-1 … Variable_1;
Examples:
60. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 60
int a,b,c =10;
int x,y,z;
z = x=y;
c) Special Assignment statement
Special Assignment are possibly using ARITHMETIC OPERATORS (+ - * / % ) together
with Assignment Operator ( = )
Syntax:
[data-type] variable-name [+ - * / % ] = value;
Example:
int i=1, j= 10;
i +=1;
j /=5;
The current value of i is 2 ( since i +1 does i=i+1 )
The current value of j becomes 2 ( since j /= 5 does j=j/5 or j = 10/5 )
11. C Control Statements: Decision making statements
11.1 CONTROL STATEMENTS OR DECISION MAKING STRUCTURES
Decision making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed.
If the condition is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
Show below is the general form of a typical decision making structure found in most
of the programming languages −
a) Sequential control structure
b) Selective control structure
c) Iterative control structure
a) Sequential Control Structure
The normal flow of control of all programs is sequential.
In sequential structure, a sequence of programs statements are executed one after
another in the order in which they are placed.
Both selection and repetition statements allow allow the programmer to alter the
normal sequential flow of control.
61. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 61
Sequential programming can also be called linear programming.
The sequential programs are non-modular in nature. That is, reusability of code is
not possible.
Thus, they are difficult to maintain and understand.
Examples of sequence control structure statements are, the program will have
statements that are placed sequentially and there is no decision involved in the
process.
Also, the program does not require a specific task to be repeated over and over
again.
b) Selective Control Structure (or) Decision Control Structure
The selective structure allows the usual sequential order of execution to be modified.
It consists of a test for a condition followed by alternative paths that the program can
follow.
The program selects one of the alternative paths depending upon the result of the test
for condition.
Examples of selective control structures statements are :
1. Simple if statement
2. if . . . else statement
3. Nested if . . . else statement
4. else if ladder
5. switch . . . case . . .default statement
c) Iterative Control Structure (or) Loop Control Structure
The iterative structure provides the ability to go back and repeat a set of statements.
Iterative structure is otherwise referred to as repetitive structure.
Examples of iterative control structure statements are :
62. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 62
1. while statement
2. do . . . while statement
3. for statement
11.2 if STATEMENTS
C allows decisions to be made by evaluating a given expression as true or false.
Such an expression involves the relational and logical operators.
Depending on the outcome of the decision, program execution proceeds in one
direction or another.
The C statement that enables these tests to be made is called the if statements.
The if statements may be implemented in different forms depending on the
complexity of conditions to be tested.
They are :
1. Simple if statement
2. if . . . else statement
3. Nested if . . . else statement
4. else if ladder
5. The if, if...else and nested if...else statement are used to make one-time decisions
in C Programming, that is, to execute some code/s and ignore some code/s
depending upon the test expression.
1. Simple if statement
The simple if statement is a conditional execution statement in C.
With a condition given and when evaluated, if result is true then perform the action
statement given along with if syntax.
If the given condition fails, the next statement following if will be executed.
Syntax
if (expression)
statement;
or
if (expression)
{
Block of statements;
}
63. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 63
Flowchart of if statement
The if statement checks whether the text expression inside parenthesis ( ) is true or
not.
If the test expression is true, statement/s inside the body of if statement is executed
but if test is false, statement/s inside body of if is ignored.
Example 1: C if statement
Write a C program to print the number entered by user only if the number entered is
negative.
#include <stdio.h>
int main(){
int num;
printf("Enter a number to check.n");
scanf("%d",&num);
if(num<0) { /* checking whether number is less than 0 or not. */
printf("Number = %dn",num);
64. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 64
}
/*If test condition is true, statement above will be executed, otherwise it will not be
executed */
printf("The if statement in C programming is easy.");
return 0;
}
Output 1
Enter a number to check.
-2
Number = -2
The if statement in C programming is easy.
When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2
is displayed in the screen.
Output 2
Enter a number to check.
5
The if statement in C programming is easy.
When the user enters 5 then, the test expression (num<0) becomes false.
So, the statement/s inside body of if is skipped and only the statement below it is
executed.
2. if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when
the test expression is true and execute some other statement/s if the test expression is false.
Syntax of if...else
if (test expression) {
statements to be executed if test expression is true;
}
else {
statements to be executed if test expression is false;
}
Flowchart of if...else statement
65. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 65
Example 2: C if...else statement
Write a C program to check whether a number entered by user is even or odd
#include <stdio.h>
int main(){
int num;
printf("Enter a number you want to check.n");
scanf("%d",&num);
if((num%2)==0) //checking whether remainder is 0 or not.
printf("%d is even.",num);
else
printf("%d is odd.",num);
return 0;
}
Output 1
Enter a number you want to check.
25
25 is odd.
Output 2
Enter a number you want to check.
2
2 is even.
66. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 66
3. Nested if...else statement (if...elseif....else Statement)
The nested if...else statement is used when program requires more than one test
expression.
Syntax of nested if...else statement.
if (test expression1){
statement/s to be executed if test expression1 is true;
}
else if(test expression2) {
statement/s to be executed if test expression1 is false and 2 is true;
}
else if (test expression 3) {
statement/s to be executed if text expression1 and 2 are false and 3 is true;
}
else {
statements to be executed if all test expressions are false;
}
How nested if...else works?
The nested if...else statement has more than one test expression.
If the first test expression is true, it executes the code inside the braces{ } just below
it.
But if the first test expression is false, it checks the second test expression. If the
second test expression is true, it executes the statement/s inside the braces{ } just
below it.
This process continues.
If all the test expression are false, code/s inside else is executed and the control of
program jumps below the nested if...else
The ANSI standard specifies that 15 levels of nesting may be continued.
Example 3: C nested if else statement
Write a C program to relate two integers entered by user using = or > or < sign.
#include <stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to checkn");
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d = %d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d > %d",numb1,numb2);
else
printf("Result: %d > %d",numb2,numb1);
return 0;
67. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 67
}
Output 1
Enter two integers to check.
5
3
Result: 5 > 3
Output 2
Enter two integers to check.
-4
-4
Result: -4 = -4
12. switch STATEMENT
In a simple definition, switch statement is used to accomplish multiple choices and
single selection task required.
Decision making are needed when, the program encounters the situation to choose a
particular statement among many statements.
If a programmer has to choose one block of statement among many alternatives,
nested if...else can be used but, this makes programming logic complex.
This type of problem can be handled in C programming using switch statement.
The major use is that menu creation with multiple choices will effectively done
using switch statement.
Syntax of switch...case
switch (expression) {
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The following flow diagram explains the working of switch statement:
68. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 68
The value of n is either an integer or a character in above syntax. If the value of n
matches constant in case, the relevant codes are executed and control moves out of
the switch statement.
If the n doesn't matches any of the constant in case, then the default codes are
executed and control moves out of switch statement.
Example of switch...case statement
Write a program that asks user an arithmetic operator('+','-','*' or '/') and two
operands and perform the corresponding calculation on the operands.
Answer:
/* C program to demonstrate the working of switch...case statement */
/* C Program to create a simple calculator for addition, subtraction,
multiplication and division */
# include <stdio.h>
int main() {
char o;
float num1,num2;
69. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 69
printf("Select an operator either + or - or * or / n");
scanf("%c",&o);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(o) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
return 0;
}
Output
Enter operator either + or - or * or /
*
Enter two operands: 2.3
4.5
2.3 * 4.5 = 10.3
The break statement at the end of each case cause switch statement to exit. If break
statement is not used, all statements below that case statement are also executed.
goto STATEMENT
The goto statement is used to alter the normal sequence of program execution by
unconditionally transferring control to some part of the program.
The syntax is :
goto label :
Where label is an identifier used to label the target statement to which the control would
be transferred.
Control may be transferred to any other statement within the current function.
70. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 70
The target function must be labeled followed by a colon.
The syntax is :
label : statement ;
Example of goto statement
/* C program to demonstrate the working of goto statement. */
/* This program calculates the average of numbers entered by user. */
/* If user enters negative number, it ignores that number and
calculates the average of number entered before it.*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump; /* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Output
Maximum no. of inputs: 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average: 7.07
Though goto statement is included in ANSI standard of C, use of goto statement should be
reduced as much as possible in a program.
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto
statement makes the logic of the program complex and tangled. In modern
programming, goto statement is considered a harmful construct and a bad
programming practice.
The goto statement can be replaced in most of C program with the use of break and
continue statements. In fact, any program in C programming can be perfectly written
without the use of goto statement.
All programmer should try to avoid goto statement as possible as they can.
71. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 71
13. Looping statements
13.1 Looping Statements in C
Loops causes program to execute the certain block of code repeatedly until some
conditions are satisfied, i.e., loops are used in performing repetitive work in
programming.
Suppose you want to execute some code/s 10 times.
You can perform it by writing that code/s only one time and repeat the execution 10
times using loop.
13.2 Types of Looping in C
There are 3 types of loops in C programming:
a) while loop
b) do...while loop
c) for loop
13.3 while loop
The while loop checks whether the test expression is true or not. If it is true, code/s
inside the body of while loop is executed, that is, code/s inside the braces { } are
executed.
Then again the test expression is checked whether test expression is true or not.
This process continues until the test expression becomes false.
Syntax of while loop
while (test expression) {
statement/s to be executed. }
Example of while loop
Write a C program to find the factorial of a number, where the number is entered
by user. (Hints: factorial of n = 1*2*3*...*n)
/*C program to demonstrate the working of while loop*/
#include <stdio.h>
int main(){
int number,factorial;
printf("Enter a number.n");
scanf("%d",&number);
factorial=1;
while (number>0){ /* while loop continues util test condition number>0 is true */
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}
72. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 72
Output
Enter a number.
5
Factorial=120
13.4 do...while loop
In C, do...while loop is very similar to while loop.
Only difference between these two loops is that, in while loops, test expression is
checked at first but, in do...while loop code is executed at first then the condition is
checked. So, the code are executed at least once in do...while loops.
Syntax of do...while loop
do {
some code/s;
}
while (test expression);
At first codes inside body of do is executed.
Then, the test expression is checked.
If it is true, code/s inside body of do are executed again and the process continues
until test expression becomes false(zero).
Notice: there is semicolon in the end of while (); in do...while loop.
Example of do...while loop
Write a C program to add all the numbers entered by a user until user enters 0.
/*C program to demonstrate the working of do...while statement*/
#include <stdio.h>
int main(){
int sum=0,num;
do /* Codes inside the body of do...while loops are at least executed once. */
{
printf("Enter a numbern");
scanf("%d",&num);
sum+=num;
}
while(num!=0);
printf("sum=%d",sum);
return 0;
}
Output
Enter a number
3
Enter a number
-2
73. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 73
Enter a number
0
sum=1
In this C program, user is asked a number and it is added with sum.
Then, only the test condition in the do...while loop is checked.
If the test condition is true,i.e, num is not equal to 0, the body of do...while loop is again
executed until num equals to zero.
13.5 for loop
Loops cause program to execute the certain block of code repeatedly until test
condition is false.
Loops are used in performing repetitive task in programming.
for Loop Syntax
for(initialization statement; test expression; update statement)
{
code/s to be executed;
}
loop works in C programming as follows:
The initialization statement is executed only once at the beginning of the for loop.
Then
the test expression is checked by the program.
If the test expression is false, for loop is terminated.
But if test expression is true then the code/s inside body of for loop is executed and
then update expression is updated.
This process repeats until test expression is false.
This flowchart describes the working of for loop in C programming.
for loop example
Write a program to find the sum of first n natural numbers where n is entered by
user. Note: 1,2,3... are called natural numbers.
#include <stdio.h>
int main(){
int n, count, sum=0;
printf("Enter the value of n.n");
scanf("%d",&n);
for(count=1;count<=n;++count) //for loop terminates if count>n
{
sum+=count; /* this statement is equivalent to sum=sum+count */
}
printf("Sum=%d",sum);
74. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 74
return 0;
}
Output
Enter the value of n.
19
Sum=190
In this program, the user is asked to enter the value of n.
Suppose you entered 19 then, count is initialized to 1 at first.
Then, the test expression in the for loop,i.e., (count<= n) becomes true.
So, the code in the body of for loop is executed which makes sum to 1. Then, the
expression ++count is executed and again the test expression is checked, which becomes
true.
Again, the body of for loop is executed which makes sum to 3 and this process continues.
When count is 20, the test condition becomes false and the for loop is terminated.
13.6 C Loop Control Statements
Loop control statements are used to change the normal sequence of execution of the loop.
Statement Syntax Description
break statement break; It is used to terminate loop
or switch statements.
continue statement continue; It is used to suspend the
execution of current loop
iteration and transfer control
to the loop for the next
iteration.
goto statement goto labelName;
labelName: statement;
It transfers current program
execution sequence to some
other part of the program.
break and continue
There are two statements built in C programming, break; and continue; to alter the
normal flow of a program.
Loops perform a set of repetitive task until text expression becomes false but it is
sometimes desirable to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression.
In such cases, break and continue statements are used.
The break; statement is also used in switch statement to exit switch statement.
13.6.1 break Statement
In C programming, break is used in terminating the loop immediately after it is
encountered. The break statement is used with conditional if statement.
Syntax of break statement
break;
The break statement can be used in terminating all three loops for, while and do...while
75. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 75
loops.
Example of break statement
Write a C program to find average of maximum of n positive numbers entered by
user. But, if the input is negative, display the average(excluding the average of
negative input) and end the program.
/* C program to demonstrate the working of break statement by terminating a loop, if
user inputs negative number*/
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputsn");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break; //for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Output
Maximum no. of inputs
4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average=7.07
In this program, when the user inputs number less than zero, the loop is terminated using
break statement with executing the statement below it i.e., without executing
sum=sum+num.
13.6.2 continue Statement
It is sometimes desirable to skip some statements inside the
loop.
In such cases, continue statements are used.
Syntax of continue Statement
continue;
76. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 76
Just like break, continue is also used with conditional if statement.
Example of continue statement
Write a C program to find the product of 4 integers entered by a user. If user enters
0 skip it.
//program to demonstrate the working of continue statement in C programming
# include <stdio.h>
int main(){
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue;
/ *In this program, when num equals to zero, it skips the statement
product*=num and continue the loop. */
product*=num;
}
printf("product=%d",product);
return 0;
}
Output
Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
product=-30
14. PREPORCESSOR DIRECTIVES
14.1 Introduction to preprocessor Directives
What are Preprocessor Directives?
C Preprocessor is just a text substitution tool and it instructs the compiler to do
require pre-processing before the actual compilation.
It is a task done by C compiler before the start of the compiling the C Language
Code.
The keyword Preprocessor insists that tasks done before compilation through
Computer Processor.
Types of Preprocessor Directives
All preprocessor commands begin with a hash symbol (#).
It must be the first nonblank character, and for readability, a preprocessor directive
should begin in the first column.
77. Compiled By: Er. K. KHAJA MOHIDEEN, Assistant Professor / Information Technology Page 77
Why are preprocessor directives used?
Preprocessor directives, such as #define and #ifdef , are typically used to make
source programs easy to change and easy to compile in different execution
environments.
Directives in the source file tell the preprocessor to take specific actions.
The following section lists down all the important preprocessor directives –
Sl No Directive Description
1 #define Substitutes a preprocessor macro.
2 #include Inserts a particular header from another file.
3 #undef Undefines a preprocessor macro.
4 #ifdef Returns true if this macro is defined.
5 #ifndef Returns true if this macro is not defined.
6 #if Tests if a compile time condition is true.
7 #else The alternative for #if.
8 #elif #else and #if in one statement.
9 #endif Ends preprocessor conditional.
10 #error Prints error message on stderr.
The Two major types of Preprocessor Directives are
1) # include
2) # define
1) #include
The #include directive tells the C preprocessor to include the contents of the file specified
in the input stream to the compiler and then continue with the rest of the original file.
Use of #include
The #include preprocessor directive is used to paste code of given file into current
file.
It is used include system-defined and user-defined header files.
If included file is not found, compiler renders error.