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

C Notes - Module1

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

INTRODUCTION OF C LANGUAGE

C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972 by Dennis
Ritchie. The development of C is given in the figure below:

Major parts of popular operating systems like Windows, UNIX, Linux is still written in C. This is
because even today when it comes to performance (speed of execution) nothing beats C. Moreover,
if one is to extend the operating system to work with new devices one needs to write
device driver programs. These programs are
exclusively written in C. Also, common consumer
devices like microwave oven, washing machines
and digital cameras are getting smarter by the day.
This smartness comes from a microprocessor, an
operating system and a program embedded in this
devices. These programs not only have to run fast
but also
have to work in limited amount of memory. No wonder that such programs are written in C. C is
a compiled language. That means the computer will not interpret the code directly. Instead, you
will need to convert—or compile—the human-readable source code into machine-readable
machine code.
FEATURES OF C

• Simple: C is a simple language in the sense that it provides structured approach (to break
the problem into parts), rich set of library functions, data types etc.
• Machine Independent or Portable: Unlike assembly language, c programs can be
executed in many machines with little bit or no change. But it is not platform-
independent.
• Mid-level prorgramming language: C is also used to do low level programming. It is
used to develop system applications such as kernel, driver etc. It also supports the feature
of high level language. That is why it is known as mid-level language.
• Rich Library: C provides a lot of inbuilt functions that makes the development fast.
• Speed: The compilation and execution time of C language is fast.
• Extensible: C language is extensible because it can easily adopt new features.Structured
prorgramming language
• Structured prorgramming language: C is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to
understand and modify.
Structured programming (sometimes known as modular programming) is a subset of procedural
programming that enforces a logical structure on the program being written to make it more
efficient and easier to understand and modify. Certain languages such as Ada, Pascal, and dBASE
are designed with features that encourage or enforce a logical program structure.

One of the biggest advantages of using any structured language is that a programmer can declare
local variables inside a given boundary and these local variables are only available to the code
which is a part of that structure. For example, in C language a programmer can declare a local
variable which can only be used inside the function body where it is declared. In the absence of
functions and local variables programmers will have to create global variables and this will lead
to many bugs in the program because of uncontrolled access to global data.

Although the term block-structured language does not strictly apply to C, C is commonly reffered
to sructured language. It has many similarities to other structured languages, sunch as ALGOL
Pascal, and Module-2. The reason that C (and C++) is not, technically, a block-structured
language is that block-structured languages permit procedures or functions to be declared inside
other procedures or functions. Since C does not allow the creation of functions
within functions, it cannot formally be called block-structured.

STRUCTURE OF C PROGRAM

The computer will start running your program from the main() function. The name is important: if
you don’t have a function called main(), your program won’t be able to start. The main() function
has a return type of int. So what does this mean? Well, when the computer runs your program, it
will need to have some way of deciding if the program ran successfully or not. It does this by
checking the return value of the main() function. If you tell your main() function to return 0, this
means that the program was successful. If you tell it to return any other value, this means that there
was a problem.
The function name comes after the return type. That’s followed by the function parameters if there
are any. Finally, we have the function body. The function body must be surrounded by braces.
DATA TYPE IN C
Data types in C programming language enables the programmers to appropriately select
the data as per requirements of the program and the associated operations of handling
it.

Data types in c language can be broadly classified as:

1. Primitive Data Types


2. User Defined Data Types, for example, enum, structure, union
3. Derived Data Types, for example, array, pointers

Primitive Data Types


The primitive data types in c language are the inbuilt data types provided by the c
language itself. Thus, all c compilers provide support for these data types.

The following primitive data types in c are available:

• Integer Data Type, int


Integer data type is used to declare a variable that can store numbers without a decimal.
The keyword used to declare a variable of integer type is “int”. Thus, to declare integer
data type following syntax should be followed:

int variable_name;

• Float data Type, float

Float data type declares a variable that can store numbers containing a decimal
number,floating point numbers (single precision).

Syntax

float variable_name;

• Double Data Type, double

Double data type also declares variable that can store floating point numbers but gives
precision double than that provided by float data type. Thus, double data type are also
referred to as double precision data type.

Syntax

double variable_name;

Note:- Single precision and Double precision basically differs in the number of digits represented after
the decimal point. Double precision number will represent more digits after the decimal point than a
single precision number. Example: - Single precision – 32.75 and double precision – 32.7543

