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

Introduction C

Uploaded by

hafidhadam2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Introduction C

Uploaded by

hafidhadam2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 122

C Programming

What is C?
 A language written by Brian Kernighan and
Dennis Ritchie. This was to be the language
that UNIX was written in to become the first
"portable" language

In recent years C has been used as a general-


purpose language because of its popularity
with programmers
What is C?
 C language is a general purpose and structured
programming language developed by 'Dennis Ritchie'
at AT &T's Bell Laboratories in the 1972s in USA.
 It is also called as 'Procedure oriented programming
language.'
 C is not specially designed for specific applications
areas like COBOL (Common Business-Oriented
Language) or FORTRAN (Formula Translation)
 It is well suited for business and scientific applications.
 It has some various features like control structures,
looping statements, arrays, macros required for these
applications
Why use C?
• Mainly because it produces code that runs
nearly as fast as code written in assembly
language. Some examples of the use of C might
be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Data Bases
• Language Interpreters
• Utilities
Mainly because of the portability that writing standard C programs can
offer
Why C Still Useful?
C provides:
 Efficiency, high performance and high quality
softwares
 flexibility and power
 many high-level and low-level operations  middle
level
 Stability and small size code
 Provide functionality through rich set of function
libraries
 Gateway for other professional languages like C  C+
+  Java
Why C Still Useful?
C is used:
 System software Compilers, Editors,
embedded systems
 data compression, graphics and computational
geometry, utility programs
 databases, operating systems, device drivers,
system level routines
 there are zillions of lines of C legacy code
 Also used in application programs
Software Development
Method
Requirement Specification
• Problem Definition
Analysis
• Refine, Generalize, Decompose the problem
definition
Design
• Develop Algorithm
Implementation
• Write Code
Verification and Testing
• Test and Debug the code
Documentation
Development with C
• Four stages
Editing: Writing the source code by using some IDE or
editor
Preprocessing or libraries: Already available routines
compiling: translates or converts source to object
code for a specific platform source code -> object
code
linking: resolves external references and
produces the executable module

Portable programs will run on any machine but…..


Note! Program correctness and robustness are most
important than program efficiency
Structure of C program

Include files
Global variable and
function declaration
Main functions

Function subprogram
Simple C Program
/* A first C Program*/

#include <stdio.h>

void main()

{
printf("Hello World \n");

}
Simple C Program
Line 1: #include <stdio.h>
As part of compilation, the C compiler runs a
program called the C preprocessor. The
preprocessor is able to add and remove code from
your source file.
In this case, the directive #include tells the
preprocessor to include code from the file stdio.h.
This file contains declarations for functions that
the program needs to use. A declaration for the
printf function is in this file.
Simple C Program
Line 2: void main()
• This statement declares the main function.
• A C program can contain many functions but
must always have one main function.
• A function is a self-contained module of code that
can accomplish some task.
• Functions are examined later.
• The "void" specifies the return type of main. In
this case, nothing is returned to the operating
system.
Simple C Program
Line 3: {

• This opening bracket denotes the start of the


program.
Simple C Program
Line 4: printf("Hello World From About\n");
• Printf is a function from a standard C library that
is used to print strings to the standard output,
normally your screen
• The compiler links code from these standard
libraries to the code you have written to produce
the final executable
• The "\n" is a special format modifier that tells the
printf to put a line feed at the end of the line
• If there were another printf in this program, its
string would print on the next line
Simple C Program
Line 5: }
• This closing bracket denotes the end of the
program
Escape Sequence

\n new line
\t tab
\a alert
\\ backslash
\” double quote
Comment
• Comment should be enclosed between /*
*/
• It is used to increase the readability of the
program
• Any number of comments can be given at
any place in the program
• Comment cannot be nested
• It can be split over more than one line
Getting started with C
Communicating with a computer involves speaking
the language the computer understands
Steps in learning English language

Alphabets Words Sentences Paragraph

