03 Basic of C

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 99

Basics of C Language

Pandit Deendayal Petroleum University


Gandhinagar
HISTORY OF C
• Developed by Dennis Ritchie at AT&T’s BELL
LABS in 1972.
• In 1983, ANSI set up a committee to establish
a standard specification of C.
• The committee released the standard
specification in 1989, known as C89.
• ISO adopted it and came out with new
release in 1999.
• This standard was adopted as ANSI
standard.
USE OF C
• OPERATING SYSTEMS
• EDITORS
• COMPILER CONSTRUCTION
• INTERPRETERS
• ASSEMBLERS
• DBMS/RDBMS
• APPLICATION SOFTWARE
• GENERAL-PURPOSE SOFTWARE
USE OF C
• DEVELOPING GAMES
• COMMUNICATION PROTOCOLS
• DEVICE DRIVER PROGRAMMING
• PROGRAMS FOR MOBILE DEVICES
• ROBOTICS
STEPS FOR WRITING A
PROGRAM
C CHARACTER SET
• ALPHABETS : A … Z , a … z
• DIGITS :0…9
• SPECIAL
SYMBOLS : ~ ` ! @ # %
^ & * ( )_ - + =
| \ {}[] :
; “ ‘ < > , . ? /
C CHARACTER SET
• ALPHABETS : A … Z , a … z
• DIGITS :0…9
• SPECIAL
SYMBOLS : ~ ` ! @ # %
^ & * ( )_ - + =
| \ {}[] :
; “ ‘ < > , . ? /
VARIABLES/CONSTANTS
• VARIABLE:
Whose value can be changed.
• CONSTANT:
That never changes.

A Variable B
100 Constant ‘i’
TYPES OF CONSTANTS
CONSTANTS

PRIMARY SECONDARY
CONSTANTS CONSTANTS

Integer Constant Array, Pointer