• Character Data Type, char

Character data type declares a variable that can store a character constant. Thus, the
variables declared as char data type can only store one single character.

Syntax

char variable_name;

• Void Data Type, void


Unlike other primitive data types in c, void data type does not create any variable but
returns an empty set of values. Thus, we can say that it stores null.

Syntax

void variable_name;

Data Type Qualifiers


Apart from the primitive data types mentioned above, there are certain data type
qualifiers that can be applied to them in order to alter their range and storage space and
thus, fit in various situations as per the requirement.

The data type qualifiers available in c are:

• Short
• Long
• Signed
• unsigned

It should be noted that the above qualifiers cannot be applied to float and can only be
applied to integer and character data types.

The entire list of data types in c available for use is given below:

Size(in
C Data Types Range
bytes)

Int
2 -32,768 to 32,767
signed int
2 -32,768 to 32,767
unsigned int
Integer Data Types 2 0 to 65535
short int
1 -128 to 127
signed short
1 -128 to 127
int
unsigned short 1 0 to 255
int
4 -2,147,483,648 to
long int 2,147,483,647
4
signed long int Same as Above
4
unsigned long 0 to 4,294,967,295
int

float 4 3.4E-38 to 3.4E+38

Floating Point Data double 8 1.7E-308 to 1.7E+308


Types
long double 10 3.4E-4932 to 1.1E+4932

char 1 -128 to 127

Character Data signed char 1 -128 to 127


Types
unsigned char 1 0 to 255
Keyword Format Specifier Size Date Range

%c 1 byte -128 to +127


Char

%d 2 bytes 0 to 255
Int

%f 4 bytes
Float -3.4e38 to +3.4e38

%lf 8 bytes
Double -1.7e38 to +1.7e38

%ld 4 bytes
long int -231 to +231

%u 2 bytes 0 to 65535
unsigned int

%Lf 16 bytes
long double -3.4e38 to +3.4e38

%c 1 byte 0 to 255
Unsigned char
C TOKENS
A compiler designer prescribes rules for making a program using statements. The smallest
unit in a program/statement is called a token. The compiler identifies them as token. The
keywords, identifiers, constants, string literals, and operators are examples of tokens. Punctuation
characters such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.

Keywords:
Keywords are the reserved words used in programming. Each keywords has fixed meaning
and that cannot be changed by user. For example:

int roll;

Here, int is a keyword that indicates, 'roll' is of type integer.

As, C programming is case sensitive, all keywords must be written in lowercase. Here is
the list of all keywords predefined by ANSI C.

Keywords in C Language

Auto Double int struct


Break Else long switch

Case Enum register typedef

Char Extern return union

continue For signed void

Do If static while

default Goto sizeof volatile

Const Float short unsigned

Besides these keywords, there are some additional keywords supported by Turbo C.

Additional Keywords for Borland C

as Fa interru pasca nea hug cdec


m r pt l r e l

Identifiers
Identifiers, as the name suggests help us to identify data and objects in the program. Identifiers
are basically the name given to program elements such as variables, arrays, and functions.

Rules for formatting Identifier names