Steps in learning C

Alphabets Constants
Digits Variables Instruction Program
Special-symbols Keywords
Keywords
• Keywords are the reserved words whose meaning has
already been explained to the C compiler
• C has 32 keywords
• These keywords combined with a formal syntax form a
C programming language
• Rules to be followed for all programs written in C:
• All keywords are lower-cased
• C is case sensitive, do-while is different from DO WHILE
• Keywords cannot be used as a variable or function name
C Keywords
Keywords
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
Identifiers
• Identifiers refer to the name of variables, functions and
arrays
• These are user-defined names and consist of sequence
of letters and digits, with a letter as a first character
• Both uppercase and lowercase letters are permitted,
although lowercase letters are commonly used
• The underscore character is also permitted in identifiers
• It is usually used as a link between two words in long
identifiers
Identifier Names


Some correct identifier names are - arena, s_count
marks40
class_one

Some erroneous identifier names are -

X
1stsst
oh!god
start….end
The number of characters in the variable that are
recognized differs from compiler to compiler
An identifier cannot be the same as a C keyword
Variables
• Variables are named locations in memory that are used
to hold a value that may be modified by the program
• Unlike constants that remain unchanged during the
execution of a program
• A variable may take different values at different times
during execution
• The syntax for declaring a variable is –
DataType IdentifierName ;
• Example- int num;
long int sum , a;
Constants
• Constants are the fixed values that do not
change during the execution of a program
• C supports several types of constants
• Numeric Constants
• Integer constants
• Real constants
• Character Constants
• Single character constant
• String Constants
Special Symbols

• ! , @, #, $ , & , * , ….. These all symbols that can be find


on Keyboard, are called Special Symbols

• Every symbol has its special meaning in different respect


at different place that’s why it is called Special Symbols
Character & String
• The Characters that can be used to form words,
numbers and expressions depend upon the computer
on which the program is running
• The characters in C are grouped into the following
categories :
• Letters
• Digits
• Special characters
• White Spaces
• Remember that a character ‘a’ is not equivalent to the
string “a”
Operators
• Operator is a symbol that operates on one or more
operands and produces output

Example - c=a+b;

• In the above Example the symbols + and = are


operators that operate on operands a, b , and c
Arithmetic in C

C operation Algebraic C

Addition(+) f+7 f+7

Subtraction (-) p-c p-c

Multiplication(*) bm b*m

Division(/) x/y, x , x y x/y

Modulus(%) r mod s r%s


Precedence order

• Highest to lowest

()
*, /, %
+, -
Example
Algebra:
z = pr%q+w/x-y

C:
z = p * r % q + w / x – y ;

Precedence:
1 2 4 3 5
Example

Algebra:
a(b+c)+ c(d+e)

C:
a * ( b + c ) + c * ( d + e )
;
Precedence:
3 1 5 4 2
Decision Making

• Checking falsity or truth of a statement


• Equality operators have lower precedence than
relational operators
• Relational operators have same precedence
• Both associate from left to right
Decision Making
• Equality operators
==
!=
• Relational operators
<
>
<=
>=
Summary of Precedence
Order
Operator Associativity

() left to right
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
= left to right
Assignment Operators
=
+=
-=
*=
/=
%=
Increment/ decrement
operators
++ ++a
++ a++
-- --a
-- a--
Increment/ decrement
operators
main()
{
int c;
c = 5;
printf(“%d\n”, c); 5
printf(“%d\n”, c++); 5
printf(“%d\n\n”, c); 6

c = 5; 5
printf(“%d\n”, c); 6
printf(“%d\n”, ++c); 6
printf(“%d\n”, c);

return 0;
}
printf & scanf
Printf & Scanf

• printf() and scanf() functions are inbuilt


library functions in C
• These functions are declared and related
macros are defined in “stdio.h” which is a
header file
printf ( ) function

• printf( ) function is used to print the