Real Constant Structure,
Character Constant Union, Enum
RULES: INTEGER CONSTANTS
• It must have at least one digit.
• It must not have a decimal point.
• It can be +ve or –ve.
• If no sign precedes, it is assumed
to be positive.
• No commas or blanks are allowed
within it.
RULES: INTEGER CONSTANTS
• Range:
16-bit Compiler: -32768 to +32767
32-bit Compiler:
-2147483648 to +2147483647
• Examples:
1802 +1972 -4000 -32500
RULES: REAL CONSTANTS
• It must have at least one digit.
• It must have a decimal point.
• It can be + ve or – ve.
• If no sign precedes, it is assumed
to be positive.
• No commas or blanks are allowed
within it.
• EXAMPLES: +9.02 -19.72
RULES: CHARACTER
CONSTANTS
• Any alphabet, any digit or a special
symbol enclosed within single inverted
commas is known as character
constant.
e.g. 'a''7''+’
• The maximum length of a character
constant can be 1 character.
• Internally, it uses ASCII to store a
character.
DATA TYPES
DATA TYPE RANGE SIZE FORMAT
(BYTES)
signed char -128 to +127 1 %c
unsigned char 0 to 255 1 %c
short signed -32768 to 2 %d
int +32767
short unsigned 0 to 65535 2 %u
int
signed int -32768 to 2/4 (32-bit %d
+32767/-231 to Compiler)
+231-1
DATA TYPES
DATA RANGE SIZE FORMAT
TYPE (BYTES)
unsigned int 0 to 65535/ 2/4 (32-bit %u
0 to 232-1 Compiler)
long signed -2147483648 4 %ld
int to 2147483647
long 0 to 4 %lu
unsigned int 4294967295
float -3.4e38 to 4 %f
+3.4e38
double -1.7e308 to 8 %lf
+1.7e308
DATA TYPES
DATA RANGE SIZE FORMAT
TYPE (BYTES)
long double -1.7e4932 to 10 %Lf
+1.7e4932
The size and ranges of int, short and long are compiler
dependent. Sizes in this figure are for 16-bit compiler.
RULES: VARIABLE NAMES
• A variable name is any combination of
alphabets, digits or underscores (Max 31).
• The first character in the variable name
must be an alphabet or underscore.
• No commas or blanks are allowed within
a variable name.
• No special symbol other than an
underscore ( as in tot_marks) can be
used.
RULES: VARIABLE NAMES
• No Reserve Words (Keywords) are
allowed as the name of variables.
• e.g. a A b c hr min name1
gross_salary
• a and A are different variables.
( Case sensitive )
• These rules remain same for all types
of primary and secondary variables.
KEYWORDS
• Keywords are those words whose
meaning has been explained to the C
compiler.
• Also known as "Reserved Words".
• Cannot be used as the name of
variable.
LIST OF KEYWORDS
auto break case char
const continue default do
double else enum extern
float for goto if
int long register return
short signed sizeof static
struct switch typedef union
unsigned void volatile while
RULES: C PROGRAM
• Each instruction is written as a separate
statement. Series of Instructions will
make a program.
• Statement in a program must appear in
the same order in which we wish them to
be executed.
• Blank spaces may be inserted between
two words to improve the readability.
• It is a free form language.
– e.g. c = a+ b; printf ( "%d\n" , c);
RULES: C/C++ PROGRAM
• All statements are written in small case
letters.
• Every statement must end with a ; (Semi-
colon). Thus, ; acts as a statement
terminator.
Program to Add Two Numbers
Algorithm #include <stdio.h> // header
file
void main( ) // function
{ /* Program to add 2 Nos. */
int a, b, c;
INPUT A, B printf( " Enter 2 Nos. ");
C=A+B scanf ("%d %d",&a,&b); //
PRINT C input
c = a + b; // add 2 nos.
C Program
Program to Add Two Numbers
Algorithm #include <stdio.h> // header file
#include <conio.h> // header file
void main( ) // function
{ /* Program to add 2 Nos. */
int a, b, c;
clrscr();
printf( " Enter 2 Nos. ");
INPUT A, B scanf ("%d %d",&a,&b); // input
C=A+B c = a + b; // add 2 nos.
printf("%d + %d = %d\n", a,b,c);
PRINT C getch();
} C Program
Header Files
• Preprocessor adds the contents of the
"stdio.h" header file to the program.
• It contains declarations for the functions
called printf ( ) , scanf ( ), etc.
• Header files are included at the beginning
of all programs.
• For using different functions, we need to
include different header files.
Header Files
• stdio.h • math.h
– printf ( ) – abs ( )
– scanf ( ) – pow ( )
• conio.h – sin ( )
– clrscr ( ) – tan ( )
– getch ( ) – sqrt ( )
– getche ( ) • Find out other
names of header
files.
FUNCTION
• Function is a self-contained block of
statements that perform a coherent task of
some kind.
• Every C/C++ program is collection of
these functions.
void main ( )
{

}
FUNCTION

function name

void main ( )
{

}
FUNCTION

Return type

void main ( )
{

}
FUNCTION

void main ( arguments, if any )


{

}
FUNCTION

void main ( )
{
statement(s);
}
FUNCTION

Return type function name

void main ( arguments, if any )


{
statement(s);
}
printf() function
• Displays output on monitor.
• prototype available in stdio.h header file.
• general form
– printf(“format string”, list of variables or
constants or expression);
– format string data types
– Format string can contain other characters
also. They will be printed as they are.
printf() function
Examples
• printf(“%f”, 3.1415); // constant
• printf(“3.1415”);
– output : 3.1415
• printf(“%d %d %d”, p , r , n); // variable(s)
– output : 10000 10 3
• printf(“area = %.2f sqr.mtr \n” , area);
– output : area = 25.00 sqr.mtr
• cursor will be in next line because of \n.

data types
printf() function
More Examples
• printf(“simple interest = %.2f”, p*r*n/100);
// expression
– output : simple interest = 3000.00
• Use of ESCAPE SEQUENCE is allowed in
format string.
in C++, we use cout object instead of printf()
function.

data types
scanf() function
• used to receive input from the user.
• prototype available in stdio.h header file.
• similar to cin object in C++.
• general form
– scanf (“format string”, list of addresses of
variables);
– e.g. scanf( “%d %f %c”, &i, &pi, &ch);
• ‘&’ is address of operator.

data types
scanf() function
• When you enter the data via keyboard,
they must be separated by either blank(s),
tab(s) or newline(s) characters.

• Try out this in the lab.


– scanf(“%d:%d:%d”,&hh, &mm, &ss);
• hh, mm, ss are int variable.
ESCAPE SEQUENCE
• \n New Line : cursor in the next line.
• \r carriage return : cursor at the 1st
position in current line.
• \b Backspace : moves cursor 1
position to the left from
its current pos.
• \f Form Feed : used on printer to
move to next page.
ESCAPE SEQUENCE
• \t Tab : moves to next tab stop
• \’ Single quote: displays single quote
• \” Double Quote : displays double quote
• \\ Backslash : displays backslash
• \a Alert : output on speaker.
(ascii value : 7)
FUNCTION PROTOTYPE
• It is a declaration that defines:
– the return type &
– The parameters of a function (arguments) &
– Type of order of the arguments.
• e.g.
– void add (void);
– void add ( int , int );
– float add (void);
– float add ( float, float );
FUNCTION PROTOTYPE
• Each declaration clearly specifies:
– the number of arguments
– the order of arguments
– type of arguments
– The type of value that each function would
return.
FUNCTION PROTOTYPE
• Compiler uses the prototype to crosscheck
the above details when you call any
function. ( also known as STRONG TYPE
CHECKING)
WHY FUNCTION?
• We can write the whole logic in main()
function itself. Then why to write separate
Function?
– Writing functions avoids rewriting the same
code over and again. (Reusability)
– Top-Down Approach can be adapted.
– Program development becomes very easy.
WHY FUNCTION?
– Divide the operation of a single program into
separate activities.
– Put each activity in a different function.
– Writing and Checking of individual function
becomes more easy.
– To maintain secrecy of code.
Types of Functions

• Two Types of Functions:


• Built-in Functions:
• User-defined Functions

Built-In Functions User-Defined


Functions
Prototype Declaration Already done We have to declare
Function Definition Already provided in We have to define
library, not visible to us
Function Calling We have to call We have to call
Examples sin(), cos(), pow(), add(), subtract(), prime(),
clrscr(), getch(),… perfect(),…
Various forms of Functions
• Function with No Return Value and no
arguments.
– void add ( void );
• Functions with arguments but no return value.
– void add ( int , int );
• Functions with return value but having no
arguments.
– int add (void);
• Functions with return value and with arguments.
– float add ( float , float );
Functions
No Arguments/No Return Value
void add(void)
#include <stdio.h>
{#include <conio.h>
void
int main()
a, b, c;
{ printf(“\nEnter 2 Nos.”);
scanf(“%d
// function%d”,
prototype
&a, &b);
declaration.
cvoid
= a add(void);
+ b;
clrscr();
printf(“Answer = %d”, c);
} add(); // calling function.
getch();
}
Functions
With Arguments/No Return Value

#include
add (a<stdio.h>
, b);
#include
getch(); <conio.h>
}void main()
{
void
int add(
a, b; int x, int y)
{ void add( int , int );
clrscr();
int z;
zprintf(“\nEnter
= x + y; 2 Nos.”);
scanf(“%d %d”,&a,&b);
printf(“Answer = %d”, z);
}
How memory looks like?
function main() a b

10 20

function add() x y z

10 20 30
Functions
No Arguments/With Return Value
float add(void)
#include <stdio.h>
{#include <conio.h>
void main()
float x, y, z;
{ printf(“\nEnter 2 Nos.”);
float c;
scanf(“%f %f”, &x, &y);
float
z = x add(void);
+ y;
clrscr();
return z;
} c = add();
printf(“Answer = %f”,c);
getch();
}
How memory looks like?
function main() c

30

function add() x y z

10 20 30
Functions
With Arguments & Return Value

#include
c = add <stdio.h>
(a, b);
#include
printf(“Answer
<conio.h> = %f”,c);
voidgetch();
main()
}{
float a, b, c;
float
float
add(addfloat
(float,
x, float
float);y)
{ clrscr();
printf(“\nEnter
return (x+y); 2 Nos.”);
} scanf(“%f %f”, &a , &b);
How memory looks like?
function main() a b c

10 20 30

function add() x y

10 20
WHEN TO USE WHICH
FUNCTION
INPUT PROCESS OUTPUT
VOID FN FN FN
FN(VOID)

VOID MAIN FN FN
FN(INT)

INT FN FN MAIN
FN(VOID)

INT MAIN FN MAIN


FN(INT)
CONTROL STRUCTURES
• SEQUENCE STRUCTURE
• SELECTION STRUCTURE
• LOOP STRUCTURE
SEQUENCE STRUCTURE
entry
Action 1

Action 2

Action 3
exit
SELECTION STRUCTURE
entry
true false
condition

Action 1 Action 2

exit
Action 3
SELECTION STRUCTURE
• if-else
• switch
if-else (various forms)
1) if (condition) e.g. if ( a > 5)
statement; printf(“%d”, a);

