Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PPS Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

Introduction to C- Programming

History of C Language
 The C Language is a general purpose, high level and structured oriented programming
language developed at Bell laboratories in 1972, by Dennis M. Ritchie.
 C programming features, where derived from an earlier language called ‘B’ (BCPL- Basic
Combined Programming Language).
 C language was invented for implementing UNIX operating system.
 In 1978, Dennis Ritchie and Brian Kernighan published the first edition “ The C
Programming Language” and commonly known as “K & R C”
 In 1983, the ANSI (American National Standard Institute) established a committee to
provide a modern, comprehensive definition of C. The resulting definition is the ANSI C,
completed in 1988.

Features of C Language
The following are the standard features of C Language as follows.

1. Portability: Programs written in C language can be run on any compiler with little or no
modifications of a program.
2. Flexibility: C language has number of reserved keywords, which helps the programmers
to take control over the usage of language and to modify the structure of program.
3. Modularity: C language provides feature of modularity, i.e. we can breakdown a large
program into manageable modules. This feature provides easy to understand and
debugging of the program will become faster.
4. Robustness: C language is a robust language, with rich set of built-in functions and
operators that can be used to write any complex programs.
5. Extensibility: In C language program, the new features can be added at any time by the
programmer to the existing program.
6. Efficiency and effectiveness: Programs written in C language are fast and efficient, due
to the variety of data types and powerful operators.
Applications of C Language
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to
develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11
computer in 1972.

Some of applications of the C language are:

1. C language is used for creating computer applications.


2. C language is used to write embedded software’s.
3. It is also used in developing verification software, test code, simulators etc. for various
applications and hardware products.
4. Used for creating Language Compilers, Assemblers, Text editors, Network Drivers,
Language interpreters, Database programs, and utilities.
5. C is used to implement different Operating System Operations.
6. UNIX Kernel is completely developed in C Language.

C Programming Development Cycle


Executing a program written in C Language involves a series of steps. They are:

1. Creating the program


2. Compiling the program
3. Linking your program with whatever function needed from the library
4. Executing the program.
1. Creating the program: The software used to write a program is known as text editor. A
text editor helps us to enter, change and store character data. After we complete the
program, we save our file to disk. This file will be input to the compiler and this file is
known as source file.
2. Compiling the program: The compiler software (Program) translates the source file into
its equivalent machine language code and also it displays if any syntactical errors in the
program.
3. Linking the program: Linking is process of putting together other program files and
functions that are required by the source program. For example, if the program is using
printf() function, then the object code of this function should be brought from the
stdio.h library of the system and linked it to the source program.
4. Executing the program: Once the .EXE file is created and stored on the disk, it is ready
for execution. When we execute it, it is first brought from the disk into the memory
(RAM) by an operating system component called Program Loader then asks for input
parameters from the user, processes it and produces the results to user.
Structure of a C Program
Structure describes the way in which a program can be written, and the structure of a C
Program looks like:

Figure: Structure of C Program with example

Documentation Section: It consists of a set of comment lines giving the name of the program
and other details.

Preprocessor Directives: This section contains header file section, it provides instructions to
the compiler to link functions from the system library and macro definition section, used
defines all symbolic constants.

Function Prototyping: This includes nature of the functions, such as return type, name of
function and list of arguments.

Syntax: return_type function_name(arguments_list);


Global variable Declaration: There are some variables and those variables are declared above
all functions and whose scope is valid throughout the program.

Main Function: Every C program must have one main function section. This section contains
two parts, declaration and executable part. Declaration Part (i.e. Local variable Declaration)
declares all the variables used in the executable part. There should be at least one statement in
the executable part (i.e. Code of the Program) which contains instructions to perform certain
task.
The declaration and executable part must appear between the opening and closing braces. All
statements in the declaration part should end with the semicolon.

Functions (Sub Programs): The Subprogram Section contains all the user defined functions that
are called in the main function. It is a reusable block of statements that are executed upon
calling from the main function by the function name. A program may have any number of user
defined functions.

Comments in C Program
Comments are non-executable code used to provide documentation to the program, by the
programmer.

 Comments provide clarity to the C source code allowing others to better understand
what the code was intended to accomplish and greatly helping in debugging the code.
 Comments are especially important in large projects containing hundreds or thousands
of lines of source code or in projects in which many contributors are working on the
source code.
1. Single Line Comments: We can create a comment on a single line in the following ways.

For example: /* Author: Dennis M Ritchie */


(Or)
For example: // Book Title: ANSI C

2. Multiple Line Comments: We can create a comment on multiple lines using /* */.