“character, string, float, integer, octal and
hexadecimal values” onto the output screen
• We use printf( ) function with %d format
specifies the displayed value of an integer
variable
• Similarly %c is used to display character,
%f for float variable, %s for string variable,
%lf for double and %x for hexadecimal
variable
• To generate a new line, we use “\n” in C
printf() statement
%d got replaced by value of an integer variable (no),
%c got replaced by value of a character variable (ch),
%f got replaced by value of a float variable (flt),
%lf got replaced by value of a double variable (dbl),
%s got replaced by value of a string variable (str),
%o got replaced by a octal value corresponding to
integer variable (no),
%x got replaced by a hexadecimal value
corresponding to integer variable
\n got replaced by a newline
#include <stdio.h>
int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
scanf() function:

• scanf() function is used to read character,


string, numeric data from keyboard
• Consider below example program where user
enters a character. This value is assigned to
the variable “ch” and then displayed
• Then, user enters a string and this value is
assigned to the variable ”str” and then
displayed
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( up to 100
character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
Output:

Enter any character


a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai
Note
• The format specifier %d is used in scanf()
statement. So that, the value entered is
received as an integer and %s for string
• Ampersand is used before variable name
“ch” in scanf() statement as &ch
• It is just like in a pointer which is used to
point to the variable
DATA TYPES
DATA TYPES
• C data types are defined as the data storage
format that a variable can store a data to
perform a specific operation
• Data types are used to define a variable
before to use in a program
• Size of variable, constant and array are
determined by data types
Data types:

S.no Types Data Types


1 Basic data types int, char, float, double
2 Enumeration data type Enum
3 Derived data type pointer, array, structure, union
4 Void data type void
Integer Data Type
• “int” keyword is used to refer integer data type which store
numeric values
• The storage size of int data type is 2 or 4 or 8 byte
• It varies depend upon the processor in the CPU that we use
• 16 bit processor, 2 byte (16 bit) of memory will be
allocated for int data type.
• Likewise, 4 byte (32 bit) of memory for 32 bit processor and
8 byte (64 bit) of memory for 64 bit processor
• int (2 byte) can store values from -32,768 to +32,767
• int (4 byte) can store values from -2,147,483,648 to
+2,147,483,647
• If you want to use the integer value that crosses the above
limit, you can go for “long int” and “long long int” for which
the limits are very high
Character Data Type
• Character data type allows a variable to store only one
character
• Storage size of character data type is 1
• We can store only one character using character data
type
• “char” keyword is used to refer character data type
• For example, ‘A’ can be stored using char data type
• You can’t store more than one character using char data
type
Floating Point Data Type
1. float
• Float data type allows a variable to store decimal
values
• Storage size of float data type is 4. This also varies
depend upon the processor in the CPU as “int” data
type
• We can use up-to 6 digits after decimal using float
data type
• For example, 10.456789 can be stored in a variable
using float data type
Floating Point Data Type

2. double
• Double data type is also same as float data type
which allows up-to 10 digits after decimal
• The range for double data type is from 1E–37 to
1E+37.
 Modifiers in C
• The amount of memory space to be allocated for a
variable is derived by modifiers
• Modifiers are prefixed with basic data types to modify
(either increase or decrease) the amount of storage
space allocated to a variable
• For example:
 storage space for int data type is 4 byte for 32 bit
processor
 We can increase the range by using long int which is 8
byte
 We can decrease the range by using short int which is
2 byte
storage
S.No Data Types Range
Size
1 Char 1 –127 to 127
2 Int 2 –32,767 to 32,767

3 Float 4 1E–37 to 1E+37 with six digits of precision

4 Double 8 1E–37 to 1E+37 with ten digits of precision

5 long double 10 1E–37 to 1E+37 with ten digits of precision


6 long int 4 –2,147,483,647 to 2,147,483,647
7 short int 2 –32,767 to 32,767
8 unsigned short int 2 0 to 65,535
9 signed short int 2 –32,767 to 32,767
10 long long int 8 –(2power(63) –1) to 2(power)63 –1
11 signed long int 4 –2,147,483,647 to 2,147,483,647
12 unsigned long int 4 0 to 4,294,967,295
unsigned long long
13
int
8 2(power)64 –1
Enumeration Data Type
• Enumeration data type consists of named integer
constants as a list
• It start with 0 (zero) by default and value is
incremented by 1 for the sequential identifiers in the
list

• Enum syntax in C:

enum identifier [optional{ enumerator-list }];


Enum example in C:
enum month { Jan, Feb, Mar };
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2
respectively by default */

enum month { Jan = 1, Feb, Mar };


/* Feb and Mar variables will be assigned to 2 and 3
respectively by default */

enum month { Jan = 20, Feb, Mar };


/* Jan is assigned to 20. Feb and Mar variables will be
assigned to 21 and 22 respectively by default */
#include <stdio.h>

int main()
{
enum MONTH { Jan = 0, Feb, Mar };

enum MONTH month = Mar;

if(month == 0)
printf("Value of Jan");
else if(month == 1)
printf("Month is Feb");
if(month == 2)
printf("Month is Mar");
}
Derived Data Type

• Array, pointer, structure and union are called


derived data type in C language
• To know more about derived data types, please
read “C – Array“ , “C – Pointer” , “C – Structure” and
“C – Union” topics
Void Data Type

• Void is an empty data type that has no value


• This can be used in functions and pointers
• Please read “C – Function” topic to know how to
use void data type in function with simple call by
value and call by reference example programs
VARIABLE

• C variable is a named location in a memory where a


program can manipulate the data
• This location is used to hold the value of the
variable
• The value of the C variable may get change in the
program
• C variable might be belonging to any of the data
type like int, float, char etc
VARIABLE

Rules for naming C variable:


• Variable name must begin with letter or
underscore
• Variables are case sensitive
• They can be constructed with digits, letters
• No special symbols are allowed other than
underscore
• sum, height, _value are some examples for
variable name
VARIABLE
Declaring & initializing C variable:
• Variables should be declared in the C program before
to use
• Memory space is not allocated for a variable while
declaration. It happens only on variable definition
• Variable initialization means assigning a value to the
variable

S.No Type Syntax Example


1
Variable data_type int x, y, z; char
declaration variable_name; flat, ch;
int x = 50, y = 30;
2
Variable data_type
char flag = ‘x’,
initialization variable_name = value; ch=’l’;
VARIABLE
There are three types of variables in C program
Local variable
• The scope of local variables will be within the
function only
• These variables are declared within the function
and can’t be accessed outside the function
#include<stdio.h>
void test();

int main()
{
int m = 22, n = 44;
// m, n are local variables of main function
/*m and n variables are having scope within this main function
only. These are not visible to test funtion.*/
/* If you try to access a and b in this function, you will get
'a' undeclared and 'b' undeclared
error */
printf("\nvalues : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80;
// a, b are local variables of test function
/*a and b variables are having scope within this test
function only. These are not visible to main function.*/
/* If you try to access m and n in this function, you will get
'm' undeclared and 'n' undeclared error */
printf("\nvalues : a = %d and b = %d", a, b);
VARIABLE

There are three types of variables in C program


Global variable
• The scope of global variables will be throughout
the program
• These variables can be accessed from anywhere in
the program
• This variable is defined outside the main function,
that the variable is visible to main function and all
other sub functions
#include<stdio.h>
void test();
int m = 22, n = 44;
int a = 50, b = 80;
int main()
{
printf("All variables are accessed from main function");

printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);
test();

void test()
{

printf("\n\nAll variables are accessed from" \


" test function");

printf("\nvalues : m= %d : n= %d : a= %d : b= %d“ ,m,n,a,b);


}
VARIABLE
Environment variables in C:
• A variable that will be available for all C
applications and C programs
• We can access these variables from anywhere in
a C program without declaring and initializing in
an application or C program
• The inbuilt functions which are used to access,
modify and set these environment variables are
called environment functions
• There are 3 functions which are used to access,
modify and assign an environment variable in C:
1. setenv()
2. getenv()
3. putenv()
VARIABLE
• Difference between variable declaration & definition in C:

S.no Variable declaration Variable definition

• Declaration tells the compiler Definition allocates memory


1 about data type and size of the •
for the variable
variable

2
• Variable can be declared many • It can happen only one time
times in a program for a variable in a program

3
• The assignment of properties • Assignments of storage
and identification to a variable space to a variable
CONSTANT

• C Constants are also like normal variables


• But, only difference is, their values can not be modified
by the program once they are defined (fixed values)
• Constants may be belonging to any of the data type

Syntax:
const data_type variable_name;
(or)
const data_type *variable_name;
CONSTANT
Rules for constructing C constant:
1. Integer Constants in C:
• An integer constant must have at least one digit
• It must not have a decimal point
• It can either be positive or negative
• No commas or blanks are allowed within an integer constant
• If no sign precedes an integer constant, it is assumed to be
positive
• The allowable range for integer constants is -32768 to 32767
CONSTANT
Rules for constructing C constant:
2. Real constants in C:
• 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
CONSTANT
Rules for constructing C constant:
3. Character and string constants in C:
• A character constant is a single alphabet, a single digit or a
single special symbol enclosed within single quotes
• The maximum length of a character constant is 1 character
• String constants are enclosed within double quotes
CONSTANT
Rules for constructing C constant:
4. Backslash Character Constants in C:
• 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
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
Octal constant (N is an octal
\N
constant)
Hexadecimal constant (N – hex.dcml
\XN
cnst)
CONSTANT
S.no Constant type data type Example

int 53, 762, -478 etc


unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680

Real or Floating float 10.456789


2
point constants doule 600.123456789
013 /* starts with
3 Octal constant int
0 */
Hexadecimal 0×90 /* starts with
4 int
constant 0x */
character
5 char ‘A’ , ‘B’, ‘C’
constants
6 string constants char “ABCD” , “Hai”
CONSTANT
•How to use constants in a C program?
• We can define constants in a C program in the
following ways.
• By “const” keyword
• By “#define” preprocessor directive
• Please note that when you try to change constant
values after defining in C program, it will through
error
#include <stdio.h>

void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/

printf("value of height : %d \n", height );


printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
#include <stdio.h>

#define height 100


#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'

void main()
{

printf("value of height : %d \n", height );


printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

}
OPERATORS AND EXPRESSIONS
• The symbols which are used to perform logical and
mathematical operations in a C program are called C
operators
• These C operators join individual constants and variables
to form expressions
• Operators, functions, constants and variables are
combined together to form expressions
• Consider the expression A + B * 5. where, +, * are
operators, A, B are variables, 5 is constant and A + B * 5 is
an expression
OPERATORS AND EXPRESSIONS
Types of C operators:
• Arithmetic operators
• Assignment operators
• Relational operators
• Logical operators
• Bit wise operators
• Conditional operators (ternary operators)
• Increment/decrement operators
• Special operators
Types of C operators
Arithmetic Operators in C:
• C Arithmetic operators are used to perform mathematical
calculations like addition, subtraction, multiplication,
division and modulus in C programs
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
#include <stdio.h>
int main()
{
int a=40,b=20, add,sub,mul,div,mod;

add = a + b;
sub = a - b;
mul = a * b;
div = a / b;
mod = a % b;

printf("Addition of a, b is : %d\n", add);


printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
Types of C operators
Assignment operators in C:
Operators Example Explanation
Simple assignment 10 is assigned to
operator = sum=10
variable sum
This_is_same_as_sum=su
+= sum+=10
m+10…………
This is same as sum =
-= sum-=10
sum-10
This is same as sum =
*= sum*=10
sum*10
Compound assignment This is same as sum =
operators /+ sum/=10
sum/10
This is same as sum =
%= sum%=10
sum%10
This is same as sum =
&= sum&=10
sum&10
This is same as sum =
^= sum^=10
sum^10
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
{
Total+=i; // This is same as Total =

Total+i
}
printf("Total = %d", Total);
}
Types of C operators
Relational operators in C:
• Relational operators are used to find the relation between two
variables. i.e. to compare the values of two variables in a C program
S.no Operators Example Description
1 > x>y x is greater than y
2 < x<y x is less than y
x is greater than or
3 >= x >= y
equal to y
x is less than or equal
4 <= x <= y
to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Types of C operators
Logical operators in C:
• Are used to perform logical operations on the given expressions
• There are 3 logical operators in C language
S.no Operators Name Example Description
It returns true when both conditions
1 && logical AND (x>5)&&(y<5)
are true
(x>=10)|| It returns true when at-least one of
2 || logical OR
(y>=10) the condition is true

It reverses the state of the operand


!
“((x>5) && (y<5))”
3 ! logical NOT ((x>5)&&(y<5)
If “((x>5) && (y<5))” is true, logical
)
NOT operator makes it false
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \
"But, status is inverted as false\n");
}
}
Types of C operators
Conditional or ternary operators in C:
• Conditional operators return one value if condition is true and
returns another value is condition is false
• This operator is also called as ternary operator

Syntax : (Condition? true_value: false_value);


Example : (A > 100 ? 0 : 1);
• In above example, if A is greater than 100, 0 is returned else
1 is returned. This is equal to if else conditional statements
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Types of C operators
• Increment operators are used to increase the value of the
variable by one
• Decrement operators are used to decrease the value of the
variable by one in
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – – var_name; (or) var_name – – ;
Example:
Increment operator: ++i; i++;
Decrement operator: – – i ; i – – ;
Types of C operators
Difference between pre/post increment & decrement
operators in C:
S.n Operator
Operator Description
o Type
Value of i is incremented
Pre ++i
1 before assigning it to
increment
variable i
Value of i is incremented
Post- i++
2 after assigning it to
increment
variable i
Value of i is decremented
Pre – –i
3 before assigning it to
decrement
variable i
Value of i is decremented
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int i=0; int i=0;
while(++i < 5 ) while(i++ < 5 )
{ {
printf("%d printf("%d
",i); ",i);
} }
return 0; return 0;
} }
#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int i=10; int i=10;
while(--i > 5 ) while(i-- > 5 )
{ {
printf("%d printf("%d
",i); ",i);
} }
return 0; return 0;
} }
Types of C operators
• Special Operators in C:
S.n Operato
Description
o rs
This is used to get the address of the
1 & variable
Example : &a will give address of a
This is used as pointer to a variable
2 * Example : * a where, * is pointer to the
variable a
Sizeof This gives the size of the variable
3
() Example : size of (char) will give us 1
In this program, “&” symbol is used to get
the address of the variable and “*” symbol
is used to get the value of the variable that
the pointer is pointing to
#include <stdio.h>

