Você está na página 1de 40

C Compiled Notes/I BSc CS

Programming

Evolution
ALGOL (Algorithmic Language) was the first computer language to
use block structure.
In 1967, Martin Richards developed a language called BCPL (Basic
Combined Programming Language) primarily for writing system
software.
In 1970, Ken Thompson created a language using many features of
BCPL and named it B.
C was evolved from ALGOL, BCPL and B. C was developed by
Dennis Ritchie at Bell Laboratories in1972.
C uses many concepts from these languages and added some new
features and emerged as a new language.
Most of the modern programming software and system software are
coded in C.
Characteristics of C Language
Well suited for structured modular programming.
Robust language with rich set of built-in functions and operators.
Has minimal instruction set and programs written in are efficient and fast.
Highly portable.
Highly flexible.
Allows access to the machine at bit level (Low level (Bitwise) programming).
Supports pointer implementation - extensive use of pointers for arrays,
structures, and functions.
Page 1 of 40

C Compiled Notes/I BSc CS

A program
It is a collection of declarations and functions.
It contains block structured statements.
Variables declared within a block are allocated on entry and terminated on exit.
Functions are blocks of codes defined for specific purpose inside the program
and can be called at the time of need.
Every C program begins with main() function and ends on exiting the main()
function.

Structure of a C Program
C program can be viewed as a group of building blocks called functions:
documentation section
preprocessor directives
global declaration section
main()
{
local declarations;
input statements;
processing statements;
output statements;
}
user-defined function definitions;

C Compilation Model
Preprocessor:
1. The Preprocessor accepts source code as input and interprets special
Page 2 of 40

C Compiled Notes/I BSc CS

preprocessor directives denoted by #.


2. It is also responsible for removing comments and empty programming
lines.
Compiler:
1. The compiler translates the preprocessed code to assembly code
(Machine understandable code)
Assembler:
1. The assembler creates the object code
(On UNIX, file with a.o suffix and on MS-DOS files with .obj indicates
object code files).

Link Editor:
1. Source file may contain references, library functions or functions
defined in other source files and it is the role of link editor to combine
these functions with main() to create an executable file.
2. External variable references are also resolved here.
C Fundamentals
Basic elements of C language constitutes:
1. Character set
2. Identifiers
3. Operators
4. Expressions
5. Statements

C program organization
1. Relies on standard library for input & output.
2. Relies on external standard library for assertion.
3. Preprocessor for handling directives in the program.

Data types
Data type defines the kind of information and it includes the byte strength
supported by the compiler and range of values that it can accept
Categories
Page 3 of 40

C Compiled Notes/I BSc CS

Primary
:User defined:Derived
:Empty
:-

predefined built-in
defined by user
derived from combination of primary data types
Ex: void

Primary data types:


Data type
Int
Char
Float
Double

Description
Integer quantity
Single character
Floating point members
Double precision floating
Point numbers

Memory
2 bytes
1 byte
4 byte
8 bytes

Range
-32,768 to 32,767
-128 to 127
3.4E-38 to 3.4E+38
1.73E-308 to
1.7E+308

Type qualifiers for primary data type:


short, long, signed, unsigned.
Short
Long
Signed
Unsigned

: regular memory allocation


: doubles the allocated memory and increases the range of use.
: the value can have negative values, a bit is used for representing the
sign of the value
: the value does not have any negative values. The sign bit is also
used for storing numbers.

Type Qualifier Size and Range


Data type

Memory in bytes

int
signed int
unsigned int
short int
signed short int
unsigned short int
long int
signed long int
unsigned long int

2
2
2
1
1
1
4
4
4

Range
-32,768 to 32,767
-32,768 to 32,767
0 to 65,535
-128 to 127
-128 to 127
0 to 225
-2,147,483,648 to 2,147,483,647
-2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
Page 4 of 40

C Compiled Notes/I BSc CS