2) if (condition) e.g. if ( x > y )


{ {
statement(s); printf(“%d”,x);
}; printf(“%d”,y);
}
• Condition is evaluated in terms of zero and
non-zero.
• Non-zero means true and zero means false.
if-else (various forms)
3) if (condition)
{
statement(s)1;
} // no semicolon over here.
else
{
statement(s)2;
}; // semicolon at the end only.
if-else (various forms)
4) if (condition1) e.g. if ( avg >= 70)
{ statement(s)1; } printf(“Dist.”);
else else
if (condition2) if ( avg >= 60)
{ statement(s)2; } printf(“1st”);
else else
{ statement(s)3; }; printf(“oth”);
if-else (various forms)
5) if (c1) C1 C2 ACTION
{
if (c2) T T S1
{ s1; } T F S2
else F - S3
{ s2; };
} T means (Non-zero)
else F means (zero)
{ s3; };
Relational Operators
• == Equality operator.
– (do not use =, as = is assignment operator.)
• > Greater than
• < Less than
• >= Greater than or Equal to
• <= Less than or Equal to
• != Not equal to
Logical Operators
• You can join two conditions within one
condition with the help of logical operators.
• && and (Binary Operator)
• || or (Binary Operator)
• ! Not (Unary Operator)

• Binary Operator requires 2 operands.