For example: /*
* Author: TechOnTheNet.com
* Purpose: To show a comment that spans multiple lines.
* Language: ANSI C */
C Language Syntax Rules
C language syntax specifies rules for sequence of characters to be written in C language. The rule specify
how character sequence will be grouped together to form tokens. A smallest individual unit in C
program is known as C Tokens. Tokens are keywords, identifiers, constants, variables or any symbol
which has some meaning in C language. A C program can also be called as collection of various tokens.

Some basic syntax rules for C program are:

 C is a case sensitive language, so all C instructions must be written in lower case letter.
 All C statement must be end with a semicolon.
 Whitespace is used in C to describe blanks and tabs.
 Whitespace is required between keywords and identifiers.

Formatted I/O Functions in C Language


C programming language provides many of the built-in functions to read given input and write
data on screen, printer or to any file.

Input Functions: In any programming language, input means to feed some data into the
program. This can be given in the form file or from the command line. Some of input functions
are:

1. Scanf (): This function is used to read character, string, and numeric data from keyboard.

Syntax: scanf (“control_string_specifier1 control_string_specifier1”,”, &arg1, &arg2);

The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory.

Example: integer (%d), float (%f), character (%c) or string (%s).

The argument list contains a list of variables each proceeded by the address operator (‘&’) and
separated by comma.

2. getchar (): This function reads a single character at a time from the command line or
from the file.

Syntax: variable = getchar ();

It returns the unsigned char that they read. If end-of-file or an error is encountered then
getchar () functions return EOF.
3. gets(): It reads characters from the standard input (stdin) and stores them as a C string
into string variable, until a newline character or the end-of-file is reached.

Syntax: char * gets (char * star); (or) gets (variable-name);

Output Functions: In any programming language, output means to display some data on
screen, to printer or to any file. C programming language provides set of built-in functions to
output required data.

1. printf(): It is one of the most frequently used function in C language to display


formatted output.

Syntax: printf (“control_string_specifier1, control_string_specifier1”, arg1, arg2);

2. putchar(): This functions outputs or prints a single character on the screen at a time.

Syntax: putchar(variable_name);

3. puts(): This function writes or puts a line of string on the screen at a time.

Syntax: puts(variable_name);

NOTE:

 printf() returns the number of characters printed by it and scanf() returns the number
of characters read by it.
 scanf() stops reaching characters when it encounters a blank space, but gets() reads a
space as a character too.

C Tokens
C programs contain many elements which are identified by the compiler, are known as tokens.
Tokens can be categorized as,

1) Keywords
2) Identifiers
3) Variables
4) Constants
5) Special symbols
6) Operators
For example, consider following program,

void main()
{
int x, y, sum;
x = 5, y = 10;
sum = x + y;
printf (“Sum = %d\n”, sum);
}
From above program C Tokens can be categorized as follows:
Identifier: main
Special symbols: {,}, (,)
Keyword: int
Variables: x, y, sum
Operators: +, =
Tokens: main, {,}, (,), int, x, y, sum

1. Keywords

1. Keywords are pre-defined words (or) reserved words in C compiler.


2. Each keyword is meant to perform a specific function in a C program.
3. Since keywords are referred names for compiler, they cannot be used as identifiers.
4. All keywords must be written in lower case.

In C language there are 32 keywords are available and listed below.


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2. Identifiers

In C language identifiers are the names, which are given to variables, user-defined
functions and arrays.

Syntax Rules:

1. An identifier should only have alphanumeric characters (a-z, A-Z, 0-9) and
underscore (_) symbol.
2. The first character of an identifier should only have alphabets (a-z, A-Z) or
underscore (_) symbol.
3. Identifiers are case sensitive in C language. For example, “name” and “Name”
are two different identifiers in C language.
4. Keywords are not allowed to be used as identifiers.
5. Special characters (Ex: ;, ., white spaces, slash etc.,) are not permitted to use as
identifiers.

Comparison between identifier and keywords

Identifier keyword
Identifiers are names that are given to C take some reserved word called keyword,
various program elements, such as variable, they have predefine meaning in C.
function and arrays.
Identifiers consist of letters and digits. Keyword consist only letter.
Identifier’s first character must be a letter. Keyword’s all character is letter.
Identifiers Upper and lowercase letter is use. Keywords are all lowercase.
Upper and lowercase are not equivalent. Upper and lowercase are also not
equivalent.
Like: X, sum_5, _weather, 9_name etc. Like: auto, short, long etc.
But 4th is not identifier because identifier
first character must a letter.
3. Variables

A variable is a name that is used to store a value. Variable are simply names used to
refer some locations in memory i.e. a location that holds a value.

Variable declaration: Declaration of variable must be done before they are used in the
program. It tones three things:

 It tells the compiler what the variable name it is.


 It specifies what type of data the variable will hold.
 It tells the scope or lifetime of a variable.