(1) It cannot include any special characters or punctuation marks (like #, $, ^,?, etc) except
the underscore ‘_”.
(2) There cannot be two successive underscores.
(3) Key words cannot be used as identifiers.
(4) The case of alphabets characters that form the identifier name is significant. For example
“First” is different from ‘first’ and ‘FIRST’.
(5) The identifier name must begin with an alphabet or and underscore. However, use of
underscore as the first character must be avoided because several compiler-defined
identifiers in the standard C library have underscore as their first character.
(6) Identifier can be of any reasonable length. They shoud not contain more than 31
characters.

Example of valid identifier

Roll_no,marks,emp_number,basic_pay etc.

Example of invalid identifiers

23_student, #roll, %name, -hra etc.

Variable
A variable is defined as a meaningful name given to the data storage location in computer memory.
When using a variable, we actually refer to address of the memory where the is stored. C language
supports two basic kinds of variable-numeric and character.

Each variable to be used in the program must be declared. To declare a variable, specify the data type
of the variable followed by its name.

Int roll_no, float salary, char grade etc.

While declaring a variables, we can also initialize them with some value. For example,

int roll_no=11;

float salary=40000;

char grade=’A’

Constants
There are 4 types of constants in C.

▪ Integer constants
▪ Character constants
▪ Real/Floating point constants
▪ String constants
By definition, a constant is a quantity that does not change throughout the execution of a program.

Integer Constants

An integer constant is an integer quantity which contains a sequence of digits.It should not have a
decimal point. Blanks and commas are not allowed within an integer constant.An integer constant can
be either +ve or -ve. The constant must lie within the range of the declared data type (including
qualifiers long,short etc.).

Example of valid integer constants:- 976 8987 5 -25 etc.


Example of invalid integer constants:- 78.43 7-8 89,76 etc.
An integer constant can be either Decimal, Hexa Decimal or Octal. See the table below to
understand how these 3 different constants are defined in C.

Integer Type
Prefix Suffix Example

Ox
Hexa Decimal OxA7B
O
Octal O54

Ox I or L
Long Hexa Decimal OxA7BL

Unsigned Long Hexa


Ox UI or UL
Decimal OxA7FUI

O I or L
Long Octal O54L

▪ A decimal constant can contain any combination of integers from 0 through 9. Ex:
189 0 75 87
▪ A hexa decimal constant should begin with 0X or 0x. Ex: 0x65F or 0X7A
▪ An octal constant should begin with digit 0. It can take any digits from 0 through 7.
Note:- There is no binary integer constant in C by default. This means, you cant give a binary number
directly to program by writing sth like:- 0b11001011 – which is meaningless and result in an error. How
ever, programmer can add a preprocessor (which we will learn later) to accept binary numbers in a
program.
Floating Point Constants

They are also known as real constants. A real constant contains a decimal point or an exponent. It
can be either +ve or -ve. Commas and blank space are not allowed within a real constant.

Examples:– 254.175, -16.47 -0.5e-7 +4.1e8


A literal like 0.07 is treated as of type double by default. To make it a float type literal, you must
specify it using suffix ‘F’ or ‘f’.
Examples:– 0.02F, 0.34f, 3.141592345L, 0.002314, 2.123E-3
Note that suffix L is for long double.
A floating point number may also be expressed in scientific notation. In this notation, the mantissa is
either a floating point number or an integer and exponent is an integer with an optional plus or minus
sign. Therefore, the numbers given below are bvalid floating point numbers

0.5e2, 14E+3, 2.1E-3, -5.6e-2


Thus, scientific notation is used to express numbers that are either very small or very large. For
example,
120000000=1.2E8 and -0.000000025=-2-5E-8
Character Constant

A character constant is a character which is enclosed in single quotes. A character constant is of


size 1byte and can contain only 1 character. A character can be an alphabet like a,b,A,C etc or a
special character like &,^, $, #,@ etc or a single digit from 0 through 9. It can also be an escape
sequence character like space ‘ ‘ or a null character ‘\o’ or a new line ‘\n’ etc.

Example: ‘A’ ‘a’ ‘ b’ ‘8’ ‘#’ etc.


Each character has a corresponding ASCII value. ASCII value is the numeric code of a particular
character and is stored inside the machine’s character set.
Note:- It is good that you read more about ASCII. There are basically two types of ASCII characters
known as control characters and printable characters. Control characters are usually used to
control a device using the program or to manipulate some logic inside a program. Control characters
are not usually printed to an output device. Printable characters are usually printed to a display
device or a printer.
String Constants

A. A string constant is a collection of characters enclosed in double quotations “”


B. It may contain alphabets, digits, special characters and blank space.
Example: “Circuits Today123″

CONSTANT VS LITERAL
A literal is a value that is expressed as itself. For example, the number 25 or the string
“Hello World” is both literals.
A constant is a data type that substitutes a literal. Constants are useful in situations where
• a specific, unchanging value is to be used at various times during the software program
• you want to more easily understand the software code
A variable in a program can change its value during the course of execution of the program.
A constant retains the same value throughout the program.

Constant Literal

const PI = 3.14; var radius = 5; var radius = 5;


var circumference = 2 * PI * radius; var circumference = 2 * 3.14 * radius;

Suppose we are writing a program to determine which members of a population are eligible to vote,
permitted to drink, both or neither.
Constant Literal

const PI = 3.14; var radius = 5; var radius = 5;


var circumference = 2 * PI * radius; var circumference = 2 * 3.14 * radius;

const DRINKING_AGE = 21;


const VOTING_AGE = 18;
18 and 21 are literals. We could use these literals in all areas of our program. For example, if(age >
18) or if(age < 21). But we can make our code more understandable if we
use constants instead. if(age > VOTING_AGE) is easier to understand. Other benefits of using
constants are

• Constants free the programmer from having to remember what each literal should be. Often values that
stay constant throughout the program have a business meaning. If there are several such values, the
programmer can define them all in the beginning of the program and then work with the easier-to-
remember constant names.
• If business requirements dictate that the constant be changed (for example, if the drinking age is
lowered to 20 in the future), it is much easier to adapt the program. If we use literals throughout the
program, the change will be hard to do and there is a good chance some instances will not be corrected.

INPUT /OUTPUT IN C
printf() function
int printf(const char *format [,argument, …]);

The printf() function do the following:

• Accept a series of arguments


• Apply to each argument a format specifier contained in the format string *format
• Output the formatted data to the screen

On success, the printf functions return the number of bytes.

#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;
}
OUTPUT:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96

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