• Unary Operator requires only 1 operand.
Logical Operators
• Examples:
(1) if ( (a>b) && (a > c) )
printf(“%d is largest.”, a);
(2) if ( (p < 35) || (c < 35) || (m < 35))
printf(“You are fail.”);
(3) if (! flag) // if (flag == 0)
printf(“You can’t go ahead.”);
Short Circuit
• || and && have a feature of short circuiting an
expression.

• ||
– if the first expression evaluates to true, the following
expression is not evaluated.
• &&
– if the first expression evaluates to false, the following
expression is not evaluated.
Examples of Short Circuit
int a, b, c;
a = 4; b = 10; c = 30;
if ( ( a < b ) || ( a < c ) )
/* (4<10)||(4<30) */
...
if ( ( a > b ) && ( a > c ) )
/* (4>10)&&(4>30) */
The Conditional Operators
• Turnery Operator: ( ) ? :
• ((Expression1) ? Expression2 : expression3);

• y = (( x > 5) ? 3 : 4);
means if x > 5, y = 3 otherwise y = 4

• int big, a, b, c;
• big = ((a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) );
Increment/Decrement Operators
• Unary
• ++ increment
• -- decrement
• Each has two flavours, pre and post
• Applies to integer and char data-types only
Pre Increment
• Value of variable is incremented and then
used in expression.
• Syntax

++variableName
Example
int a, c;
a = 10;

/* increment first, then take value */


c = ++a;
i.e. a = a + 1; c = a;

/* a is 11 */
/* c is 11 */
Post Increment
• Value of variable is used in expression and
later incremented.
• Syntax

variableName++
Example
int a, c;
a = 10;

/* take value first, then increment */


c = a++;
i.e. c = a; a = a + 1;

/* a is 11 */
/* c is 10 */
Decrement operator
• Pre Decrement
– Similar to Pre Increment
– Syntax : --variableName
• Post Decrement
– Similar to Post Increment
– Syntax : variableName--
Operator Precedence
• Multiple operators in an expression
• Precedence decides the order of application of
operators
• Specified by a precedence table
• Operators at the top have higher precedence
• Operators in the same row have same
precedence
• () can be used to override precedence rules
Precedence of operators
() [ ] -> . (Highest precedence)
- ++ -- ~ ! & * (type) sizeof
* / %
+ -
<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= (Lowest precedence)
Exercise-Write C Program for the
following.
1. Find out largest and smallest of two values.
2. Find out largest and smallest of three values.
3. Find out net salary where net salary = gross
salary + allowances – deductions.
If gross salary > 10000, allowances are 10%,
deductions are 3% of gross salary.
If gross salary > 5000, allowances are 7%,
deduction are 2% of gross salary.
Exercise-Write C Program for the
following.
4. Calculate total, average of marks of three
subjects. Give following grades to the
student.
If average >= 70, distinction, if average >=
60, first class,
if average >= 50, second, if average >= 35,
third class,
Otherwise fail. If student secures < 35 marks
in any subject then declare student fail.
Exercise-Write C Program for the
following.
5. Find out whether a given no. is divisible by 7
or not.
6. Find out net sales where net sales = gross
sales – discount.
If gross sales > 20000, discount is 15%
If gross sales > 10000, discount is 10%
otherwise 5%.
SWITCH-CASE-DEFAULT
• Control statement
• Allows us to make a decision from the
number of choices.
• switch( integer expression)
{
case constant1 : { statements1 }
break;
case constant2 : { statements2 }
default : { statement3 }
}
SWITCH-CASE-DEFAULT