Syntax: storage_class_specifier data_type variable_name; //variable declaration

Example: auto int sum, age, total; (or) int sum, age, total;

Variable definition: The location (address) is allocated for variable definition.

Example:

int x=10, y=20; // variable initialization


int sum; // variable declaration
sum = x+y; // variable definition

NOTE: the name of variable must not change, but the value stored in the variable may change
during execution of the program.

Rules of variables declaration:

1. All variables must be declared before they can be appeared in executable


statements.
2. A variable name must not start with digits.
3. Keywords are not allowed as variable names.
4. White spaces are not allowed in variable names.
5. Variable names can consists of alphabets, digits and only permitted
special symbol underscore (_).
4. Constants

 C Constants are like normal variables. But, only difference is their values cannot
be modified by the program once they are defined.
 Constants refer to fixed values. They are also called as literals.
 Constants may be belonging to any of the data type.

Syntax: const data_type variable_name; (or) const data_type *variable_name;

Integer Constants:

An integer constant can be a decimal, octal, or hexadecimal constant. A prefix specifies the base
or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. Some examples are:

85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Rules for constructing Integer constants:


1. An integer constant must have at least one digit.
2. It must not have a decimal point.
3. It can be either positive or negative.
4. If no sign precedes an integer constant, it is assumed to be positive.
5. Commas or blanks are not allowed within an integer constant.

Example: -33 32767

There are three types of integer constants namely:


a) Decimal integer constant
b) Octal integer constant
c) Hexadecimal integer constant
Decimal Integer constant (base 10):

 It consists of any combinations of digits taken from the set 0 through 9,


preceded by an optional – or + sign.
 The first digit must be other than 0.
 White spaces, commas, and non-digit characters are not permitted between
digits.

Valid: 32767 -9999 -23


Invalid: 12,245 -Illegal character (,)
10 20 30 -Illegal character (blank space)

b) Octal Integer Constant (base 8) :

 It consists of any combinations of digits taken from the set 0 through 7.


 If a constant contains two or more digits, the first digit must be 0.
 In programming, octal numbers are used.

Valid: 037 0435


Invalid: 0786 - Illegal digit 8
123 - Does not begin with zero
01.2 -Illegal character (.)

c) Hexadecimal integer constant (base 16) :

 It consists of any combinations of digits taken from the set 0 through 9


and also a through f (either uppercase or lowercase).
 The letters a through f (or A through F) represent the decimal quantities
10 through 15 respectively.
 This constant must begin with either 0x or 0X.

Valid: 0x 0X1 0x7F


Invalid: 0xefg - Illegal character g
123 - Does not begin with 0x
Real (or) floating Constants: A floating-point literal has an integer part, a decimal point, a
fractional part, and an exponent part. You can represent floating point literals either in decimal
form or exponential form. Some examples are:

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Rules of floating constants:

 A real constant must have at least one digit


 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.

Single Character Constants: A single character constants contains a single character


enclosed within a pair of single quote marks.
Example: ’5’ ‘X’ ‘;’

Backslash (or) escape sequence character Constants:

 There are some characters which have special meaning in C language.


 They should be preceded by backslash symbol to make use of special
function of them.
 Given below is the list of special characters and their purpose.

Backslash Character Meaning


\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\0N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

String constants: A string constant is a sequence of characters enclosed in double quotes.


The characters may be letters, numbers, special characters and blank space.
Example:”Hello!”
“1986”
Special symbols

Symbols other than the alphabets and digits and white-spaces are called special symbols. C has
following list of special symbols.