int integer = 9876;


float decimal = 987.6543;

// Prints the number right justified within 6 columns


printf("4 digit integer right justified to 6 column: %6d\n", integer);

// Tries to print number right justified to 3 digits but the number is not right adjusted because
there are only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);

// Rounds to two digit places


printf("Floating point number rounded to 2 digits: %.2f\n",decimal);

// Rounds to 0 digit places


printf("Floating point number rounded to 0 digits: %.f\n",987.6543);

// Prints the number in exponential notation(scientific notation)


printf("Floating point number in exponential form: %e\n",987.6543);
return 0;
}
OUTPUT:
4 digit integer right justified to 6 column: 9876
4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02

scanf() function
int scanf(const char *format [,address, …]);

The scanf() functions do the following:


• Scan a series of input fields one character at a time
• Format each field according to a corresponding format specifier passed in the format string
*format.
• Store the formatted input at an address passed as an argumanet following *format.

On success, scanf() function return the number of input fields successfully scanned, converted, and
stored. Return value =0 if no fields were stored.

#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 ( upto 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

OPERATORS IN C
Operators are the symbol which operates on value or a variable. For example: + is a
operator to perform addition.
C programming language has wide range of operators to perform various operations. For
better understanding of operators, these operators can b e classified as:

Arithmetic Operators

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* Multiplication

/ Division

% remainder after division( modulo division)

Example of working of arithmetic operators


/* Program to demonstrate the working of arithmetic operators in C. */
#include <stdio.h>
int main(){
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}

a+b=13

a-b=5

a*b=36

a/b=2

Remainder when a divided by b=1

Explanation

Here, the operators +, - and * performed normally as you expected. In normal


calculation, 9/4 equals to 2.25. But, the output is 2 in this program. It is because, a and b are
both integers. So, the output is also integer and the compiler neglects the term after decimal
point and shows answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided
by b=4, remainder is 1.

Suppose a=5.0, b=2.0, c=5 and d=2

In C programming,

a/b=2.5

a/d=2.5

c/b=2.5

c/d=2

Note: % operator can only be used with integers.


Increment and decrement operators
In C, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -
- subtracts 1 to operand respectively. For example:

Let a=5 and b=10

a++; //a becomes 6

a--; //a becomes 5

++a; //a becomes 6

--a; //a becomes 5

Difference between ++ and -- operator as postfix and prefix

When i++ is used as prefix (like: ++var ), ++var will increment the value of var and then
return it but, if ++ is used as postfix (like: var++), operator will return the value of operand
first and then only increment it. This can be demonstrated by an example:

#include <stdio.h>
int main(){
int c=2,d=2;
printf("%d\n",c++); //this statement displays 2 then, only c incremented by 1 to 3.
printf("%d",++c); //this statement increments 1 to c then, only c is displayed.
return 0;
}

Output

Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to
the left side. For example:

var=5 //5 is assigned to var

a=c; //value of c is assigned to a

5=c; // Error! 5 is a constant.


Operator Example Same as

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b

Relational Operator

Relational operators check relationship between two operands. If the relation is true, it
returns value 1 and if the relation is false, it returns value 0. For example: a>b Here, > is
a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.

Operator Meaning of Operator 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)


Operator Meaning of Operator Example

<= Less than or equal to 5<=3 return false (0)