expression

has value constant 1 statements 1 break

constant 2 statements 2
missing break
control falls through

statements 3
default
SWITCH-CASE-DEFAULT
int i = 25;
switch (i)
{
case 121: printf(“121\n”);
break;
case 7: printf(“7\n”); break;
default: printf(“ I am in default\n”);
};
SWITCH-CASE-DEFAULT

if i ==

has value 121 printf(“121”); break

7 printf(7);

default printf(“default”);
SWITCH-CASE-DEFAULT
char c = ‘x’;
switch (c)
{
case ‘v’ : printf(“ I am in case v.\n”);
case ‘a’ : printf(“ I am in case a.\n”);
case ‘x’ : printf(“ I am in case x.\n”);
default : printf(“ I am in default.\n”);
}
SWITCH-CASE-DEFAULT
The output will be
I am in case x.
I am in default.
why?
we have not written break statement.
SWITCH-CASE-DEFAULT
char c = ‘a’;
switch (c)
{
case ‘a’ :
case ‘A’ : printf( “I am in case a.”);
break;
case ‘1’ : printf( “ I am in case 1.”);
break;
};
LOOP STRUCTURE
entry
Let us
Understand
loop
do...while
true
condition Action 1
while
false
Action 2 for
exit
Steps for Writing Algorithm

A: Statements to be
A executed before loop begins
B B: Starting Value
E
C: Ending Value
F D: Difference
E: Control Variable (C.V.)
= Initial Value (I.V.)
D C
F: Loop Statements
G G: Statements to be
executed after loop ends.
Flow of do…while loop

initialization

Add Difference

loop back Loop statement(s)

yes no
condition
DO…WHILE LOOP STRUCTURE

do
A
{
E B
D

F
F

D C
G
} while ( C );
G
Examples of do…while loop
Print 1st 10 natural numbers. Print 1st N natural numbers.
INPUT N
I=0 1 I=0 1

PRINT I PRINT I
+1 10 +1 N

printf(“Enter a Value.”);
i = 0; scanf(“%d”,&n); i = 0;
do do
{ {
i ++; ++i;
printf(“%d\n”,i); printf(“%d\n”,i);
} while ( i < 10 ); } while ( i < n );
Flow of while loop

initialization

no
condition
loop back
yes
Add Difference

Loop statement(s)
WHILE LOOP STRUCTURE
A
A
E B
E
F

while ( C )
D C
G
{
D

F
};
G
Examples of while loop
Print 1st 10 natural numbers. Print 1st N natural numbers.
INPUT N
I=0 1 I=0 1

PRINT I PRINT I
+1 10 +1 N

printf(“Enter a Value.”);
i = 0; scanf(“%d”,&n); i = 0;
while ( i < 10 ) while ( i < n )
{ {
i = i + 1; i += 1;
printf(“%d\n”,i); printf(“%d\n”,i);
}; };
Flow of for loop

initialization

loop back no
condition

yes
Add Difference

Loop statement(s)
FOR LOOP STRUCTURE
Steps for writing Algorithm
A
A: Statements to be
E B executed before loop begins
B: Starting Value
F C: Ending Value
D: Difference
D C E: Control Variable (C.V.)
G = Initial Value (I.V.)
F: Loop Statements
G: Statements to be
executed after loop ends.
for ( C.V.= B ;C.V. <= C ; C.V. + D )
{
F
};
Examples of for loop
Print 1st 10 natural numbers. Print 1st N natural numbers.
INPUT N
I=0 1 I=0 1

PRINT I PRINT I
+1 10 +1 N

printf(“Enter a Value.”);
scanf(“%d”,&n);
for ( i = 1 ; i <= 10 ; i = i + for ( i = 1 ; i <= n ; i = i + 1 )
1) {
{ printf(“%d\n”,i);
printf(“%d\n”,i); };
};
Comparison of
while and do…while
• While and for are top-tested loop.
– Condition is checked before loop body is being
executed.
– If condition is true, then only loop gets executed.
– It may happen that loop may not be executed at all.
• do…while is bottom-tested loop.
– Condition is checked after loop body is executed.
– Even if condition is false, it will execute the loop
body once.
Keywords continue and break
• Find out the output of the following segment of
the program.
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
for(j=1;j<=5;j++) for(j=1;j<=5;j++)
{ {
if ( i == j) if ( i == j)
continue; break;
printf(“%d %d\n”,i,j); printf(“%d %d\n”,i,j);
} }

You might also like