Program elements
Tokens/alphabet,
Operators,
Comments,
Keywords,
Identifiers/ variables,
Literals/constants,
Statements
Tokens
It is the collection of characters that forms the basic vocabulary for compiler.
Alphabet
Lower case :- a,b,c,..,x,y,z.
Upper case :- A,B,C,.,X,Y,Z.
Digits
:- 0,1,2,3,4,5,6,7,8,9.
Special character:- (,),(),(),(),(),(.),(;).
Operators
Arithmetic :- (+),(-),(*),(/),(%).
Relational :- (<,>),(<=),(>=),(==),(!=).
Logical
:- &&, ||,!
Conditional :- ?:
Assignment :- =
Increment,decrement
:- ++,--,+=,-=,/=,%=,^=.
Boolean
:- <<,>>,/\,\/
Pointer
:- *,&,->,.
Parenthesis :- {,},(,),[,].
Comments
Comment lines are included in the program to give explanatory comments about
the program.
Comment lines have to be marked to separate them from program while compiling.
Page 5 of 40

C Compiled Notes/I BSc CS

1.Multi line comment


2.Single line comment

::-

/*comment*/
//comment (rest of the line)

Keywords
Explicitly reserved words that have strict predefined meaning in C.
EX- else, register, static, long, int, virtual, etc
Use of Keywords
Keywords are used for
Declarations
Statement syntax
Access control
Compiler directives
Identifiers /variables
It is a sequence of letters or digits or characters.
Used as identifier (label/name) for objects (variables), methods (functions), and
symbolic constant.
Identifier should Not begin with a digit.
Upper, lower case letters are distinct.
Can be v-long (principle).
(usually) 31 characters.
Example

:-

count, size, next_line, n5.

Literals/ constants
Constant values are
Literals can be of any native data type values.
Example

:- 5, 5u(unspecified), 5.0, \n, etc.

Types of variables (data types)


Integer

:-

5,8,57,64,.
Page 6 of 40

C Compiled Notes/I BSc CS

Unsigned
Long
Octal
Hexadecimal
Boolean
Floating point
(Double)Floating point
Floating point (Long)
Character
Alignment
Wchart
String

::::::::::::-

8u,76u,54u,.
4L,50L,
O8,O96,.
Ox8,Ox96,..
true,false.
5.0,8.96,
5.0F,60.4F,..
5.0L,60.4L,.
S,..
\n,
LXYZ,..
S,.

Character constants (printers)/carriage control


\a
\\
\b
\r
\
\f
\t
\n
\o
\
\v

alert
backslash
back space
carriage return
double quote
form feed
tab
new line
null character
single quote
vertical tab

Statements
1 Initialization
2 Input/output statements
3 Expression
4 Assignment statements
5 Control statements
6 Compound statement
7 Control structures
Input/output statements
Page 7 of 40

C Compiled Notes/I BSc CS

Input statements
scanf:
Syntax
example

scanf(control string,variable list);


scanf(%d,&x);

Output statements
printf:
Syntax
example

printf(control string,variable list);


printf(%d\nx);

Declaring & initializing