EXAMPLE:
/*Relational operator */
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10,b=20;
clrscr();
printf("\n %d<%d=%d",a,b,a<b);
printf("\n %d<=%d=%d",a,b,a<=b);
printf("\n %d>%d=%d",a,b,a>b);
printf("\n %d>=%d=%d",a,b,a>=b);
printf("\n %d==%d=%d",a,b,a==b);
printf("\n %d!=%d=%d",a,b,a!=b);
getch();
return 0;
}
OUTPUT:
10<20=1
10<=20=1
10>20=0
10>=20=0
10==20=0
10!=20=1

Logical Operators
Logical operators are used to combine expressions containing relation operators. In C,
there are 3 logical operators:
Meaning of
Operator Operator Example

Logial If c=5 and d=2 then,((c==5) &&


&& AND (d>5)) returns false.

Logical If c=5 and d=2 then, ((c==5) || (d>5))


|| OR returns true.

Logical
! NOT If c=5 then, !(c==5) returns false.

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true,
either the expression should be true. Since, (c==5) is true. So, the expression is true. Since,
expression (c==5) is true, !(c==5) is false.

Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C. For example:

c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10.

/*Conditional operator*/
#include<stdio.h>
#include<conio.h>
int main()
{
int num1,num2,larger;
//clrscr();
printf("\nEnter two Numbers:");
scanf("%d%d",&num1,&num2);
larger=num1>num2?num1:num2;
printf("Larger of %d and %d is: %d",num1,num2,larger);
getch();
return 0;
}
OUTPUT:
Enter two Numbers:10
13
Larger of 10 and 13 is: 13

Bitwise Operators
Bitwise operators operate on individual bits of integer (int and long) values. This is useful for
writing low-level hardware or OS code where the ordinary abstractions of numbers, characters,
pointers, and so on, are insufficient. Bit manipulation code tends to be less "portable". Code is
"portable" if without any programmer intervention it compiles and runs correctly on different types
of computers. The bit wise operations are commonly used with unsigned types. These operators
perform bit wise logical operations on values. Both operands must be of the same type and width:
the resultant value will also be this type and width. These operators include: bitwise AND, bitwise
OR, bitwise XOR and shift operators.

Biwise operators are:

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left (multiply by power of 2)


Operators Meaning of operators

>> Shift right (divide by power of 2)

Definition of bitwise logical operators:


Bit a Bit b a&b a|b a^b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Example:
Bitwise Negation
a=00000011
~a =11111100
Bitwise And
a = 00000011
b = 00010110
a&b=00000010
Bitwise Or
a = 00000011
b = 00010110
a|b=00010111
Bitwise Exclusive Or
a = 00000011
b = 00010110
a^b=00010101
.

Left shift
When we apply a left-shift, every bit is shifted to the left by one place. So the MSB of the number is lost,
the LSB of number is set to 0.Shifting once to the left multiplies the number by 2.
On the contrary, when we apply a shift-right operator, every bit in number is shifted to the right by one
place. So, the LSB of the number is set to 0.

Right Shift
a = 0000 0011 = 3
(a<<=1) = 00000110 = 6
(a<<=2) = 00011000 = 24
(a<<=3) = 11000000 = 192
Left Shift
a=11000000 =192
(a>>=1) = 01100000 = 96
(a>>=2) = 00011000 = 24
(a>>=3) = 0000 0011 = 3

Example:
/*Bitwise operator*/
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10,b=12,c=0;
c=a&b;
printf("\n the value of c after a&b is %d",c);
c=a|b;
printf("\n the value of c after a|b is %d",c);
c=a^b;
printf("\n the value of c after a^b is %d",c);
printf("\n the value of a after a>>1 is %d",a>>1);
printf("\n the value of b after b<<1 is %d",b<<1);
getch();
return 0;
}
OUTPUT:
the value of c after a&b is 8
the value of c after a|b is 14
the value of c after a^b is 6
the value of a after a>>1 is 5
the value of b after b<<1 is 24
sizeof operator in C
Sizeof is a 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.

• When sizeof() is used with the data types such as int, float, char… etc it simply return
amount of memory is allocated to that data types.

#include<stdio.h>
int main()
{
printf("%d\n",sizeof(char));
printf("%d\n",sizeof(int));
printf("%d\n",sizeof(float));
printf("%d", sizeof(double));
return 0;
}