int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
#include <stdio.h>
#include <limits.h>

int main()
{

int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
}
Types of C operators
• Bit wise operators in C:
• These operators are used to perform bit operations
• Decimal values are converted into binary values which are the
sequence of bits and bit wise operators work on these bits
• Bit wise operators in C language are
& (bitwise AND)
| (bitwise OR)
~ (bitwise NOT)
^ (XOR)
<< (left shift)
>> (right shift)
#include <stdio.h>
int main()
{
int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
CONTROL STATEMENT
DECISION CONTROL STATEMENT
• In decision control statements (C if else and nested if),
group of statements are executed when condition is
true. If condition is false, then else part statements
are executed.
• There are 3 types of decision making control
statements in C language. They are,
• if statements
• if …… else statements
• nested if statements
DECISION CONTROL STATEMENT
Decision
control
Syntax Description
statement
s
if (condition) In these type of statements, if condition is
if
{ Statements; } true, then respective block of code is executed.
if (condition)
In these type of statements, group of
{ Statement1; Statem
statements are executed when condition is
ent2;}
if…else true.
else
If condition is false, then else part statements
{ Statement3; Statem
are executed.
ent4; }
if (condition1) If condition 1 is false, then condition 2 is
{ Statement1; } checked and statements are executed if it is
nested if else_if (condition2) true.
{ Statement2; } If condition 2 also gets failure, then else part is
else Statement 3; executed.
if statements

int main()
{
int m=40,n=40;
if (m == n)
{
printf("m and n are equal");
}
}
if ….. else statements
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n) {
printf("m and n are equal");
}
else {
printf("m and n are not equal");
}
}
Nested if statements
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
LOOP CONTROL STATEMENTS
• Loop control statements in C are used to perform
looping operations until the given condition is true.
Control comes out of the loop statements once
condition becomes false.
• There are 3 types of loop control statements in C
language
• for
• while
• do-while
LOOP CONTROL STATEMENTS
S.n Loop
Syntax Description
o Name
Where,
exp1 – variable initialization
for (exp1; exp2; ( Example: i=0, j=2, k=3 )
1 For expr3) exp2 – condition checking
{ statements; } ( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )
while (condition) where,
2 While
{ statements; } condition might be a>5, i<10
do { statements;
where,
3 do while }
condition might be a>5, i<10
while (condition);
for Loop