Declaration
Declaration is associated with a data type followed by variable name
Allocates required memory storage for the variable.
Initialization
Assigning a default / initial value for the variable.
Example
main()
{
int area;
int radius=5;

//declared,defined,but un initialized.
//declared,defined,initialised.

Expression
Combination of identifier, constant and their operations (represented by operator)
that can be evaluated to a single value.
Tolerant towards mixing types.
Allows widening conversions
Eg : int can be widened to double.
Allows explicit/implicit narrowing conversions(considered a bad programming
practice) Eg : float can be narrowed to int.
Page 8 of 40

C Compiled Notes/I BSc CS

Precedence rules describes how expressions are over loaded.


Type conversions
1 Type conversion is used for converting values of one type to another.
2 Type conversions are required when an expression consists of different data
types, which are also known as mixed expressions.
3 Conversions can be performed both implicitly & explicitly.
Implicit type conversion / automatic type conversion
1Any Boolean, short, enum types are promoted to integer type.
2 Any integral types that cannot be represented as integer type is promoted to
unsigned type.
3 In case of mixed expression the value of a lower type is promoted to the
higher type & expression is evaluated to higher type.Also called widening
conversion.Data is preserved during such conversion.
4 Conversions to a lower type occurs only if higher type is assigned to a
lower type, also called narrowing conversion.
5 Data is truncated to fit the lower type -> might result in data loss.
1.
6 For both widening & narrowing conversions. Variable / identifier
stored in
memory is not temporary copy of the variable is converted.
Explicit type conversions
1 Explicit type conversions refer to manual type conversions.
2 Explicit type conversions can be done by,
Using cast operators.
Including appropriate conversion functions.
Statements
1. Statement is an instruction for execution.
Page 9 of 40

C Compiled Notes/I BSc CS

2. A statement is always followed by a semicolon indicating the end of


statement.
Eg: - printf(GOD is great);
Assignment statement
1. An assignment expression followed by a semicolon.
Eg: - a=5;
2. Assignment operator assigns right to left.
3. Left should always be an identifier / variable.
4. Ivalue -> a memory location where a value can be stored or retrieved.
Ivalue -> variable, identifier.
Compound statement

1. A series of statements surrounded by the braces.


2. Grouping a set of statements into an executable unit.
3. Declarations are permitted within each set of compound statement.
All declarations within the compound statement are local to the
compound only.
Example
main()
{
int i=5;
printf(%d,i); //will print 5.
{
int i=0;
printf(%d,i); //will print 0.
}
printf(%d,i); //will print 5.
}
Page 10 of 40

C Compiled Notes/I BSc CS

Wherever a single statement cannot be placed, a compound / a program


structure can be placed.

Scope and Storage : Storage classes


Scope of an identifier is limited to the block in which it is declared.
Identifier becomes unknown outside the block.
Scope extends to inner blocks unless identifier is redefined in the inner
block.
Example
If a and b are declared in the outer block, Scope of a and b extends
to inner block.
If a is again redefined in inner block, old definition does not prevail in
inner block. And the new definition of a is limited to inner block
(Declaration in inner block option is available in c++ compilers).
Example
{
int a=5, b=7; //outer block
printf(%d %d,a,b);

//prints a=5, b=7;

{
int a=0; //inner block
printf(%d %d,a,b);

//prints a=0, b=7

}
printf(%d %d,a,b);

//outer block

//prints a=5, b=7

Scope

Scope is often referred as global or local


Global
Page 11 of 40

C Compiled Notes/I BSc CS

Scope extends to all blocks of the file


Global identifier is declared at the beginning of the file outside any
blocks.
Local
Declared inside a block.
Scope is limited within the block.
Basic Storage classes
Storage classes limit the scope, life and accessibility of variables across
the program and its functional blocks.
Types
1. auto (automatic).
2. extern (external)
3. register
4. static.
Storage class - automatic
auto
automatic.

: defines the storage of the declared variable as

Syntax : auto int x;


auto datatype variable;
Working
Declared within function body.
Scope is of the variable is limited to the block in which it is
declared.

Page 12 of 40

C Compiled Notes/I BSc CS

Variable/object is automatically destroyed on exiting the


block/scope area.
Data in the variable/identifier/object is lost upon destroyed.
Note:
This is the default declaration.
In the absence of any specific storage class, auto is assumed by
default.
Storage class - external
extern : defines the storage class as external.
Syntax : extern int x;
extern data type variable;
Working
Declaring a variable as extern makes the variable global.
Usually defined/declared outside any function block.
Extern indicates that declaration/definition of the variable can be in
the same file or other included files.
Variables are permanent.
Variables are never out of scope.
Note :
Scope extends to the current file and all included files and their
functions.
It cannot be automatically destroyed.
Storage Class - register:

Page 13 of 40

C Compiled Notes/I BSc CS

register : requests register memory for the variable.


Syntax : register int x;
register datatype variable;
Working

Requests for high speed memory for the associated variable.


If registers are unavailable for allocation, it is automatically converted
to auto.

Behavior and scope of register variables are like auto.

Very high speed memory (processor registers).

Note : Usually requested when frequent accessing or modification is done on


the variables(E.g. iterators, counters, flags).
Storage Class - Static
Static

: defines a memory location with static/permanent storage.

Syntax : static int x;


static datatype variable;
Working

Behavior is same as that of auto local variable.


Scope is limited to the block in which it is declared.

Unknown outside the block.

Initialized only once.

Page 14 of 40

C Compiled Notes/I BSc CS

Retains previous values on been testing the block.

Note : only static functions can access/modify static variables.


Example
{
int i=0;
while (i<10)
{
static int j=0; //initialize only once//
printf(%d,c); //prints0-9
j++;
}
}
Arrays

Need for an Array


Applications require the processing of multiple data items that have common
characteristics (for example, set of numbers,set of names):
Ex:
To sort a given set of numbers
Matrix manipulation
Definition:
A data structure which can hold the homogeneous data items is called an Array.
Array is a derived datatype which is used to store similar data items in
contiguous memory locations under a single name.
It holds a fixed number of equally sized data elements, generally of the same
data type.
The individual elements are accessed by specifying the subscript.
Memory organization of an Array
Page 15 of 40

C Compiled Notes/I BSc CS

The elements in the array are always stored in consecutive memory locations.
An array of 5 integer elements, occupies 10 contiguous bytes in memory.

Starting address is assumed to be 1000 and totally 10 bytes are allocated.


Address of I th location = base address +(size of the individual data element *
index i)

1st element
2nd element
1000
1002
Array Declaration:

3rd element
1004

4th element
1006

5th element
1008

Arrays are declared with appropriate data type and size. Array declaration
reserves space in memory.
Syntax:
datatype array_name[size];
EX:
int x[5];
Defines an integer array x of 5 integers starting at x[0], and ending at x[4].
char str[16]="qwerty";
Defines a character array which is used to represent a string of maximum of 16
characters.
float sales_amt[10];
Defines an floating point array sales_amt of 10 floating point numbers
starting at sales_amt[0]
and ending at sales_amt[9]
Accessing array elements
The array elements are accessed by specifying the subscript / index
Syntax:
array_name[index or subscript];
Page 16 of 40

C Compiled Notes/I BSc CS

Examples:
x[0]-> to access the 1st element in array
x[4]-> to access the 5th element in array
str[2]-> to access the 3rd character in a string
sales_amt[8]-> to access the 9th sales amount
Array initialization
Array elements can be initialized during declaration or can be initialized in the
program statements.
In partial initialization, the uninitialized array elements are initialized to zero or
NULL
Syntax:
datatype arrayname[size] = {value(s)};
OR
datatype arrayname[ ] = {value(s)};
Example
1.int a[5]={1,2,3,4,5};
/*a[0]=1, a[1]=2, a[2]=3, a[3]=4 and a[4]=5*/
2.int a[5]={0};
/*all the array elements are initialized to zero*/
3.int a[5]={1,2,3,4}; /*a[4] = 0*/
int a[ ] = {1,2,3,4};
/*a[0]=1, a[1]=2, a[2]=3, a[3]=4*/ If not specified size depends upon the
number of
values initialized.
4.float b[2]={10.2,45.34};
/*b[0] = 10.20, b[1] = 45.34*/

To initialize the array to zero automatically, the keyword static can be used
during initialization.
static int a[10];
/*all the array elements are initialized to zero automatically*/
Page 17 of 40

C Compiled Notes/I BSc CS

2.The static keyword is used to retain the value of array between function calls.
When static,
arrayinitial()
{
static int a[3];
a[0]+=10;
a[1]+=11;
a[2]+=5;
}
1. During the first call to the function:
Initial: a[0]=a[1]=a[2]=0
Final: a[0]=10 a[1]=11 a[2]=5
2.During the second call to the function:
Initial: a[0]=10 a[1]=11 a[2]=5
Final: a[0]=20 a[1]=22 a[2]=10
Basic operation of an array
1.Basic operation allowed on arrays are storing, retrieving, processing array
elements, and deleting array elements.
2.Inserting an element to an array is not directly possible.
3.Once an array element is deleted, the value in that location will be undefined
or garbage
Array is a constant pointer, so following expressions are illegal:
1.a++: Base address of array a is modified by adding one.
2.a+=2: Base address of array a is modified by adding two.
Getting the value for arrays
Examples:
int a[3];
scanf(%d, &a[0]);
/*get the value for 1st location*/
scanf(%d%d%d, a, a+1, a+2);
/*get the value for first 3 locations
(array name has the base address)*/
for(i=0;i<3;i++)
Page 18 of 40

C Compiled Notes/I BSc CS

scanf(%d,&a[i]);
Printing out of the arrays elements
Examples:
int a[3];
printf(%d, a[0]);
/*prints value of 1st location*/
printf(%d%d%d,a[0],a[1],a[2]);
/*prints value of first 3 locations*/
for(i=0;i<3;i++)
printf(%d,a[i]);
Multidimensional arrays
The elements of an array can themselves be arrays.
Multidimensional arrays will also occupy the contiguous memory locations.
Array elements are usually stored in row major order.
Two-Multidimensional array(Declaration)
Syntax:
datatype arrayname [row ][column]
Example:
int a[2][2];
/*creates 8 bytes of contiguous memory locations. (2*2 = 4
elements).*/
Assume that array starts at location 1000:
1.a[0][0] will be in 1000 (row 0 and column 0)
2.a[0][1] will be in 1002 (row 0 and column 1)
3.a[1][0] will be in 1006 (row 1 and column 0)
4.a[1][1] will be in 1008 (row 1 and column 1)
Two-Multidimensional array: Initialization
Multidimensional arrays can also be initialized in the declaration statement.
Examples:
int num[2][3] = {1,2,3,4,5,6};
int num[2][3] = {1,2,3,4,5};
Page 19 of 40

C Compiled Notes/I BSc CS

/*num[1][2] = 0*/
int num[2][3] = {{1,2,3},{1,2,3}};
/*row elements are initialized separately*/
int num[2][3] = {{1,2},{4}};
/*num[0][2] = 0, num[1][1]=num[1][2]=0*/
Advantages:
1.Simple and easy to use
2.Stored in contiguous locations
3.Fast retrieval because of its indexed nature
4.No need for the user to worry about the allocation and de-allocation of
arrays
Limitations:
1.If m elements out of n locations defined, n-m locations are
unnecessarily wasted
2.No automatic array bounds checking during compilation
Strings
Strings are sequence of characters.
A character string is stored in an array of character type, one ASCII character
per location.
String should always have a NULL character (\0) at the end.
Ex:
char c[4]={s,u,m,\0);
/*c[0] = s, c[1] = u, c[2] = m, c[3] = \0*/
char str[16]="qwerty";
Creates a string. The value at str[5] is the character y.
The value at str[6] is NULL.
The values from str[7] to str[15] are undefined.
char name[5] = INDIA
Strings are terminated by the null character, one extra storage location in an
array is required.
Array of string Declaration
Two dimensional character arrays are used to represent array of strings.
Page 20 of 40

C Compiled Notes/I BSc CS

Syntax:
char arrayname [no. of strings]
[max no. of chars in strings];
Example:
char studname[50][15];
50 student names each with 15 characters at the maximum.
Arrays of strings: initialization
Syntax:
char arrayname[r][c]={values};
Example:
char name[3][5] = {bata,cat,at}
char name[3][5] ={{b,a,t,a,\0},{c,a,t,\0},{a,t,\0}}
Reading a string
String can be read either by character-bycharacter or as an entire string
(using %s)
Example:
1. char name[20];
int i=0;
while((name[i]=getchar()) != \n)
i++;
scanf( %s , name);
ILLEGAL OPERATIONS ON A STRING:
1. Assigning a string to another string variable using = operator.
2.Comparing two strings using == operator.
3.Concatenating two strings using + operator.
Structures and union
Structures and unions help to store heterogeneous data items in one data
arrangement.
Structures and Unions are the main constructs available in C through which
Page 21 of 40

C Compiled Notes/I BSc CS

new data type can be defined.


Structures and unions provide a way to group logically related data items
together.
The structure is a derived data type used to represent heterogeneous data.

A structure is an aggregation of components that can be treated as a single


variable.The components are called members.
For example, an employee is represented with the following attributes:

employee code (alphanumeric)


employee name (string)
department code (integer)
salary (float)

Structure Declaration
Structures are defined via a template and declared with a tag which helps to
avoid repeating the definition.
struct keyword is used to define structures.
Syntax:
struct tag_name
{
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
::
type variable-name, variable-name,........;
};
Structure-variables can be declared anywhere in the program.
Syntax to define structure variables:
struct tag_name new-structure-variable;
Example:
struct employee
Page 22 of 40

C Compiled Notes/I BSc CS

{
int code;
char name[20];
int dept_code;
float salary;
};
struct employee emp1, emp2;
Structure definition and declaration of structure variables can be combined
together.
Example:
struct employee
{
int code;
char name[20];
int dept_code;
float salary;
} emp1, emp2;
Note: Tag name is optional in this case.
Structure Initialization
Structure variables can be initialized at the time of declaration.
If the structure variable is declared before the main function, the member
variables are automatically initialized to zero or Null.
If it is partially initialized, then uninitialized members will be assigned zero or
Null character
.
Example:
struct stud
{
int rollnum;
char name[20];
int semester;
float avg;
};
Page 23 of 40

C Compiled Notes/I BSc CS

struct stud stud1={101,Dina, 1, 90.78},


stud2={102,Raja, 1};
2424242424242424242424242424242424242424242424
F24o24r24 24t24h24e24 24s24t24r24u24c24t24u24r24e24
24v24a24r24i24a24b24l24e24
24s24t24u24d242
t24h24e24 a24vg 24w24i24l24l24 24b24e24
24i24n24i24t24i24a24l24i24z24e24d24 24t24o24 24024.24024
24
24A24C24C24E24S24S24I24N24G24 24T24H24E24
24M24E24M24B24E24R24S24:24
24
M24e24m24b24e24r24s24 24o24f24 24t24h24e24
24s24t24r24u24c24t24u24r24e24 24c24a24n24 24b24e24
24a24c24c24e24s24s24e24d24 24b24y24 24u24s24i24n24g24 24t24h24e24
24m24e24m24b24e24r24 24a24c24c24e24s24s24 24o24p24e24r24a24t24o24r24
24.24(24d24o24t24)24.24
24 24 24S24y24n24t24a24x24:24
24 24 24

24s24t24r24u24c24t24_24v24a24r24i24a24b24l24e24.24m24e24m24b24e24r
24-24f24i24e24l24d24-24n24a24m24e24
24 24 24E24x24a24m24p24l24e24:24
24 24 24 24e24m24p24124.24c24o24d24e
emp1.name
emp1.dept_code
emp1.salary
emp2.code
emp2.name
Operations on structure:

1.Each member of a structure can be assigned to the corresponding member of


another structure.
2.Structure can also be assigned to another Structure provided they have the
same composition.
3.sizeof() operator can be used to find the size of the structure.
Note:
Page 24 of 40

C Compiled Notes/I BSc CS

Two structure variables cannot be compared for equality, even though the values
store In the member variables are the same. This is because slack bytes are added
in between two member variables and these slack bytes have some garbage value.
Nested structures
Structures can contain members that themselves are structures.
struct date
{
int day;
int month;
int year;
};
struct employee
{
int code;
char name [20];
struct date doj ;
int dept_code;
float salary;
}emp1,emp2;
Structures and arrays
The members of structures can be arrays and the structure can also be an array
Example:
struct stud
{
int rollnum;
char name[20];
int semester;
int avg;
};
struct stud student[50];

Accessing values:
student[1].rollnum, student[1].name,
Page 25 of 40

C Compiled Notes/I BSc CS

student[1].semester, student[1].avg
Arrays within structure:
Example:
struct student-mark
{
int rollnumber;
char name[15];
int sub_marks[5];
} student;
Accessing values:
student.sub_marks[0],
student.sub_mark[1], student.name
UNIONS
1.Union, like a structure, is a derived data type
2.Unions follow the same syntax as structures but the only difference is that
members of the union share storage.
3.Union differs from structure only in storage and in initialization.
DECLARATION
Syntax:
union tag_name
{
type variable-name, variable-name,........;
type variable-name, variable-name,........;
type variable-name, variable-name,........;
::
type variable-name, variable-name,........;
}union-variable1, union-variable2...... ;
UNION INITIALIZATION
Union can be initialized only with a value for the first union member. All other
member can not be initialized.
Example:
union item
Page 26 of 40

C Compiled Notes/I BSc CS

{
int m;
float x;
char c;
};
union item product = {100};
100 will be assigned to union member variable m.

UNIONS OF STRUCTURES
The members of structures and unions can include other structures and unions.
Example:
struct employee_type
{
int code;
char name[20];
int dept_code;
float salary;
};
struct stud_type
{
int rollno;
char name[15];
int age;
float avg;
};
union person
{
char surname[10];
struct employee_type e1;
struct stud_type s1;
}ex;

ENUMERATION
Enumeration is a derived data type, similar to structures or a union.

Page 27 of 40

C Compiled Notes/I BSc CS

Its members are constants that are written as identifiers, though they have signed
integer values.
These constants represent values that can be assigned to corresponding
enumeration variables.
enum keyword is used to declare enumerated variables.

Syntax:
enum tag {member1,member2,member n};
tag is a name that identifies enumerations.
Members represent the identifiers
Enumerated variables can be declared as follows:
storage-class enum tag var1,var2,varn;
Example:
enum escapes {bell=`\a', backspace=`\b', tab=`\t, newline=`\n', vtab=`\v',
return=`\r'}
main()
{
enum escapes e1;
e1 = getch();
if (e1 == newline)
printf("newline");
}
typedef
The typedef allows users to define new data types that are equivalent to existing
data types.
It gives new names to existing data types.
Syntax:
typedef datatype new-type;
Example:
typedef int numbers;
Page 28 of 40

C Compiled Notes/I BSc CS

Here, numbers is the new name given to integer data type and it can be used to
declare integer variables.
Example:
numbers n1, n2;
Example:
typedef struct
{
int empno;
char empname[10];
}employee;
employee emp1, emp2;
Note:
No need to use struct keyword when declaring structure variables.
Control structures
1. Linear structure: Executes in a sequential fashion where the next line will
be followed as the previous line is completed.
2.Decision Making /Branching/selection structures:Execute the portion of
statements that are found true on decision
simple if
if & if else structures
nested- if
ladder if
switch - case structure
goto statement
break statement
continue statement
3.Looping/iterative/cyclic structures:Repeated execution of set of statements
(from a starting point to ending point / as long as the condition is true/until
the condition becomes false)
while structure
do structure
for-loop structure
Page 29 of 40

C Compiled Notes/I BSc CS

Simple if
The general form is
if(condition)
statement;
Working
If the condition results in true then the following / subsequent statement is
executed.
If the condition results in false then the following / subsequent statement is not
executed.
Condition can be,
Boolean value(i.e., true or false).
Boolean expression.
Expression with logical / relational operators resulting in Boolean values.
Any integer / float value are implicitly converted to Boolean values.
Example
if(temperature<0)
printf(warning:Extreme chillness observed as the temperature is below 0);

if else structure
General form is
if(condition);
statement1;
else
Page 30 of 40

C Compiled Notes/I BSc CS

statement2;
statement3;

//this statement is not a part of structure.

Working

If condition is true, statement1 (if statement) is executed before executing


statement3. Statement2 is not executed.
If condition is false statement2 (the else statement) is executed before
executing statement3. Statement1 is not executed.
Example
1.

if(mark<50)
printf(fail); // will o/p if condition is true.
else
printf(pass); //will o/p if condition is false.
printf(result);

if(balance) //true if balance>0, false if balance==0


printf( balance Exists);
Note: integer value balance is converted to boolean.
Nested- if
General form
if(condition1)
{
if(condition2)
statement1;
else
statement2;
}
Page 31 of 40

C Compiled Notes/I BSc CS

else
{
if(condition3)
statement3;
else
statement4;
}
Working

Condition1 is evaluated first, if true the if-else structure of if compound


statement is processed.
If condition2 is true statement1 is executed and if false, the statement2 is
executed.
If condition1 is false, the if-else structure of else compound statement is
processed.
If condition3 is true, statement3 is executed & if false statement 4 is
executed.
Nesting of if-else structures is permitted.
Each structure should not overlap with other structures or parent structure.
Ladder if
Multiple nesting of simple if structure is known as ladder if.
Example:-

1.

if(gender==boy)
{
if(marks=>50)
printf(boy passed);
else
Page 32 of 40

C Compiled Notes/I BSc CS

printf(boy failed);
}
else
{
if(marks=>50)
printf(girl passed);
else
printf(girl failed);
}
2.

if(subject1=>50)
{
if(subject2=>50)
{
if(subject3=>50)
{
if(subject4=>50)
{
if(subject5=>50)
printf(pass);
}
}
}
}

Switch - case structure


The general form is
switch (expression)
{
case value 1: statement1/{set of statements};
case value2: statement2;
.
.
.
.
case value n: statement n;
default: statement x;
Page 33 of 40

C Compiled Notes/I BSc CS

}
Working
First the expression is evaluated.
The expression value is matched with the values specified in the case area of
switch structure.
If the matching value is found, the respective statement is executed.
If no match is found then default statement is executed.
Control exits the structure & next statement outside the structure is executed.
Note:
A break statement is required at the end of each statement or compound
statement in the switch structure.
The break statement enables the control to exit the structure after executing
the respective statement.
In the absence of break statement all statements following the selected
statement inside the structure are executed before exiting.
In the absence of default case statement, no match for value is found and
none of the statements in switch case structure are executed.
Conditions cannot be used in the value option of the switch case structure.
The closing braces of switch case should not be followed by a semicolon.

Example:

scanf(%d,salary_grade);
switch(salary_grade)
{
Page 34 of 40

C Compiled Notes/I BSc CS

case 1: salary=3,000;
printf(%d,salary);
break;
case 2: salary=8,000;
printf(%d,salary);
break;
case 3: salary=15,000;
printf(%d,salary);
break;
default:
printf(invalid grade);
break;
}

goto statement
goto statement is the most primitive form of branching.
The branching statement is an unconditional branching to a labeled
statement.
General form:
goto label;
label:
statement;
Working
The control is immediately transferred to the statement at the label.
Note
This statement is to used with extreme caution, so that it does not disturb any
structures.
Preferably donot use this statement.
Example:int i=10;
Page 35 of 40

C Compiled Notes/I BSc CS

goto next;
i++;
printf(%d,i);
next: printf(we have skipped the o/p);
break statement:
General form
break;
Working
Break statement will face the control out of the program structure (current
structure).
Eg -> loop structures, if-else, switch.
Note: Will force total exit out of current structure.
Example:
i=0;
do
{
printf(%d,i);
i++;
}while(i>0); //will form a continuous loop
i=0;
do
{
printf(%d,i);
i++;
if(i>100) break;
}while(i>0); //will print from 0-100.
continue statement:
General form:
Page 36 of 40

C Compiled Notes/I BSc CS

continue;
Working
Continue statement will force the control out of current loop only.
Control will continue with next loop.
Note:
Used in looping structures.
Will not forcecomplete exit.
Loop will continue with next iteration.
Example
i=0;
do
{
if(i%2) continue;
printf(%d,i);
i++;
if(i>100) break;
}while(i>0); //will print even numbers from 0-100
Looping structures
While structures
The general form of a while statement is
while(condition)
Statement;
Working
The condition is evaluated.
Page 37 of 40

C Compiled Notes/I BSc CS

If the condition is true the statement is executed.


The above steps will be repeatedly executed until the condition is false.
Note:
An expression can be used instead of condition, holds true if exp>0.
Compound statement / statement block can be used instead of single
statement.
Must take care to see that loop does not continue indefinitely.
No semicolon after while or end of structure.
Example
i=0;
while(i<10)
{
printf(%d,i);
i++;
}
do structure
The general form is
do
Statement;
while(condition);
Working
The statement is executed.
Condition is evaluated.
If condition is true, statement is executed again.
Page 38 of 40

C Compiled Notes/I BSc CS

It will be repeated until condition is false.


Note:
Expression can be used instead of condition, true if exp>0.
Compound statements can be used instead of single statement.
Must take care to see that loop is not infinite.
A semicolon must follow at the end of while condition.
Will ensure statement is executed at least once.
Example
i=0;
do
{
printf(%d,i);
i++;
}while(i<100);
for-Loop Structure
General form is
for(initialization;condition;increment)
Statement;
Working
Initialization statement is executed (initializing iterator variable / identifier)
Condition is checked.
If true, statement is executed.
Increment statement is executed (incrementing iterator).
Steps 2,3,4 are continuously repeated until condition fails.
Note:
Page 39 of 40

C Compiled Notes/I BSc CS

Not as flexible as while, do-while statements.


Simple & easy to use.
Forces programmer to set the initialization & increments for condition
iterators.
Measures to be taken to prevent from endless loops.
Semicolon doesnt follow the for().
Example:for(i=0;i<10;i++)
{
printf(%d,i);
}

Page 40 of 40

Você também pode gostar