Output
1
4
4
8

• Size of constant

#include<stdio.h>

int main() {

printf("%d", sizeof(10));
printf("%d", sizeof('A'));
printf("%d", sizeof(10.10));

return 0;
}
• 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("%d", sizeof(a+d));
return 0;
}
Output
8

/*sizeof operator*/
#include<stdio.h>
#include<conio.h>
int main()
{
int si=-10;
unsigned int ui=11;
long int li=12345;
long unsigned int lui=123456;

float f=11.34f;
double d=231.123;
long double ld=1234.645;
char ch='a';
clrscr();
printf("\nsi=%d",si);
printf("\nui=%u",ui);
printf("\nli=%ld",li);
printf("\nlui=%lu",lui);
printf("\nf=%f",f);
printf("\nf=%e",f);
printf("\nd=%lf",d);
printf("\nld=%Lf",ld);
printf("\nch=%c",ch);
printf("\n\nsize of integer=%d",sizeof(int));
printf("\nsize of long signed integer=%d",sizeof(long signed int));
printf("\nsize of float=%d",sizeof(float));
printf("\nsize of double=%d",sizeof(double));
printf("\nsize of long double=%d",sizeof(long double));
getch();
return 0;
}
DECISION CONTROL STATEMENTS
1. If statement
The if statement is the simplest form of decision control statements that is
frequently used in decision making. The general from of if statement is :-
if (condition)

//Block of C statements here

//The above statements will only execute if the condition is true

..

The if structure may include one statement or n statements enclosed within curly
Brackets. First the test condition is evaluated if the condition is true then the
statement inside the if block is executed otherwise statement outside the if block
is executed. Test condition is any valid C statement that include logical operator.
2.if-else statement
The if-else statement is used to express decisions. Formally the syntax is
if (expression)
statement1
else
statement2
where the else part is optional. The expression is evaluated; if it is true (that is, if expression
has a non-zero value), statement1 is executed. If it is false (expression is zero) and if there is an
else part, statement2 is executed instead.

Since an if tests the numeric value of an expression, certain coding shortcuts are possible. The
most obvious is writing
if (expression)
instead of
if (expression != 0)
Sometimes this is natural and clear; at other times it can be cryptic.

3.Else-If
The syntax is
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement

This sequence of if statements is


the most general way of writing a multi-way decision. The expressions are evaluated in order;
if an expression is true, the statement associated with it is executed, and this terminates the
whole chain. As always, the code for each statement is either a single statement, or a group of
them in braces.
The last else part handles the ``none of the above'' or default case where none of the other
conditions is satisfied. Sometimes there is no explicit action for the default; in that case the
trailing
else
statement
can be omitted, or it may be used for error checking to catch an ``impossible'' condition.

Switch
The switch statement is a multi-way decision that tests whether an expression matches one of
a number of constant integer values, and branches accordingly.
switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}

Each case is labeled by one or more integer-valued constants or constant expressions. If a case
matches the expression value, execution starts at that case. All case expressions must be
different. The case labeled default is executed if none of the other cases are satisfied. A
default is optional; if it isn't there and if none of the cases match, no action at all takes place.
Cases and the default clause can occur in any order.

The break statement causes an immediate exit from the switch. Because cases serve just as
labels, after the code for one case is done, execution falls through to the next unless you take
explicit action to escape. break and return are the most common ways to leave a switch.

Iterative statements
C language supports three types of iterative statements

• while loop
• do-while loop
• for loop

While loop

Statement x;
while(expression)
{
Statement block;
}
Statement y;

In the while loop, the condition is tested before the execution of any of the statement block is
executed. If the expression is evaluated to true (non-zero), only then the statements will executed
otherwise if the expression is evaluated to false (zero) the control jump to the statement next to the
while loop. The while loop will executed as long as the evaluated to non-zero (true). A while loop
is also called entry-condition loop as condition is tested at the start of the loop. If the expression
evaluates to false, then the statements enclosed in the loop will never be executed.

do-while loop

statement x;
do
{
Statement block;
} while (expression);
statement y;
In do-while loop the conditional expression is evaluated at the end of the loop. This means the
body of the loop is executed at least once even if the conditional expression is evaluated to false
(zero).
Like the while loop, the do-while loop continues to executed until the conditional expression is
evaluated to true (non-zero)

You might also like