Symbol Meaning
~ Tilde
! Exclamation mark
# Number sign or hash
$ Dollar sign
% Percent sign
^ Caret
& Ampersand
* Asterisk
( Left parenthesis
) Right parenthesis
_ Underscore
+ Plus sign
| Vertical bar
\ Backslash
` Apostrophe
- Minus sign
= Equal to sign
{ Left brace
} Right brace
[ Left bracket
] Right bracket
: Colon
" Double Quotation mark
; Semicolon
< Less than
> Greater than
? Question mark
, Comma
. Period
/ Forward Slash
Operators

Operators are symbols that trigger an action when applied to C variables and other objects.
The data items on which operators act upon are called operands.

Depending on the number of operands that an operator contains, operators can be classified as
follows:

1. Unary Operators: Those operators that require only single operand to act upon are
known as unary operators.
2. Binary Operators: Those operators that require two operands to act upon are called
binary operators.
3. Ternary Operators: These operators require three operands to act upon.

Data types in C Language


Data type means type of data. C language has rich set of data types.

1. Built-in (or) primary (or) primitive (or) Pre-defined data types.


2. User-defined (or) derived (or) secondary data types.
3. void data type.
4. Enumerated data type.

1. Primitive Data Types: Primitive data types are predefined data types, which are
supported by the programming language. For example, integer, character, and string are
all primitive data types.
Data Types and its range:

2. Derived Data Types: The data types which derived from fundamental or primitive
data types is known as derived data types. For example, arrays, functions, structures
and unions etc.
3. Void Data Type: void data type means “no values” (or) “empty” i.e. it take or returns
empty value. The void data type usually used with functions to specify its return type or
with parameters list.
4. Enumerated Data Type:

 Enumerated data type consists of named integer constants as a list.


 It starts with zero by default and increments by one for the sequential identities
in the list.

Syntax: enum identifier{enumerators_list};

Example: enum month{ jan, feb, march};


Data Types conversion Specifiers:

Specifier Meaning
%d (or) %i Used to read and displays integer values
%f Used to read and display real values in decimal notations. Example:
10.256
%e Used to read and display real values in scientific notation. Example:
3.6e7
%E Used to read and display real values in scientific notation with capital
letter. Example: 3.6E7
%c Used to read and display characters
%lf Used to read and display long double values
%x Used to read and display hexadecimal values in lowercase.
%X Used to read and display hexadecimal values in uppercase.
%0x Used to read and display octal values
%u Used to print the addresses of a variable.

Type Casting

Converting one type of data into another type is known as type casting. There are two
types of type conversions:

1. Implicit type casting


2. Explicit type casting

1. Implicit type casting: This casting is also known as automatic type casting i.e.
type casting done by compiler automatically, when the lower data type is assigned
to higher data type.

Example:

int x=20;
float y;
y=x;
printf(“%d”=”f”, x,y); // here, there is no loss of data

2. Explicit type casting: This casting is also known as type casting. Explicit type
casting uses unary type cast operator. This is useful when higher data type value is
trying assigned to lower data type value, because there may be a loss of data. So,
the compiler will also show an error like “possible loss of data”.

Example:

float x=20;
int y,z;
y=(int)(x+20); // here float value is converted to int type
z=(int) (x+50);

Local and Global variables


Local variables: Variable whose existence is known only to the main program or functions
are called local variables. Local variables are declared within the main program or a function.

Global variables: Variables whose existence is known to the both main() as well as other
functions are called global variables. Global variables are declared outside the main() and other
functions.

The following Program illustrates the concept of both local as well as global variables.
Example:
#include<stdio.h>
int x=50; // global variable declaration
int y=25; // global variable declaration
int add(); // function prototyping
void main(){
int x=10; // local variable declaration
int y=20; // local variable declaration
printf(“sum of two numbers=%d\n”,x+y);
sum=add();
printf(“sum of two numbers=%d\n”,sum);
}

int add(){
return x+y;
}

Output:

sum of two numbers=30


sum of two numbers=75

Storage Classes
Every variable in C programming has two properties: type and storage class. Type refers to the
data type of variable whether it is character or integer or floating-point value etc. And storage
class determines how long it stays in existence.
The storage class determines two properties of a variable:

1. Scope of a variable: Which specifies the part of the program over which a variable
name is visible, i.e. the variable is accessible by name.
2. Life time (or) extent of a variable: Which specifies the part of memory where
storage is allocated for a variable and how long the storage allocation continues to
exist.

Storage classes are classified into 4-types, they are:

1. automatic storage class


2. register storage class
3. external storage class
4. static storage class

1. automatic (auto) storage class

 This is the default storage class of any variable.


 In order to explicit declaration of variable use “auto” keyword.

Features:

 auto storage class variables are stored in main memory i.e. RAM.
 Scope of variables is within a block or function.
 Lifetime of variables should exist as long as control remains in the block.
 Default initial value stored in variables is garbage value.

Syntax: auto int variable_name; // explicit declaration

(Or) int variable_name; // default auto declaration

Example:

#include<stdio.h>
void main()
{
auto int a=10;
{
auto int a=100;
printf(“internal block value=%d\n”, a);
}
printf(“external block value=%d\n”, a);
}
Output:

internal block value=100


external block value=10

NOTE: The example above defines two variables within the same storage class. “auto” can only
be used within functions, i.e., as a local variables.

2. register storage class

 register keyword is used to define local variable.


 register storage class variable are stored in registers instead of RAM.
 As variable is stored in register, the Maximum size of variable =
Maximum Size of Register.
 This is generally used for faster access.

Features:

 register storage class variables are stored in CPU Registers.


 Scope of variables is within a block or function.
 Lifetime of variables should exist as long as control remains in the block.
 Default initial value stored in variables is garbage value.

Syntax: register int variable_name; //explicit declaration

Example:

#include<stdio.h>
void main()
{
int a=100, b=100;
register int sum;
sum=a+b;
printf(“Addition=%d\n”, sum);
}

Output:

Addition=200
3. External (extern) or global storage class

 Variables of this storage class are “Global variables”.


 Global Variables are declared outside the function and are accessible to
all functions in the program.
 Generally, External variables are declared again in the function using
keyword “extern”.
 In order to explicit declaration of variable we use “extern” keyword.

Features:

 external storage class variables are stored in RAM.


 Scope of variables is global to the program.
 Lifetime of variables should exist till end of the program.
 Default initial value stored in variables is zero value.

Syntax: extern int variable_name; //explicit declaration

Example:

#include<stdio.h>
int a=150; // global variable declaration
void display(); //function prototyping
void main()
{
extern int a; //explicit declaration
printf(“value in main block=%d\n”, a);
display();
}

void display(){
extern int a;
printf(“value in display block=%d\n”, a);
}

Output:

value in main block=150


value in display block=150

NOTE

 Declaration within the function indicates that the function uses external
variable.
 Functions belonging to same source code do not require declaration (no
need to write extern).
 If variable is defined outside the source code, then declaration using extern
keyword is required.

4. static storage class

 static keyword is used to static storage class variables.


 These type variables can initialize and executed only once and
retains the value changed among functions in the program.

Features:

 static storage class variables are stored in RAM.


 Scope of variables initialized only once within a block or function.
 Lifetime of variable value persists between different function calls.
 Default initial value stored in variables is zero value.

Syntax: static int variable_name; //explicit declaration

Example:

#include<stdio.h>
void display(); //function prototyping
void main()
{
display();
display();
display();
}

void display(){
static int a=0; //declaration and only once executed
printf(“changing value=%d\n”, a);
a=a+10;
}

Output:

changing value=0
changing value=10
changing value=20
Summary of storage classes

Category Auto Register External Static


Keyword Auto register extern static
Storage area RAM (stack) CPU Registers RAM RAM
Scope within the within the Global/ File within the block
block or block or Scope or function
function function
Lifetime Local to the Local to the End of End of program
block block program
Initial value Garbage value Garbage value 0 (zero) 0 (zero)

C Operators
Operator is a symbol that is used to perform mathematical or logical manipulations in the
program. C language has the following operators:

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Ternary (or) conditional operator
7. Increment or decrement operators
8. Special operators

1. Arithmetic operators: These are used to perform basic mathematical calculations


like addition, subtraction, multiplication, division and modulus operations in an
expression.

Operator Description Example


+ Addition or unary plus C=A+B gives sum of A+B
- Subtraction or unary minus C=A-B gives difference of A-B
* Unary or multiplication C=A*B gives multiplication of A*B
/ Division operator C=A/B gives quotient value
% Modulo Division C=A%B gives remainder value
2. Relational operator: These operators are used to compare the value of two variables
(or) operands.

Operator Description Example


== Equal to 5 ==3 returns false (0)
> Greater than 5>3 returns true (1)
< Less than 5<3 returns false (0)
!= Not equal to 5!=3 returns true(1)
>= Greater than or equal to 5>=3 returns true (1)
<= Less than or equal to 5<=3 return false (0)

3. Logical operators: These operators are used to compare two or more relational
expressions.

Operator Description Example


&& Logical AND If c=5 and d=2 then, ((c==5) && (d>5)) returns false.
|| Logical OR If c=5 and d=2 then, ((c==5)||(d>5)) returns true.
! Logical NOT If c=5 then, !(c==5) returns false.

4. Bitwise (or) binary operators: C has distinction of supporting special operators


known as bitwise operators for manipulation of data at bit level. These operators are
used for testing the bits and shifting them right to left or left to right.

Operator Description Example(A=12, B=2)


& Binary AND A&B gives 0
| Binary OR A|B gives 14
^ Binary EX-OR A^B gives 14
~ Binary Complement ~B gives -3 hint: -(n+1)
<< Left shift A<<2 gives 48
>> Right shift B>>2 gives 0

NOTE

 Left shifting one time means, it is equal to multiplying the value by 2 one time.
 Right shifting one time means, it is equal to dividing the value by 2 one time.
5. Assignment operators: This operator is used to assign the values for the variables in
the programs.

Operator Description Example


= Simple assignment A=B; i.e. B value is assigned to A
+= Addition and assignment A+=B is same as A=A+B
-= Subtraction and assignment A-=B is same as A=A-B
*= Multiplication and assignment A*=B is same as A=A*B
/= Division and assignment A/=B is same as A=A/B
%= Modulus and assignment A%=B is same as A=A%B
<<= Left shift and assignment A<<=B is same as A=A<<B
>>= Right shift and assignment A>>=B is same as A=A>>B
&= Binary AND and assignment A&=B is same as A=A&B
|= Binary OR and assignment A|=B is same as A=A|B
^= Binary EX-OR and assignment A^=B is same as A=A^B

6. Ternary operator: The conditional operator contains a condition followed by two


conditions or two expressions. Conditional operator takes three operands and consists
of two symbols ‘?’ and ‘:’. It is also called as ternary operator, because it takes three
arguments.

Syntax: (Condition)? (Expression1): (Expression2);

If the condition is true then expression1 gets evaluated otherwise (i.e. if condition false)
expression2 gets evaluated.

Example1: if(10%2==0)?printf(“even number”):printf(“odd number”); //prints even number

Example2: sum=(10>=10)?(100-50):(200-50); // the value of 50 assigned to variable sum

7. Increment or decrement operators: These operators are used to increment or


decrement by 1 in an expression.

Operator Description Example


++operand Unary pre-increment A=++10; first evaluates 11 and
assigns A=11
--operand Unary pre-decrement A=--10; first evaluates 9 and assigns
A=9
operand++ Unary post-increment A=10++; first assigns A=10 then
increments A by 1
operand-- Unary post-decrement A=10--;first assigns A=10 then
decrements A by 1
8. Special operators: C supports some special operators as shown below.

Operator Description Example


Sizeof() Returns the size of variable Int a; sizeof(a); returns 2 bytes
* Pointer to a variable Int *a; ‘a’ is pointer variable of type
int
& Returns the address of &a; will gives the actual address of
variable variable ‘a’
, Separates two or more int name, address, email;
identifiers

Operators Precedence and Associativity


Precedence and Associativity are the two characteristics of operators that determine the
evolution order of sub expressions in absence of brackets.

Operators precedence determines, which operators action is to be perform first in an


expression containing more than one operator. For example, 10+20*30 is calculated as 10+
(20*30) and not as (10+20)*30.

Associativity is used when two or more operators of same precedence operators appeared in
an expression. Associativity can be either left to right or right to left. For example, 100/10*10 is
calculated as (100/10)*10 not as 100/ (10*10), due having the same precedence of operators
(/, *).

Operator precedence & Associativity are listed in the following table and this table is
summarized in decreasing Order of priority i.e. topmost operator has highest priority and
bottommost operator has Lowest Priority.
Precedence Operator Associativity
1 ( ) ,[ ], . ,->, operand++ ,operand -- Left to right
2 ++operand, -- operand, Unary+, unary-, Right to left
!,~,

(type),*,&,sizeof()
3 *, /, %
4 +, -
5 << , >>
6 < , <=, >, >=
7 ==, != Left to right
8 &
9 ^
10 |
11 &&
12 ||
13 ?: Right to left
14 =, +=, -=, *=, /=, %=,>>=, <<=, &=, Right to left
^=, |=
15 , Left to right

Summary of operator precedence


1. Comma Operator Has Lowest Precedence.
2. Unary Operators are Operators having Highest Precedence.
3. Sizeof() is a Operator not a Function.
4. While solving expression, equal priority operators are handled on the basis of FIFO [First
in First Out] i.e. Operator Coming First is evaluated First.

Evolution of operators in an expression is as follows:

Example: x = 3 * 2 / 2 + 3 / 2 + 2 – 2 + 3 * 2

= (3*2) / 2 + 3 / 2 + 2 – 2 + 3 * 2

= (6/2) + 3 / 2 + 2 – 2 + 3 * 2

= 3 + (3 / 2) + 2 – 2 + 3 * 2

= 3 + 1 + 2 – 2 + (3 * 2)
= (3 + 1 + 2) – 2 + 6

= (6 – 2) + 6

=4+6

= 10

Important definitions
Unary operator: A unary operation is an operation with only one operand, i.e. an operation with
a single operand. For example, post / pre increment operators.

Binary Operator: A Binary operator is one which has two operands. For example, addition, subtraction.

Associativity: Associativity indicates in what order operators of equal precedence in an expression to be


evaluated.

Precedence: Priority of operator when two or more operators appeared in an expression.

Decision Making Statements


These statements allows us to make decision based upon result of a condition, so that these
statements can be called decision making or conditional statements or sometimes called as
selection statements, because based on condition it selects the set of instructions to be
executed. The following are classified as conditional statements:

1. if statement

The if stamen is powerful decision making stamen and is used to control the flow of
execution of statements.

Syntax:

if(condition)
{
Statement-1;
……………..
……………..
Statement-n;
}
statements;
If the condition is true, the statements block will be executed otherwise the
statements block will be ignored or skipped. And the execution will jumped to the
remaining statements of the program.

Example:

#include<stdio.h>
void main()
{
int i;
printf(“Enter any value:”);
scanf(“%d”,&i);
if(i<0)
{
printf(”Negative number”);
}
}

Output:

Enter any value:-5


Negative number

2. If… else statement

The if… else statement is the extension of the simple if statement.

Syntax:

if(condition)
{
true block statments;
}
else{
false block statements;
}
statements;

If the expression is true, then the true block statements are executed; if the
condition is false, then false block statements are executed.

#include<stdio.h>
void main()
{
int marks=50;
if(marks>=35)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}

Output: Student is Pass

3. else.. if (or) else if ladder statement

It is another way of putting if statements together when multiple decisions are


involved. If you want select single choice from multiple decisions available then this
structure is used.

Syntax:

if(condition1)
{
statements1;
}
else if(condition2)
{
statements2;
}
else if(condition3)
{
statements3;
}
else {
default statements;
}

If condiotion1 is true then statements block1 will be executed otherwise condition2


is tested; if condition2 true then statements block2 will be executed otherwise
condition3 is tested and so on. If all conditions gets false then default else block
statements are executed.

#include<stdio.h>
void main ( )
{
int num;
printf(“Enter a number:”);
scanf(“%d”,&num);
if( num > 0 )
printf("\n Number is Positive");
else if( num < 0 )
printf("\n Number is Negative");
else
printf("\n Number is Zero");
}

Explanation: In the above program first condition is tested i.e. number is checked
with zero. If it is greater than zero then only first if statement will be executed and
after the execution of if statement control will be outside the complete if-else
statement i.e. program termination.

Suppose in first if condition is false then the second condition will be tested i.e. if
number is not positive then and then only it is tested for the negative. And if number
is neither positive nor negative then it will be considered as zero.

4. Nested if else statement

When series of decisions are involved, we may have to use more than one if
statement in nested form.

if(condition1)
{
if(condition2)
{
if(condition3)
{
Statements1;
}
else{
statements2;
}
}
}
statements;

If condition1 is true then condition2 tested, if condition2 is true then condition3 is


tested, if condition3 also true then statements1 will be executed otherwise the
statements2 will be executed i.e. when condition3 is failed. If condition1 is false then
it does not executes any of the statements inside it, it directly goes to out of
condition and executes the statements out of it.

#include<stdio.h>
void main()
{
int i;
printf(“Enter any value:”);
scanf(“%d”,&i);
if(i>=0)
{
if(i<=10)
{
printf(”u have entered b/w 0 and 10”);
}
}
else{
printf(“entered other than 0 and 10”);
}
}

Output:

Enter any value:9


u have entered b/w 0 and 10

Switch Statement
The switch statement is a multi way branch statement. In the program there is a possibility to
make a choice from number of options, then this structured statement is useful.

Syntax:

switch(expression)
{
case value1: statements1;
break;
case value2: statements2;
break;

case valuen: statementsn;


break;
default: default statements; // optional
}
statements;
The expression in the switch is an integer expression or characters expression. Value1, value2,
…., valuen are constants or characters known as case labels. Note that case label are ends with
a colon(:).

When the switch is evaluated, the value of expression is compared against the value1,
value2,…,valuen. If a value matches with any case, then the block of statements are executed.
The break statement at end of each block signal the end of particular case and causes an exit
from the switch statement and transfers control to the remaining statements of the program.
The default case is executed when value of expression does not match with any of the case
values in switch statement.

Example:

#include<stdio.h>
void main()
{
int marks=35,i=1;
switch(i)
{
case 1: if(i >= 35)
printf(“pass”);
else
printf(“failed”);
break;
}
}

Output:

pass

Loop Statements
Loop is defined as a block of statements, which are repeatedly executed for certain number of
times.

 In looping, sequences of statements are executed until the condition is satisfied.


 Depending upon the position of the control statements in the loop, the loop
statements are classified as entry-controlled and exit-controlled loop
statements.

Entry controlled loop statement

 The condition is tested before the start of execution of statements.


 If the condition is not satisfied, then the statements of the loop will not be
executed.
Exit controlled loop statement

 The condition is tested after executing the statements of the loop, i.e. the
statements are executed unconditionally at least once before testing of
condition.
 When the execution reaches to condition; it tested and if the condition true then
again and again executes the statements of the loop repeatedly until the
condition is satisfied.

1. while loop statement

while loop is an entry controlled loop statement i.e. the condition is tested before start
of the loop statements execution, if the condition is not satisfied then statements of the
loop will not be executed.

Syntax:

while(condition)
{
statement1;
…………………..
…………………..
statementn;
}
statements;

Example:

#include<stdio.h>
void main()
{
int i=0;
while(i<=10)
{
printf(“%d\t”,i++);
}
}

Output:

0 1 2 3 4 5 6 7 8 9 10
2. do.. while loop statement

do.. while loop statement is an exit controlled loop statement, i.e. the condition tested
after executing the statements of the loop, it happens repeatedly until the condition is
satisfied.

Syntax:

do
{
statement1;
…………………..
…………………..
statementn;
}while(condition);
statements;

Example:

#include<stdio.h>
void main()
{
int i=0;
do
{
i=i+1;
printf(“%d\t”,i);
}while(i<=10);
}

Output:

1 2 3 4 5 6 7 8 9 10 11

3. for loop statement

for loop statement is an entry controlled loop, i.e. the condition is tested before start of
the loop statements execution. If condition is not satisfied then the statements of loop
will not be executed.

Syntax:

for(initialization; condition; increment(or)decrement)


{
statement1;
…………………..
…………………..
statementn;
}
statements;

1) The variable initialization sets loop to an initial value and this statement is
executed only once.
2) The condition is a relational expression on the variable initialization; it
determines number of iterations to be performed on the statements of the loop
i.e. the statements of the loop is executed until the condition is satisfied.
3) When the statements of loop are executed, the control is transferred back to last
statement in for loop and performs increment or decrement on a variable. And
the new value of a variable is again tested with the condition; if condition is
satisfied then again executes the statements of the loop. This happens
repeatedly again and again until the condition is satisfied.

Example:

#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
printf(“%d\t”,i);
}
}

Output:

0 1 2 3 4 5 6 7 8 9 10

Comparisons between while and do.. while loop statement

While do.. while


It is an entry controlled loop statement, i.e. It is an exit controlled loop statement, i.e. it
the condition is tested before executing the tests condition after executing the statements
statements of loop. of the loop.
Initially, if the condition becomes false then it Initially, it executes the statements of loop at
does not execute any statements of the loop. least once even the condition is false.
Jump (or) Loop Control (or) Unconditional Statements
These statements transfer control to another part of the program. When we want to break any
loop condition or to continue any loop with skipping any values and to directly jump to
termination of the program, we use these statements. There are four types of jumps
statements.

1. break statement
2. continue statement
3. goto statement

1. break statement: 
 By using this jump statement, we can terminate the further execution of the program and
transfer the control to the end of the loop.

 This statement always used with the control statements like switch case, while, do..
while, for loop etc.

Syntax: break;

Example:

#include<stdio.h>
void main()
{
int i=0;
while(i<=100)
{
if(i==10)
break;
i++;
printf(“%d\t”,i);
}
Printf(“Bye”);
}

Explanation: In the above program while is used to print values from 0 to 100, but in
this program break statement is used so, we get the output as 1 2 3 …. 10 Bye. Here, each time
‘i’ value is compared with 10, if condition is true then break statement is executed and the
control comes out of while loop and prints bye.
2. continue statement:

The continue statement is exactly opposite to break statement. It is used for continuing
next iteration of the loop statements. When continue statement occurs in the loop, it does not
terminate but it skips the statements after continue statement.

Syntax: continue;

Example:

#include<stdio.h>
void main()
{
int i;
for(i=0;i<=10;i++)
{
if((i==2) || (i==4) || (i==6))
continue;
else
printf(“%d\t”,i);
}
}

Explanation: When i=0,1,3,5,7,8,9,10 the if gets evaluated false, so that continue


statement will not be executed and prints 0 1 3 5 7 8 9 10 as output. When the if condition gets
evaluated to true then it automatically goes to increment the of ‘ i’ value.

3. goto statement:

The goto statement provides a method of transfer control to a labeled point in the
program. The goto statement requires a destination label declared as label_ name:

The goto statement can classified as:

1. Forward branching: if the label_name: is placed after the goto label then goto can
be referred as forward branching statement.

Syntax:

goto Label;
statements;
………………….
………………….
Label: statement;

2. Backward branching: if the label_name: is placed before the goto label then goto
can be referred as backward branching statement.
Syntax:

Label:
statements;
………………….
………………….
goto Label;
Advantage:
 It gives the power to jump to any part of program.

Disadvantages:
 It reduces the readability of the program.
 It becomes difficult to trace the control flow of a program.
 Difficult to understand program logic.
 Using goto statement is considered as poor programming practice. So try to
avoid goto statement as possible as you can.

Comparison among break, exit() and continue:

break exit() continue


It is used to terminate the It used to terminate the It is used to transfer the
loop or to exit loop from program. control to the starting of
switch case statement. the loop.
break statement causes It causes immediate It causes immediate
immediate termination of termination of the termination of the current
the loop. program. iteration.

You might also like