#include <stdio.h>

int main()
{
int i;

for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
while Loop

#include <stdio.h>
int main()
{
int i=3;

while(i<10)
{
printf("%d\n",i);
i++;
}
}
do … while Loop

#include <stdio.h>
int main()
{
int i=1;

do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
}
Difference between while & do while
loops in C:

S.
while do while
no
Loop is Loop is executed for first time
executed irrespective of the condition.
1 only when After executing while loop for
condition is first time, then condition is
true. checked.
CASE CONTROL STATEMENTS

• The statements which are used to execute only


specific block of statements in a series of blocks are
called case control statements.
• There are 4 types of case control statements in C
language:
• switch
• break
• continue
• goto
CASE CONTROL STATEMENTS
switch case statement in C:
• Switch case statements are used to execute only specific case
statements based on the switch expression.
• Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf("Value is 1 \n" );
break;
case 2:
printf("Value is 2 \n" );
break;
case 3:
printf("Value is 3 \n" );
break;
case 4:
printf("Value is 4 \n" );
break;
default :
printf("Value is other than 1,2,3,4 \n" );
}
return 0;
}
CASE CONTROL STATEMENTS
Break statement in C:
• Break statement is used to terminate the while loops,
switch case loops and for loops from the subsequent
execution.

Syntax: break;
#include <stdio.h>
int main()
{
int i;

for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i =
5");
break;
}
printf("%d ",i);
}
}
CASE CONTROL STATEMENTS
Continue statement in C:
• Continue statement is used to continue the next iteration
of for loop, while loop and do-while loops.
• So, the remaining statements are skipped within the loop
for that particular iteration.

Syntax : continue;
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf("\nSkipping %d from display using " \
"continue statement \n",i);
continue;
}
printf("%d ",i);
}
}
CASE CONTROL STATEMENTS
goto statement in C:
• goto statements is used to transfer the normal flow of a
program to the specified label in the program.
Syntax
{
…….
go to label;
…….
…….
LABEL:
statements;
}
#include <stdio.h>

int main()
{
int i;

for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nWe are using goto statement when i = 5");
goto HAI;
}
printf("%d ",i);
}

HAI : printf("\nNow, we are inside label name \"hai\" \n");

}
Thank You
• Thank You

You might also like