You are on page 1of 260

C BASICS

Learning Outcomes
History of C A glance at a simple C program, its compilation and execution Data types RAGHUDATHESH G P Variables Keywords Constants
RAGHUDATHESH GP

ASST PROF

C BASICS

Learning Outcomes
Console IO Scope of a variable Storage class specifiers Structure of the C program G P RAGHUDATHESH Compilation model

RAGHUDATHESH GP

ASST PROF

C BASICS

History of C
BCPL (Basic Combined Programming Language): mid 60s B: 1970 C: 1971RAGHUDATHESH G P Originally designed for and implemented on UNIX system by Dennis Ritchie.
RAGHUDATHESH GP
ASST PROF

C BASICS

/* First C Program */ 1 main() 2 { printf("Hello, my first C program"); }


3 4

Simple C program

RAGHUDATHESH G P

1. Comment
2. Program execution begin here 3. Block 4. Special type of statement that prints on the console.

5. A statement must end with a semicolon.

RAGHUDATHESH GP

ASST PROF

C BASICS

Simple C program

/* First C Program */ main(){ printf("Hello, my first C program") }

RAGHUDATHESH GP hello.c

Compile
hello.obj

File name
Hello, my first C program
RAGHUDATHESH GP

run

ASST PROF

C BASICS

Comments
Statements of information Single line comment //This is a RAGHUDATHESH G P // program for addition Multi-line comment Why should we comment /*This is a program our program? for addition*/
RAGHUDATHESH GP
ASST PROF

C BASICS

Denotes kinds of data Primary data types Integral types: char, int Floating point types: RAGHUDATHESH GP float, double Derived types long int, short int, unsigned int, short unsigned int etc. Secondary data types array, pointer, structure, union, enum
RAGHUDATHESH GP

Data types

Later
ASST PROF

C BASICS

Sizes of primary types


char: 1 byte, ranging from -128 to 127 int: RAGHUDATHESH GP 2 bytes, ranging from -32768 to 32767 float : 4 bytes, ranging from -3.4e38 to 3.4e38 double: 8 bytes, ranging from -1.7e308 to 1.7e308
RAGHUDATHESH GP
ASST PROF

C BASICS

Derived Types
From the primary types char, int, float, double, many more types called derived types can be formed. Apart from that, unsigned and signed can RAGHUDATHESH G P also be specified to integral types depending on need. Example: unsigned char gives range from 0 to 255 which is actually what we want since ASCII values also have the same range.
RAGHUDATHESH GP
ASST PROF

C BASICS

long and short


long int : 4 bytes short int: 2 bytes which is same as int

RAGHUDATHESH G P

short int that can also be written as short. long int can also be written as long

RAGHUDATHESH GP

ASST PROF

C BASICS

Data types (primary and derived)


Bytes
1

Data type
signed char

Range
-128 to 127

0 to 255 -32768 to 32767 0 to 65535 -2147483648 to RAGHUDATHESH 2147483647 GP long unsigned int 4 0 to 4294967295 float 4 -3.4e38 to 3.4e38 double 8 -1.7e308 to 1.7e308 long double 10 -1.7e4932 to 1.7e4932
RAGHUDATHESH GP
ASST PROF

unsigned char short signed int short unsigned int long signed int

1 2 2 4

C BASICS

Declaration statement
General format:
datatype variableName;

RAGHUDATHESH G P Example:
int x; float y; char c;

But what is a variable ?


RAGHUDATHESH GP
ASST PROF

C BASICS

Variables
A variable has a name and represents the memory location where a value (s) is stored. RAGHUDATHESH G Pa data Every variable is associated with type indicating the kind of data it stores. Variable has to be declared in the program so that compiler and runtime environment can determine memory depending on its type.
RAGHUDATHESH GP
ASST PROF

C BASICS

Rules for variable names


Combination of alphabets, digits and underscore First character must be an alphabet RAGHUDATHESH GP No commas or blanks Some compiler restrict the names of the variables only up to 8 characters. ? Must not be a keyword. Examples: interest, pay_roll, pay_roll_07
RAGHUDATHESH GP
ASST PROF

Variable declaration and initialization


Declare and then initialize int i; i=50; int i,j; RAGHUDATHESH i=20;j=20;

C BASICS

GP

Declare and initialize together int i = 50; int i, j; i=j=20; Variable declaration must be the first statement in RAGHUDATHESH GP any block before any of the other statements.
ASST PROF

C BASICS

Keywords
Words in the C language whose meaning are already defined Keywords cannot be used as variable GP names. RAGHUDATHESH They are reserved words

RAGHUDATHESH GP

ASST PROF

C BASICS

32 keywords in C
double else
enum float for goto if

auto break
case

int long
register short signed sizeof static
RAGHUDATHESH GP

struct switch
typedef unsigned void volatile while
ASST PROF

char
const continue default do

RAGHUDATHESH extern return G P union

C BASICS

Constants
A constant is a value that does not change
C allows us to use the following constants

RAGHUDATHESH GP Integer constants Real or Floating Point (Float) constants Logical constants Character constants String constants
RAGHUDATHESH GP

ASST PROF

C BASICS

Must have at least one digit Can be either positive or negative. If no sign precedes the constant, it is positive Range allowed: 216 to 216-1 or (-32768 to 32767) RAGHUDATHESH 2 bytes GP Examples: 43, 343, -54, -5678 Cannot have decimal points For integers that hold up to 4 bytes suffix l or L ? Example : 5677188199292L, 67L 67L is forcing the computer to allocate 4 RAGHUDATHESH GP bytes for 67 instead of 2 bytes.
ASST PROF

Rules for integer constants

C BASICS

Octal constants
A leading 0 can be specified to indicate that the integer constant is octal (base 8) Counting from 0 through 8 in octal looks like this:RAGHUDATHESH 0 1 2 3 4 5 6 7 10 G P
int seven = 07; // decimal value 7 int eight = 010; // decimal value 8
What is the decimal equivalent of 0111? RAGHUDATHESH GP

ASST PROF

C BASICS

Hexadecimal constants
A leading 0x or 0X can be specified to indicate that the integer constant is hexadecimal (base 16). RAGHUDATHESH Ghex P looks Counting from 0 through 15 in like this: 0 1 2 3 4 5 6 7 8 9 a b c d e f int x=0X1; // decimal 1 int x=0xf; // decimal 15
What is the decimal equivalent of 0x11?
RAGHUDATHESH GP
ASST PROF

C BASICS

Rules for real constants


Must have at least one digit Can be either positive or negative. If no sign precedes the constant, it is positive Must have a decimal point RAGHUDATHESH GP Examples: +76.66, 76.0, -67.87 Can also be expressed in exponential form: Example: 4.5e-6, 4,1e1, 6.7E9, -9.7E7 Note that e can be either in lower case or upper case. Range -3.4e38 to 3.4e38 RAGHUDATHESH GP
ASST PROF

C BASICS

Rules for logical constants


A value representing True or False Non-zero value is true Zero is false RAGHUDATHESH G P Example: 1 ( representing a true) 0 (representing a false), 8.7, -45 ( representing a true)
RAGHUDATHESH GP
ASST PROF

C BASICS

Rules for character constants


Single alphabet, digit or special symbol Should be enclosed within single inverted commas Since characters are internally as RAGHUDATHESH G treated P integers, the ASCII values of character is what is stored internally. For example ASCII for A is 65. Range : -128 to 127 Example: C,7, Escape sequence like \n RAGHUDATHESH GP
ASST PROF

C BASICS

Escape Sequence
Escape sequences are characters which are not associated with any particular letter. For example, a new line character: \n. RAGHUDATHESH It is so called because it usesG aP \ to escape the meaning of the character next to it. What if we want a character constant with value ?
RAGHUDATHESH GP

ASST PROF

C BASICS

Escape sequence character table


\n \b \f \ \\ \t \r \a \ New line Backspace Form feed Single quote RAGHUDATHESH GP Backslash Tab Carriage return Alert Double quote
RAGHUDATHESH GP
ASST PROF

C BASICS

Rules for string constants


A set of characters enclosed within double inverted commas Example: RAGHUDATHESH Let us learn C, G P \Hello\, 7

RAGHUDATHESH GP

ASST PROF

C BASICS

#define
#define is used to associate a constant with a name which can be used in the program. Syntax: #define constant-name value RAGHUDATHESH GP

Example: #define PI 3.14

What is the advantage of associating a name with the constant ?


RAGHUDATHESH GP
ASST PROF

C BASICS

Console Output
printf() is an inbuilt function used to display output on the console (screen). General form: printf(<format string(s)>, RAGHUDATHESH <list of variable(s)>) G P %c: for printing characters %d for printing integers %f for floating point %s for strings %lf for double RAGHUDATHESH GP
ASST PROF

C BASICS

Program to add two numbers (1)


/*Addition of two numbers*/ main(){ int a, b, sum; a=10; RAGHUDATHESH G P b=2; sum=a+b; printf("a=%d, b=%d, sum=%d", a,b,sum); } RAGHUDATHESH GP

ASST PROF

C BASICS

Console input
scanf() is an inbuilt function used to accept input that users enter through the keyboard. RAGHUDATHESH GP General form: scanf(<format string(s)>, &<list of variable(s)>)
Note the & symbol. & indicates address.
RAGHUDATHESH GP
ASST PROF

C BASICS

Program to add two numbers (2)


/*Addition of two numbers*/ main(){ int a, b, sum; printf("please enter the value of RAGHUDATHESH G P Read and store the a and b"); scanf("%d%d",&a,&b); values entered into memory location sum=a+b; allocated for a and b. printf("a=%d, b=%d, sum=%d", a,b,sum); }
RAGHUDATHESH GP
ASST PROF

C BASICS

Question?
What will happen if you try to print &a, &b and &sum in the previous code? printf("a=%d, b=%d, sum=%d", &a,&b,&sum); RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

C BASICS

Scope of variables
Global -- declared outside all functions -- accessible to all statements in the RAGHUDATHESH G P program Local declared inside functions accessible to statements within the function where declared
RAGHUDATHESH GP
ASST PROF

C BASICS

Example
Global variable int j=10; main(){ Local variable int a=20; printf("a=%d, a); RAGHUDATHESH GP printf(j=%d, j); } Some other function fun(){ printf("a=%d, a); printf(j=%d, j); }
RAGHUDATHESH GP
ASST PROF

C BASICS

Storage Class Specifiers


Variables have data types and storage classes associated with them A variables storage class denotes
where RAGHUDATHESH the variable will be stored / G (memory P CPU registers) what its default value will be (that is, if no value is assigned) the scope of the variable the lifespan of the variable
RAGHUDATHESH GP
ASST PROF

C BASICS

Types of Storage Class Specifiers


automatic
register static

RAGHUDATHESH G P

extern

We will deal with this in the functions chapter

RAGHUDATHESH GP

ASST PROF

C BASICS

Automatic storage class


Storage: memory Default value: unpredictable value / garbage RAGHUDATHESH GP Scope: local to the block where it is defined Lifespan: till the control remains in the block where it is defined Example: auto int sum;
RAGHUDATHESH GP
ASST PROF

C BASICS

Register storage class



Storage: CPU registers Default value: unpredictable value / garbage Scope: local to the block where it is defined Lifespan: till the control remainsG in P the block RAGHUDATHESH where it is defined Example: register int sum; Advantage in declaring a variable as register storage class is faster access. Variables that are used very often can be declared as this.
RAGHUDATHESH GP
ASST PROF

Compilation model

C BASICS

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

C BASICS

Learning Outcomes
Operators Type Conversion Flow Control Statements

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

C BASICS

Operators
A symbol that denotes an operation that can be performed on some data

RAGHUDATHESH GP Logical Arithmetic Binary Bitwise Arithmetic Unary Conditional Relational Assignment
RAGHUDATHESH GP
ASST PROF

C BASICS

Arithmetic Binary
Operator + Example a+b Result 30
Back to School

Assume the following declaration: int a=10,b=20;


Operation Addition

Subtraction Division
Modulo

RAGHUDATHESH G P
/
%

a-b a/b

-10 0
10

Multiplication

a*b 10%20

200

20) 10( 0
0
10
3

Applicable only to integral RAGHUDATHESH types. The GP sign of the result is the same as that of the numerator.
ASST PROF

C BASICS

Arithmetic Unary
Sign Operator: + Example: +5, -5 Increment and Decrement byG 1P RAGHUDATHESH ++ - Pre-increment
y=++x; (x=x+1; and y=x;)

Post-increment
y=x++; (y=x; and x=x+1;)
RAGHUDATHESH GP
ASST PROF

C BASICS

Relational operators
Operators used to Operator compare two operands (variables, constants or < expressions) > CharactersRAGHUDATHESH can be G <= compared as well These operators are >= used extensively with flow control statements.
A few slides ahead!

Meaning
less than
greater than less than or equal to greater than or equal to equal to not equal to
ASST PROF

== !=

Examples: a!=b, a<=b

RAGHUDATHESH GP

C BASICS

Logical Operators: &&


To be used when a statement or set of statements are to be executed based on whether two expressions are true The expression on the RHS will RAGHUDATHESH G P be evaluated only if the expression on the LHS is true. Example: (x>10)&&(y<a) Also called Short circuit and operator
RAGHUDATHESH GP
ASST PROF

C BASICS

Logical Operators: ||
To be used when a statement or set of statements are to be executed based on whether at least any one of two expressions are true RAGHUDATHESH G P The expression on the RHS will be evaluated only if the expression on the LHS is false. Example: (x>10)||(y<a) Also called Short circuit or operator
RAGHUDATHESH GP
ASST PROF

C BASICS

Truth table for && and ||


expression 1 expression 2 exp1&&exp2 exp1||exp2

0 0

0 number 0

non-zero 0 RAGHUDATHESH G P1

non-zero number non-zero number

0
1

1
1
ASST PROF

non-zero number

0 implies False and 1 (or any non-zero number) implies true RAGHUDATHESH GP 8

C BASICS

Logical operators
Logical not: ! to used when the truth value of an expression is to be reversed Example: !(x>10) RAGHUDATHESH GP

RAGHUDATHESH GP

ASST PROF

C BASICS

Bitwise operators
Back to School 0000001 & 0000101 0000001
| 0000001

Assume the following declaration: char a=1,b=3;


Operation Operator Example Result

Bitwise AND Bitwise OR Bitwise XOR 1s complement

1G P RAGHUDATHESH & | ^ ~ 1&3 1|3 1^3 ~1


RAGHUDATHESH GP

3 2 -2

0000101
0000101

0000001 ^ 0000101 0000100

Move ahead

ASST PROF

10

C BASICS

~
Back to School

~1 00000001 (1s complement) Sign bit 1s complement 11111110 How to find the decimal equivalent of 11111110? Since the sign bit is 1 the number is negative. RAGHUDATHESH G get P the binary To get the decimal value of ve number equivalent of 2s complement and convert it to decimal 2s complement -( 1s complement + 1) 1s complement of 11111110 00000001 00000001 + 1 ------------RAGHUDATHESH GP 00000010 decimal value 2. Hence the number is 11 -2.
ASST PROF

C BASICS

Conditional operators
?: Also known as ternary operators as they work on three operands
If condition results in false value RAGHUDATHESH GP execute expression 2

condition ? expression 1 : expression 2


If condition results in true value execute expression 1

Example: z=x>y?10:15
RAGHUDATHESH GP
ASST PROF

12

C BASICS

Assignment operator
= variable=expression; Assigns the value of the expression to the variableRAGHUDATHESH G P Examples: a=b, a=10, a=x+y, a=x++, a=++x

RAGHUDATHESH GP

ASST PROF

13

C BASICS

Compound Operators
+= -= *= /= %= >>= >>>= <<= &= |= ^=
examples

expression
x=x+1 x=x-1 x=x*(5+10) x=x/(5+10)

RAGHUDATHESH G P
x+=1 x-=1 x*=(5+10) x/= (5+10)

equivalent

x=x%20

x%=20
RAGHUDATHESH GP
ASST PROF

14

C BASICS

sizeof
Returns the number of bytes the operand occupies in memory. Example:

RAGHUDATHESH sizeof(float) sizeof(2) int x=9; sizeof(x) ;


RAGHUDATHESH GP

GP

ASST PROF

15

C BASICS

Predict the output


1. 2. 3. 4. printf(%d, -5%-3); printf("%d",10<20); printf(%d,10&&20); RAGHUDATHESH G P int i=10,j=20,k; k=(i>j) && (j++>i); printf("%d",j); 5. printf(%d,!-1);
RAGHUDATHESH GP
ASST PROF

16

C BASICS

Conversions
What happens when two variables of different data types are used in an expression? For example, what happens when a variable of type int is added to a variable of type float? RAGHUDATHESH G P When two operands are of different types, then the operand that has smaller size is converted to the type of the operand of larger size before the operation is performed. This is implicit or widening conversion.
RAGHUDATHESH GP
ASST PROF

17

C BASICS

The implicit conversion in the direction indicated happens automatically to one of the operands when the operands of different types are used. charintlong intfloatdouble
If one of the operands is signed, the other is automatically converted to signed.

Implicit conversion

RAGHUDATHESH G P

When a variable of type int is added to a variable of type float, implicit type conversion takes place where the variable of type int is GP 18 promoted to a floatRAGHUDATHESH before the operation is done.
ASST PROF

C BASICS

Type Casting
Implicit conversion is done by the compiler automatically. Sometimes we may need to change RAGHUDATHESH G P implicit behavior In such cases we must explicitly request the compiler by using a cast operator. Cast operator: (datatype)
RAGHUDATHESH GP
ASST PROF

19

C BASICS

Example
int i=10, j=20; float f; f=i/j; RAGHUDATHESH G P printf(%f, f); prints 0.0 But f=(float)i/j; prints 0.500000
Casting i to float type.

RAGHUDATHESH GP

ASST PROF

20

C BASICS

Predict the output


char c=127; char c1=c+2; printf("%d",c1); RAGHUDATHESH G P char c=127; printf("%d",c+2);

RAGHUDATHESH GP

ASST PROF

21

C BASICS

Operators Associativity unary -------------------------------------------------------[] . () -> . left to right ! ~ ++ -- - + * (type) sizeof right to left * / % left to right + left to right >> << left to right < > <= >= left to right == != left to right & left to right ^ left to right | left to right && left to right || left to right ?: left to right = += -= *= /= >>= <<= >>>= &= ^= GP |= left to right RAGHUDATHESH 22 ASST PROF

Precedence

RAGHUDATHESH G P

C BASICS

Control Statements
Statements that enable us to order the sequence of flow of a program. Decision control statements
if statement RAGHUDATHESH switch statement

GP

Loops

while statement for statement do-while statement


RAGHUDATHESH GP
ASST PROF

23

C BASICS

if
if (condition is true) execute this statement; if (condition is true) RAGHUDATHESH G P { execute statement 1; execute statement 2; execute statement n; }
RAGHUDATHESH GP
ASST PROF

24

C BASICS

Examples for if
if (rate<10) printf(This is cheap.); if (rate<10) RAGHUDATHESH G P { printf(This is cheap.); printf (Would you like to buy?); }
RAGHUDATHESH GP
ASST PROF

25

C BASICS

if-else

if (condition is true) execute this statement; else execute this statement; if (condition is true){ execute statement 1; RAGHUDATHESH G execute statement 2; execute statement n; } else{ execute statement n+1; execute statement n+2; RAGHUDATHESH GP execute statement n+m;

ASST PROF

26

C BASICS

Examples for if-else


if (salary>1000) printf(You do not have to pay tax.); else printf (You have to pay tax.); if (salary>1000){ RAGHUDATHESH G P printf(You do not have to pay tax.); printf(But you need to pay a surcharge.); } else printf(You have to pay tax.);
RAGHUDATHESH GP
ASST PROF

27

C BASICS

switch (integer expression 1){ case integer constant 1: Can appear 0, 1 or more statement 1; times for statement 2; different RAGHUDATHESH G Pconstant statement n; values default: statement n+1; Can appear 0 statement n+2; or 1 time statement n+m; RAGHUDATHESH GP 28 }
ASST PROF

switch

C BASICS

switch example

/* This is a menu-driven program for basic arithmetic operations between two numbers*/ main(){ int a,b,i; printf("enter 2 integer numbers separated RAGHUDATHESH GP by a blank space: "); scanf("%d%d",&a,&b);

printf("please enter \n 1 to add\n 2 to subtract\n 3 to divide\n 4 to multiply\n 5 for modulo\n"); cal1.c 29 scanf("%d",&i); RAGHUDATHESH GP
ASST PROF

switch(i){ case 1: printf("Result of addition is :%d ",(a+b)); case 2: printf("Result of subtraction is :%d ",(a-b)); case 3: printf("Result of division is :%d ",(a/b)); case 4: printf("Result of multiplication RAGHUDATHESH GP is :%d ",(a*b)); case 5: printf("Result of modulo is :%d ",(a%b)); default:printf(Inappropriate value entered"); } } RAGHUDATHESH GP 30
C BASICS ASST PROF

C BASICS

execution

Execution path 1 : enter 2 integer numbers separated by a blank You enter this space: 12 2 please enter 1 to add RAGHUDATHESH G P 2 to subtract 3 to divide 4 to multiply 5 for modulo You enter this 3 Result of division is :6 Result of multiplication is :24 Result of modulo is :0 RAGHUDATHESH GP 31 Inappropriate value entered
ASST PROF

Execution path 2 : enter 2 integer numbers separated by a blank space: 10 5 You enter this please enter 1 to add 2 to subtract 3 to divide RAGHUDATHESH G P 4 to multiply 5 for modulo You enter this 1 Result of addition is :15 Result of subtraction is :5 Result of division is :2 Result of multiplication is :50 Result of modulo is :0 Inappropriate value entered
C BASICS

RAGHUDATHESH GP

ASST PROF

32

C BASICS

Fall through problem


Do you see the problem ? To correct this problem break is used at the end of each case statement. RAGHUDATHESH GP It however not necessary to put the break at the end of the last case or default statement. Let us correct the program by including break.
RAGHUDATHESH GP
ASST PROF

33

switch(i){ case 1: printf("Result of addition is :%d ",(a+b)); break; case 2: printf("Result of subtraction is :%d ",(a-b)); break; case 3: printf("Result of division is :%d ",(a/b)); RAGHUDATHESH G P break; case 4: printf("Result of multiplication is :%d ",(a*b)); break; case 5: printf("Result of modulo is :%d ",(a%b)); break; default:printf(Inappropriate value entered"); }} RAGHUDATHESH GP 34
C BASICS ASST PROF

cal2.c

C BASICS

Execution
enter 2 integer numbers separated by a blank space: 12 4 You enter this please enter 1 to add 2 to subtract RAGHUDATHESH G P 3 to divide 4 to multiply 5 for modulo You enter this 2 Result of subtraction is :8
RAGHUDATHESH GP
ASST PROF

35

C BASICS

More points on switch


Since char is also of integer type you can use char also as switch expression variables and case constants. We can also mix char and integers. RAGHUDATHESH P default can be anywhere in G between the switch cases. It need not be at the end. But if it is in between make sure that break is inserted. You can have a case without any statement. To understand where you would require such a thing move on to the next RAGHUDATHESH GP slide. 36
ASST PROF

Example: case without any statement


C BASICS

main(){ int a,b; char i; printf("enter 2 integer numbers separated by a blank space: ");

cal3.c

scanf("%d%d",&a,&b); scanf("%c",&i); printf("please enter \n a to add\n s to subtract\n d to divide\n m to multiply\n o for modulo\n any other char to exit\n "); ? scanf("%c",&i);
RAGHUDATHESH GP
ASST PROF

RAGHUDATHESH G P

37

C BASICS

switch(i){ case 'a': Fall through case 'A': printf("Result of addition is :%d ",(a+b)); break; case 's': Fall through case 'S': printf("Result of RAGHUDATHESH GP subtraction is :%d ",(a-b)); break; case 'd': Fall through case 'D': printf("Result of division is :%d ",(a/b)); break;
RAGHUDATHESH GP
ASST PROF

38

C BASICS

case 'm': Fall through case 'M': printf("Result of multiplication is :%d ",(a*b)); break; case 'o': Fall through case 'O': printf("Result of RAGHUDATHESH Gmodulo P is :%d ",(a%b)); break; Exits out of the program default: exit(); }
}
RAGHUDATHESH GP
ASST PROF

39

C BASICS

while-loop
while(condition is true) statement; while(condition is true){ RAGHUDATHESH GP statement 1; statement 2; statement n; }
RAGHUDATHESH GP
ASST PROF

40

C BASICS

Example 1
/* program to display numbers divisible by 2 and 3 between 1 to 100 */ div1.c main() { int i=1; RAGHUDATHESH G P while(i!=100){ if(i%2==0 && i%3==0) printf("%d, ",i); i++; } }
RAGHUDATHESH GP
ASST PROF

41

C BASICS

Example 2
Suppose for our calculator program you want to continue to display the menu until user exits, in such case while can be used. cal4.c main(){ int a,b; RAGHUDATHESH G P char i; int j=1; New code added while(j){ printf("enter 2 integer numbers separated by a blank space: "); scanf("%d%d",&a,&b);

RAGHUDATHESH GP
ASST PROF

42

switch(i){ //same code } printf("\n enter 0 to stop"); scanf("%d",&j); New code added } // end of while loop }

C BASICS

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

43

C BASICS

do-while
do-while is same as while with the only exception that the condition is checked only at the end of the loop. Therefore do-while guarantees that the statement RAGHUDATHESH G P within the loop will execute at least once. do{ statement(s) } while(condition);
RAGHUDATHESH GP
ASST PROF

44

C BASICS

Try out!
How will you change the while-loop of the calculator program to do-while loop ?

G P is more You mayRAGHUDATHESH find that the do-while loop appropriate in this case since we definitely need the menu to be displayed at least once!

RAGHUDATHESH GP

ASST PROF

45

C BASICS

for

In example 1 of the while loop, we saw that we set up an initial value for int i and then executed the loop until i reached certain value, incrementing is value by 1 each time. This can RAGHUDATHESH be more simply achieved G P through for loop. for(initialize var;condition; increment var){ statement(s); }
RAGHUDATHESH GP
ASST PROF

46

C BASICS

Example

div2.c

/* program to display numbers divisible by 2 and 3 between 1 to 100 this time using for loop */ main(){ RAGHUDATHESH int i; for(i=0;i<=100;i++){ if(i%2==0 && i%3==0) printf("%d, ",i); } }
RAGHUDATHESH GP

GP

ASST PROF

47

C BASICS

Count backwards
/* factorial of a number*/ main(){ int num,i,f; printf("enter a number"); scanf("%d",&num); RAGHUDATHESH G f=num; for(i=num-1;i>1;i--) f=f*i; printf("%d",f); }
RAGHUDATHESH GP

ASST PROF

48

C BASICS

break in loops
The keyword break is used to exit out of the loop anytime even when if it does not satisfy the loop conditions. RAGHUDATHESH GP When break is encountered the control jumps to the first statement after the loop.

RAGHUDATHESH GP

ASST PROF

49

C BASICS

/* program to determine if an integer entered by the user is a prime number */ main(){ int num,j,i,flag=1; printf("enter an integer "); scanf("%d",&num); j=num/2; RAGHUDATHESH G P
for (i=2;i<=j;i++){ if(num%i==0){ flag=0; printf("Not prime"); break; }} RAGHUDATHESH GP if (flag) printf("Prime number");

Example

ASST PROF

50

C BASICS

continue in loop
The continue statement is used to skip the rest of the statements in the loop and carry on with the next iteration. Gis P In other RAGHUDATHESH words, when continue encountered, the control goes to the beginning of the enclosing loop.

RAGHUDATHESH GP

ASST PROF

51

C BASICS

Example
/* program to determine if an integer greater than 100 entered by the user is a prime number */ main(){ int num,j,i,flag=1;

RAGHUDATHESH G P

while(1){ printf("enter an integer greater than 100 "); scanf("%d",&num); if(num<100) continue; If a number < 100 is entered j=num/2;
RAGHUDATHESH GP
ASST PROF

52

C BASICS

for (i=2;i<=j;i++){ if(num%i==0){ flag=0; printf("Not prime"); break; } } RAGHUDATHESH G P if (flag) printf("Prime number"); break; } }

RAGHUDATHESH GP

ASST PROF

53

C BASICS

Learning Outcomes
Function Argument Passing static variable Command line arguments G P RAGHUDATHESH Recursion

RAGHUDATHESH GP

ASST PROF

C BASICS

Function
A function is a block of code that performs a particular task. A function can be called from the same or another function whenever required. Hence RAGHUDATHESH GP we can avoid rewriting the same code. It also improves the readability of the program. Function may take some input in the form of parameters and sent out some output in the form of return value.
RAGHUDATHESH GP
ASST PROF

Example1: function without argument and return type


C BASICS

/* Using function :program to determine if an integer greater than 100 entered by the user is a prime number */ num is declared as global variable so that int num; it is accessible by all the functions. RAGHUDATHESH GP main(){ while(1){ printf("enter an integer greater than 100 "); scanf("%d",&num); if(num<100) continue; printprime(); primef1.c RAGHUDATHESH GP 3 break;}}
ASST PROF

printprime() { int j,i,flag=1; j=num/2; for (i=2;i<=j;i++){ if(num%i==0){ RAGHUDATHESH G P flag=0; printf("Not prime"); break; } } if (flag) printf("Prime number"); } RAGHUDATHESH GP

C BASICS

ASST PROF

C BASICS

return value
Did you notice the warnings that the compiler throws?
Warning primefun.c 12: Function should return a value in function main Warning RAGHUDATHESH primefun.c 27: Function should GP return a value in function printprime

In fact the first warning has been appearing ever since we have started C programming. A function must either return a value or must be declared as void.
RAGHUDATHESH GP
ASST PROF

C BASICS

return_type function_name(argumentlist) Where argument-list is Data-type var-name1, Data-type varname2, Data-type var-namen If return_type is not specified itG is P assumed to be RAGHUDATHESH an int. argument-list can contain 0 one or more arguments. function_name must be unique. It should not clash with any variable name or other function name. Variables declared inside the function and the argument-list variables are local to the function. RAGHUDATHESH GP They cannot be accessed outside the function. 6
ASST PROF

Function declaration

C BASICS

return
The return statement is used to return a value from a function. When return is encountered the control go back to RAGHUDATHESH the calling function. G P Example:
return (a); return (15); return 0; return;

Used with void. Does not return anything!


ASST PROF

RAGHUDATHESH GP

By adding return 0; at the end of main() and printprime() function we can eliminate the warnings. primef2c main(){ return RAGHUDATHESH 0; GP } printprime(){ return 0; } We need to make return type of printprime as void RAGHUDATHESH GP 8 not int.
ASST PROF

Correcting the prime number code


C BASICS

C BASICS

Complier assumes that any C function would return a type int. Any function that returns types other than int must inform the compiler by what is called prototyping. RAGHUDATHESH G P Prototyping is declaring the function that needs to be called within the calling function. Note that declaration of a function is different from definition of a function.
RAGHUDATHESH GP
ASST PROF

Prototyping

C BASICS

Changing the prime number code


primef3.c int num; int main(){ Declaring the called function void pprime(); in the calling function since called function returns void. while(1){ printf("enter an integer greater RAGHUDATHESH G P than 100 "); scanf("%d",&num); if(num<100) continue; pprime(); break; } RAGHUDATHESH GP 10 return 0}
ASST PROF

C BASICS

void pprime() { int j,i,flag=1; j=num/2;

Defining the called function

for (i=2;i<=j;i++){ if(num%i==0){ RAGHUDATHESH G P flag=0; printf("Not prime"); break; } } if (flag) printf("Prime number"); return; optional RAGHUDATHESH GP }

ASST PROF

11

C BASICS

Function with parameters


It is possible for the calling function to pass values into the called function through what is called parameters or arguments. RAGHUDATHESH G P Suppose we declare num variable inside the main(), then we will need to pass num into pprime() function since num will be local to the main() function and so it not be accessible to the pprime() function.
RAGHUDATHESH GP
ASST PROF

12

Example : prime number code with parameters


C BASICS

void main(){ int num; Making num local to main() void pprime(int n);

while(1){ RAGHUDATHESH G P printf("enter an integer greater than 100 "); scanf("%d",&num); if(num<100) continue; pprime(num); break;} RAGHUDATHESH GP 13 return 0;} primef4.c
ASST PROF

Or simply - void pprime(int);

void pprime(int x){ int j,i,flag=1; j=x/2;


C BASICS

Instead of x, num also could be used. Local variables declared inside different functions can be same!

for (i=2;i<=j;i++){ if(x%i==0){ flag=0; printf("Not prime"); G P RAGHUDATHESH break; } } if (flag) printf("Prime number");

}
RAGHUDATHESH GP
ASST PROF

14

C BASICS

Example of function returning a value of importance

/* program that has a function which calulates the gross salary given the basic salary*/ main(){ RAGHUDATHESH G P double basic,gross; double calculateGross(double basic); printf("enter basic salary "); scanf("%lf",&basic); gross= calculateGross(basic); printf("Gross=%lf",gross); } RAGHUDATHESH GP 15 gross.c
ASST PROF

double calculateGross(double basic){ double hra,ta,da, gross; da=0.5 * basic; hra=0.1 *basic; if(basic<10000) ta=1000; else if(basic>=10000 && basic<20000) RAGHUDATHESH GP ta=2000; else ta=3000; gross=basic+hra+ta+da;
C BASICS

return gross; }

RAGHUDATHESH GP

ASST PROF

16

C BASICS

Suppose we attempt to write a code that prints the number of times a function is called. main(){ void callMe(); count1.c callMe(); callMe();} RAGHUDATHESH G P void callMe(){ int count; count++; printf("you called me %d times\n" , count);} When we execute the following code it prints garbage value for count because count is not initialized. RAGHUDATHESH GP 17
ASST PROF

Without static variable

If we initialize count to 0 then print


C BASICS

you called me 1 times three times.


main(){ void callMe(); callMe(); callMe();} RAGHUDATHESH G P void callMe(){ int count=0; count++; printf("you called me %d times\n" , count);} This is because the value of count gets initialized each time the function is called. What we want is a way in which count value can RAGHUDATHESH GP 18 be retained.
ASST PROF

C BASICS

static variable
Solution to this is to declare the count variable as static variable. Static variables are automatically RAGHUDATHESH initialized the first time to 0. G P It retains the value between the function calls. static can be declared only with the function.
RAGHUDATHESH GP
ASST PROF

19

C BASICS

Count example corrected


main(){ void callMe(); callMe(); Prints: callMe(); you called me 1 RAGHUDATHESH G Pme 2 callMe(); you called } you called me 3 void callMe(){ static int count; count++; printf("you called me %d times\n" count); RAGHUDATHESH GP }

times times times

,
ASST PROF

20

C BASICS

void main(){ void f(int i,int j);

Call by value

int i=0, j=0; printf("Before calling f(): G value of RAGHUDATHESH P i=%d and value of j=%d\n", i,j); f(i,j); printf("After calling f(): value of i=%d and value of j=%d\n", i,j); }
RAGHUDATHESH GP
ASST PROF

21

void f(int i,int j){ printf("In f() before changing : value of i=%d and value of j=%d\n", i,j);
C BASICS

i++; j++;

printf("InRAGHUDATHESH f() after changing: value of GP i=%d and value of j=%d\n", i,j); }
Result of execution

Before calling f(): value of i=0 and value of j=0 In f() before changing : value of i=0 and value of j=0 In f() after changing: value of i=1 and value of j=1 RAGHUDATHESH GP 22 After calling f(): value of i=0 and value of j=0
ASST PROF

C BASICS

Observation
What do you observe? The parameter values changed in the called function code are not reflected in the calling function. RAGHUDATHESH G P This is because the parameters are passed by value to the function. Both functions have their own copy of the variables. Only the values of the variables of the calling function get copied to the variables of the called function
RAGHUDATHESH GP
ASST PROF

23

main() i j
C BASICS

Address
1000 1001 1002 1003

Call f(0,0)

0
0 0 1 1

i j

f() RAGHUDATHESH GP 1005

1004

i j i++; j++; i j RAGHUDATHESH GP

MEMORY 24
ASST PROF

C BASICS

main() i=0
j=0
1000 1001 Calls

i=1

f()

j=1

Value of i and j i=0 2000 in 1000 and RAGHUDATHESH G P j=0 2001 1001 remain the same! i++; j++;
In memory

RAGHUDATHESH GP

ASST PROF

25

C BASICS

Call by reference
What should be done so that the changed values of i and j are reflected in the calling function? 1. There should be some way in which we RAGHUDATHESH GP pass the addresses of the variables of i and j from the calling function to the called function. 2. The called function should receive these variables in a way such that they point to values rather than just receiving the values. RAGHUDATHESH GP 26
ASST PROF

C BASICS

Call by reference cont


&variable-name represents the address of the variable. Address of a variable is of integer type. RAGHUDATHESH G P that is We need a special kind of variable capable of holding an address and using which we can retrieve the value stored in the address. Such a kind of variable is called a Pointer.
RAGHUDATHESH GP
ASST PROF

27

C BASICS

Introduction to pointers
A pointer is a variable that holds an address of a variable in memory and using this pointer we can access the value stored in that location. Declaration: RAGHUDATHESH GP Data-type *variable_name; Data-type in the above syntax represents what type of data the pointer points to. Example: double i=10; double *p=&i;
RAGHUDATHESH GP
ASST PROF

28

C BASICS

Getting the address and value


*variable-name returns the value stored in the address that variable-name points to. variable-name returns the address value. RAGHUDATHESH G P Example: double i=10; double *p=&i; printf(%lf,*p); Prints 10 printf(%d,p); Prints the address
RAGHUDATHESH GP
ASST PROF

29 point.c

C BASICS

Question ?
The data-type of a pointer variable is always integer. Then what is the significance of ? specifying data-type in the declaration syntax? It is important to specify the appropriate data-type RAGHUDATHESH G P in the syntax if you want to use pointer arithmetic. You can use ++ and operators on the pointer which allows pointer to jump to next location. Whether the jump has to be 1 byte , 2 bytes , 4 bytes, 8 bytes or 10 bytes is determined by the data-type of the pointer.
RAGHUDATHESH GP
ASST PROF

More details on it in the pointers30 part of the C story.

C BASICS

Call by reference
/* program : call by value demo */ void main(){ void f(int *i,int *j); int i=0, j=0;

RAGHUDATHESH G P

printf("Before calling f(): value of i=%d and value of j=%d\n", i,j); f(&i,&j); printf("After calling f(): value of i=%d and value of j=%d\n", i,j); }
RAGHUDATHESH GP
ASST PROF

31

C BASICS

void f(int *i,int *j) { printf("In f() before changing : value of i=%d and value of j=%d\n", *i,*j); (*i)++; (*j)++;

RAGHUDATHESH G P

printf("In f() after changing: value of i=%d and value of j=%d\n", *i,*j); }
RAGHUDATHESH GP 32

ASST PROF

C BASICS

Challenge question?
In the function f() of the previous slide, we used brackets to increment the values of i and j.
(*i)++; RAGHUDATHESH (*j)++;

GP

What will happen if the brackets are removed? Will the effect be the same?
*i++; *j++;
RAGHUDATHESH GP
ASST PROF

33

C BASICS

Recursion

A function that calls itself is a recursive function. It is very important that a recursive function has an exit point. Otherwise it will get into infinite loop.
int i; condition main(){ specified. f();} Executes int f(){ successfully. i++; if(i>5) return ; Without termination RAGHUDATHESH GP 34 f();} condition : infinite loop
ASST PROF

int i; main(){ f();} int f(){ f(); }

RAGHUDATHESH G Termination P

C BASICS

Prime number using recursion


/* prime number using recursion */ int num,k; main(){ printf("enter an integer "); RAGHUDATHESH G P scanf("%d",&num); k=prime(2); if(k==0) printf("not prime"); else printf("prime"); }
RAGHUDATHESH GP
ASST PROF

35

int prime(int i){ if(num%i==0) return 0; i++; if(i>num/2) return 1; else prime(i); }

C BASICS

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

36

C BASICS

Flow
Assume num=9 prime(2) 1 {if(num%i==0) return 0; 9%2!=0 i++;2++ 3 if(i>num/2) return 1;3>(9/2) No! Return value: 0 else 4 RAGHUDATHESH G P prime(i); prime(3) }
2 3 Return value: 0

{if(num%i==0) return 0; 9%3 i++; if(i>num/2) return 1; else prime(i);}


RAGHUDATHESH GP
ASST PROF

37

C BASICS

Attempt another example


Write a non-recursive code to generate 10 Fibonacci numbers.

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

38

C BASICS

Non-recursive Recursive main(){ main(){ void fibo(int f1, int f2); int f1=0,f2=1,f3,i; int f1=0,f2=1,f3,i; printf("%d, %d,", printf("%d, %d,", f1,f2); f1,f2); fibo(f1,f2); for(i=0;i<8;i++) } { GP void fibo(int f1, int f2){ f3=f1+f2; RAGHUDATHESH static int count; f1=f2; int f3; Termination condition f2=f3; printf("%d,", f2); if(count>8) return; f3=f1+f2; } f1=f2; f2=f3; } printf("%d,", f2); count++; RAGHUDATHESH GP 39 fib.c fibo(f1,f2);}
ASST PROF

Fibonacci numbers

fibr.c

C BASICS

Use of recursion
Recursive programs sometime seem rather difficult in comparison to non-recursive ones. But in some cases it is actually easier to use recursion. RAGHUDATHESH G P For example in cases where you have a mathematical formula based on iterative value of n. For example- factorial value of n. Mathematical formula: fact(n)= n*fact(n-1) for all n<1
RAGHUDATHESH GP
ASST PROF

40

C BASICS

Recursive code

main(){ int num, res; printf("enter a number"); scanf("%d",&num); res=fact(num); printf("%d",res); RAGHUDATHESH G } int fact(int n){ int f; if(n==0) return 1; f=n*fact(n-1); return f; } RAGHUDATHESH GP

ASST PROF

41

C BASICS

num=3
fact(3)

Flow
Return 6

{int f; if(n==1) return 1; n=3 Return 2 f=n*fact(n-1); 3*fact(2) return f;} RAGHUDATHESH G P {int f; if(n==1) return 1; n=2 f=n*fact(n-1); 2*fact(1) return f;} { int f; if(n==1) return 1; n=1 f=n*fact(n-1); RAGHUDATHESH GP return f;}
Return 1
ASST PROF

42

C BASICS

Challenge!
Write recursive code to find the sum of digits First attempt to write the recursive RAGHUDATHESH G P formula. Then write the code.

RAGHUDATHESH GP

ASST PROF

43

C BASICS

Word of caution!
Recursive code may be difficult to understand and debug. Hence it should be used only in places where it makes the overall program simpler. RAGHUDATHESH GP Recursive code adds to overhead of multiple function calls.

RAGHUDATHESH GP

ASST PROF

44

C BASICS

Learning Outcomes
Arrays
Single dimensional Multidimensional

Console IO

RAGHUDATHESH G P

Unformatted IO Formatting

RAGHUDATHESH GP

ASST PROF

C BASICS

Arrays
Suppose you have to work with 100 numbers. Imagine the difficulty and time taken to type in names of 100 variable names. RAGHUDATHESH G P Arrays are here for our rescue! Array is a collection of elements of same data type.
RAGHUDATHESH GP 2

ASST PROF

C BASICS

Declaration and Initialization of Single dimensional array

An array that is a list of elements is a single dimensional array. data-type variable-name[size] Example: double prices[10]; RAGHUDATHESH G P A single dimensional array can be initialized with the declaration statement as shown in the example given below. int emp_nums[]={123,111,175,4} Int emp_nums[4]={123,111,175,4} An array that is not initialized (and which is not declared as static) contains garbage values. RAGHUDATHESH GP 3
ASST PROF

C BASICS

Accessing arrays

Array elements are accessed using the index position. Index position begins from 0. main(){ float price[]={120.50,100,175,50}; price.c int i; for(i=0;i<4;i++){ RAGHUDATHESH G P printf("Old Price for item no. %d is %f\n",i, price[i] ); price[i]=price[i]*0.02 +price[i]; printf("New Price for item no. %d is %f\n\n",i,price[i]); }} Similarly to read the data into price array, RAGHUDATHESH GP 4 scanf(%d, &price[i];
ASST PROF

C BASICS

Array and memory


When the array declaration statement is encountered, memory required for the array is calculated and contiguous memoryRAGHUDATHESH space is allocated. G P For example, for int size[4]; 4*2= 8 bytes contiguous memory space is allocated.
1000 1002 1004 1008
ASST PROF

RAGHUDATHESH GP

C BASICS

An array of char is a string. char c[]={R,i,t,c,h,i,e,\0}; is same as char c[]=Ritchie;

Strings

RAGHUDATHESH G P Note \0 (null) at the end of the first declaration. This

is to indicate the end of the string. Note that the 2nd declaration does not require this. To read and print strings simply use: Note the absence of & sign. scanf(%s,c); Why? Because the value of c printf(%s,c); is the value of the starting
RAGHUDATHESH GP

address of the array !

ASST PROF

C BASICS

Two dimensional array

Two dimensional array is like a table containing elements in the intersection of a row and a column. The best example of two dimensional array is a matrix. data-type var-name [size][size] Examples: RAGHUDATHESH G P int emp_sal[3][2]; can be viewed as: 3 rows and 2 columns int k[2][2]={ {12,34}, {13,35}}; int k[][2]={ {12,34}, {13,35}} ; int k[][2]={ {12,34,13,35};
RAGHUDATHESH GP
ASST PROF

/* getting the employee numbers and salaries of three employees into a 2dimensional array and displaying them */ main(){ int emp_sal[3][2],i,j; for(i=0;i<3;i++){ printf("enter emp number\n"); scanf("%d",&emp_sal[i][0]); RAGHUDATHESH G P printf("enter salary\n"); scanf("%d",&emp_sal[i][1]); } printf("emp number\tsalary\n"); for(i=0;i<3;i++) printf("%d\t\t%d\n",emp_sal[i][0],emp_sa l[i][1] ); RAGHUDATHESH GP 8 }
C BASICS ASST PROF

C BASICS

Experiments in lab
What will happen if array is accessed beyond its last index? What is the initial value of array elements GP that are RAGHUDATHESH not initialized? What will happen index is ve?

RAGHUDATHESH GP

ASST PROF

C BASICS

main(){ int a[]={1,2,3,4}; Result of execution: int i; Or f(&a[0]); 2 3 4 5 f(a); for(i=0;i<4;i++) RAGHUDATHESH GP printf("%d ",a[i]); } The change made in f(int a[]){ the called function is int i; reflected in the called for(i=0;i<4;i++) function. a[i]++; }
RAGHUDATHESH GP arrfun.c
ASST PROF

Functions and arrays

10

C BASICS

Analysis
main(){ a f(a1000) }
1000 1002

1 2 &a[0] 2 3
&a[1]

RAGHUDATHESH G P 1004
1008

3 4 &a[2] 4 5 &a[3]

f(a){ a[i]++; }
RAGHUDATHESH GP

ASST PROF

11

C BASICS

Array and pointer


A pointer variable can be assigned to arrays base address and using the pointer increment operator all the array elements can be accessed. RAGHUDATHESH G P Next slide shows the same code that we wrote in the previous slide using pointers. Like ++ operator, - - operator can also be used to jump one position before.
RAGHUDATHESH GP
ASST PROF

12

main(){ int a[]={1,2,3,4}; int i; f(a); for(i=0;i<4;i++) printf("%d ",a[i]); }


C BASICS

f(int *p){ int i; for(i=0;i<4;i++) { Increment the value (*p)++; p++; Jump 2 bytes to next element location RAGHUDATHESH GP 13 }}
ASST PROF

RAGHUDATHESH G P

C BASICS

2-D array and pointer


int a[3][2]={{1,2},{3,4},{5,6}}; int *p=&a[0];
can be viewed as array of arrays where a[0] is base address of row 1, a[1] is the base RAGHUDATHESH GP address of row 2 etc.
1

2 3 4

5
RAGHUDATHESH GP

ASST PROF

14

C BASICS

Other wonders!
int a[]={1,2,3,4}; 1. *(a+1) a[1]2 2. *(2+a)2[a] a[2]3 int RAGHUDATHESH G P a[3][2]={{1,2},{3,4},{5,6}};
a[1][1]*(a[1]+1) *(*(a+1)+1)
RAGHUDATHESH GP
ASST PROF

15

C BASICS

String and Pointer


main(){ char s is an array of characters s[]="Shankara"; char *p="Shankara"; p is a pointer to the first printf("%s",s); printf("%s",p); }
stored.
Both the print statements print Shankara.

character where RAGHUDATHESH G PShankara is Note that the printf() statement with %s prints the string char by char without having to increment the array index or pointer position.
RAGHUDATHESH GP
ASST PROF

16

C BASICS

Strings and pointer


Array of strings can be represented in two ways: char str[][3] char *str[];(array G of RAGHUDATHESH P pointers to string) First way is preferred to read the string from the console. Second way is the more preferred way to manipulate and print!
RAGHUDATHESH GP
ASST PROF

17

main(){ names1.c char n1[][4]={"John","Mary","Sita","Rama"}; int i; char *n2[]={"John","Mary","Sita","Rama"}; for(i=0;i<4;i++) RAGHUDATHESH GP printf("%s ",n1[i]); printf("\n"); for(i=0;i<4;i++) printf("%s ",n2[i]); }
JohnMarySitaRama MarySitaRama SitaRama Rama 18 John Mary Sita RamaRAGHUDATHESH GP
ASST PROF

C BASICS

scanf() does not work with array of pointers to string


C BASICS

main(){ char *names[4]; int i; for(i=0;i<4;i++){ RAGHUDATHESH printf("enter the name \n"); scanf("%s",names[i]); } for(i=0;i<4;i++){ printf("%s \n",names[i]); } }
RAGHUDATHESH GP

GP

names2.c
ASST PROF

19

C BASICS

So how to read string from console and print them ?

main(){ char names[6][4]; char *nm[4]; int i; for(i=0;i<4;i++){ RAGHUDATHESH G P printf("enter the name \n"); scanf("%s",names[i]); nm[i]=names[i]; }

for(i=0;i<4;i++){ RAGHUDATHESH GP printf("%s ",nm[i]);

}}

ASST PROF

names3.c

20

C BASICS

Command line arguments


Command line arguments are the data that we can pass through command-line. The command line arguments are received through a special kind of main() RAGHUDATHESH GP function: main(int argc, char*argv[]) argc holds the number of arguments and argv contains the address of the strings passed from the command line.
RAGHUDATHESH GP
ASST PROF

21

C BASICS

Example command-line arguments


main(int argc, char *argv[]){ int i;
cla.c

RAGHUDATHESH G P for(i=0;i<argc;i++) printf("%d : %s \n",i,argv[i]); } D:\cla hello Prints: 0: D:\cla.exe 1: hello


RAGHUDATHESH GP
ASST PROF

22

C BASICS

IO
IO is Input-Output. IO operations deal with reading from various input devices like keyboard, disk, network and writing to various output devices like VDU, disk, network etc. RAGHUDATHESH G P C programming language by itself does not support IO. But C compiler writers have written several libraries which can be included in our C program to do IO. printf() and scanf() are thus library functions.
RAGHUDATHESH GP
ASST PROF

23

C BASICS

Console IO
Reading from the keyboard and writing on to the screen. Two types of functions Unformatted RAGHUDATHESH G P Formatted Formatted functions allows us to display the data in the way that we want. For example, if we want to display price with only 2 decimal places, then it is possible only with the formatted IO functions.
RAGHUDATHESH GP
ASST PROF

24

Unformatted functions to read char


C BASICS

getchar(), getche(), getch() getche(), getch() return the input from the console. Unlike scanf(), they doesnt wait for the enter button to be clicked before they can consume the value typed in. RAGHUDATHESH GP getche() echoes( or displays ) the character typed in. getchar() also echoes( or displays ) the character typed in but requires enter button to be clicked like scanf().
RAGHUDATHESH GP
ASST PROF

25

C BASICS

main(){ int a,b; char i; printf("enter 2 integer numbers separated by a blank space: "); scanf("%d%d",&a,&b); RAGHUDATHESH G P getchar(); printf("please enter \n a to add\n s to subtract\n d to divide\n m to multiply\n o for modulo\n any other char to exit\n "); 26 i=getchar(); RAGHUDATHESH GP }
ASST PROF

Back to calculator code

C BASICS

Unformatted functions to print char


putch(char c), putchar(char c) Both are same and both print character on the screen.\ Example: putch(A); char ch=B; putchar(ch);

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

27

C BASICS

Unformatted functions for strings


gets() and puts() gets() is used to read string from the console and puts() is used to print. RAGHUDATHESH G in P cases scanf() does not work properly where a string is composed of multiple words. scanf() function assumes space between the words as end of the string. This is where the gets() becomes useful.
RAGHUDATHESH GP
ASST PROF

28

C BASICS

Difference scanf() and gets()


You enter this

main(){ char clr[10];

printf("enter a color\n"); enter a color light green scanf("%s",clr); RAGHUDATHESH GP printf(" \n %s",clr);} light main(){ char clr[10]; puts("enter a color\n"); gets(clr); puts(clr); RAGHUDATHESH GP }

You enter this enter a color

light blue light blue

ASST PROF

29

C BASICS

printf() can be used to format the output in the way we want to see in the screen. For instance, when we print a double value we can restrict it to 2 digits after decimal. printf(formatstring,variables) RAGHUDATHESH G P

Formatting

Formatting characters interpreted moment % is encountered. Any character that does not involve a % or \(escape char) passes through straight without any interpretation and gets printed RAGHUDATHESH GP 30 as it is.
ASST PROF

C BASICS

Formatting characters
Data type Conversion char %d or %i short signed %u short unsigned %ld long signed RAGHUDATHESH G P %lu long unsigned %f float %lf double %c signed and unsigned char %s string
RAGHUDATHESH GP
ASST PROF

31

C BASICS

Format String
%[special_char][width] ][.precision] conversion char
special_char : - : Left justify this argument RAGHUDATHESH GP +: Include a sign (+ or -) with this argument 0: Pad this argument with zeroes Width: minimum number of characters to print. Precision: the number of digits to print after the decimal point
RAGHUDATHESH GP
ASST PROF

32

C BASICS

Example
main(){ int i=10; double d=1245.678; signed short j=-10; RAGHUDATHESH printf("=%5d\n", i); printf("=%+5d\n", i); printf("=%-5d\n", i); printf("=%05d\n", i); printf("=%+5d\n", j); printf("=%5.2lf\n", d); }
RAGHUDATHESH GP

Result: G = P 10 = +10 =10 =00010 = -10 =1245.68


ASST PROF

33

C BASICS

Learning Outcomes
Pointers- summary of what we have seen so far Pointer operators Dynamic memory allocation RAGHUDATHESH G P Pointer to pointer Pointer to function

RAGHUDATHESH GP

ASST PROF

C BASICS

Pointers- summary of what we have seen so far RAGHUDATHESH GP

RAGHUDATHESH GP

ASST PROF

C BASICS

Basics
value name

int i=10; 10 i i: gives the value10 1002 &i: gives the address002 *(&i): gives the value10 pointer

Memory address

RAGHUDATHESH G P

value 1002 j name

int *j; :pointer to an int 2002 j=&i; :pointer assignment. j: gives the address of i1002 &j: gives the address of j2002 *j: give the value of i10 RAGHUDATHESH GP

Memory address

ASST PROF

C BASICS

1-D array and pointers


*a 1

int a[]={1,2,3,4};

1000 a
1002 a +1 1004 a +2

a[0],0[a],*a, *a+0 1 *(a +1) a: base array address *(a +2) 1000

2 3 4

GP a+2: base RAGHUDATHESH array address+2 1000 2 * sizeof(int) b 2002 1000+2*2 bytes int *b; 1000+4=1004 b=a; b: base array address of array a1000 *b: value at 1000 1 4 RAGHUDATHESH GP *(b+1): value at 10022
*(a +3)
ASST PROF

1006 a +3

C BASICS

2-D array and pointers

int a[2][2]={{5,6},{7,8}}; a: base array address of array 1000 *a,*a+0, a[0]: value at a2001 **a,**(a+0),*(a[0]),*(a[0]+0),a[0][0]: value at *a5 2001
5 P RAGHUDATHESH G 2002 a 1001 **a

6
7

**(a+1)

a+1 1002 a[0]*a a[1]*(a+1)

2001 2004

2004 2006

RAGHUDATHESH GP a[0][1],*(a[0]+1),*(*(a+0)+1) 6

ASST PROF

C BASICS

Pointer Operators

*: value at the address specified by the variable &: address of the variable ++: increments the pointer by size of the variable --:decrements the pointer by size of the variable GP +: additionRAGHUDATHESH of a pointer variable and a constant value -: subtraction of pointer and a constant value and subtraction of two pointers. ==: comparison of pointers
RAGHUDATHESH GP
ASST PROF

C BASICS

Predict the output


main(){ int a[2][2]={{5,10},{15,20}};

RAGHUDATHESH G P printf("%d\n",**a+1); printf("%d\n",*(*a+1)); printf("%d\n",*(*(a+1)));


}
RAGHUDATHESH GP
ASST PROF

parth.c 7

C BASICS

Array of pointers
Array of pointers to int: int *ptrs[2]; Array of pointers to int 2001 int i=10,j=11; ptrs[0]=&i; 2001 ptrs[1]=&j; RAGHUDATHESH G P
2002
2002

10

11

*(ptrs[1]), ptrs[1][0]11
RAGHUDATHESH GP
ASST PROF

ptrarr.c

C BASICS

Pointer to Pointer
A pointer variable that points to another pointer variable is a pointer to a pointer represented by **.
int i=10RAGHUDATHESH G P int *j; int **k; 2004 1003 j=&i; j k k=&j;

10 i

k is a pointer to a pointer to an int

**k10
RAGHUDATHESH GP
ASST PROF

C BASICS

Pointers to function

Like variables, functions also have addresses. A pointer variable can point to anything in the memory. RAGHUDATHESH GP Therefore a pointer variable can point to an address of a function too. The next example maintains a function pointer which points to a particular function based on users input and then later executes that function through the function RAGHUDATHESH GP 10 pointer.
ASST PROF

main(){ int i; int f(); Prototype declaration int g(); Function pointer int (*fptr)(); printf("type 0 for f() or 1 for g() "); scanf("%d", &i); if(i) RAGHUDATHESH G P address Assigning function fptr=g; to function pointer else fptr=f; Calling function through (*fptr)(); function pointer return 0; }
C BASICS

RAGHUDATHESH GP

ASST PROF

11

int f(){ printf("f() called"); return 0; } int g(){ printf("g() called"); return 0; RAGHUDATHESH }

C BASICS

GP
You type this

Output: type 0 for f() or 1 for g() 1 g() called


RAGHUDATHESH GP

ASST PROF

12

C BASICS

Dynamic memory allocation

Using arrays we can reserve a fixed memory location. Suppose that there can be a maximum of 100 employees in a department and minimum of 2. In such cases, allocation of 100 locations for a RAGHUDATHESH G P dept having 2 employee would be utter waste of space. In such cases, we can use dynamic memory allocation that allows us to allocate memory dynamically as and when required instead of allocating and reserving it straight away. RAGHUDATHESH GP 13
ASST PROF

C BASICS

malloc & calloc


To allocate memory on the fly at run time, 2 library functions malloc() or calloc() can be used. malloc(size of memory ) returns a chunk ofRAGHUDATHESH memory. We need to cast G P it to the type we want and assign it to pointer variable. calloc(number of data, size of each data) returns a chunk of memory. We need to cast it to the type we want and assign it to pointer variable.
RAGHUDATHESH GP
ASST PROF

14

main(){ int *empno, n,i; printf("enter the number of employees: "); scanf("%d",&n);
C BASICS

2 bytes

empno=(int *) malloc(n*2); or (int *) calloc(n,2); if(empno=='\0'){ RAGHUDATHESH G P printf("memory not available"); Null condition exit(0);} else for(i=0;i<n;i++){ printf("\nenter the employee number: "); scanf("%d",(empno+i)); RAGHUDATHESH GP 15 }
ASST PROF

printf("printing all the employee numbers"); for(i=0;i<n;i++) printf("\nemployee number %d : %d\n", i, *(empno+i)); }
C BASICS

enter the number of employees: 3 RAGHUDATHESH enter the employee number: 5432 enter the employee number: 6453 enter the employee number: 7654 printing all the employee numbers employee number 0 : 5432 employee number 1 : 6453 employee number 2 : RAGHUDATHESH 7654 GP

Output:

GP
You enter this

ASST PROF

16

C BASICS

Learning Outcomes
Structure and its need
Syntax Memory allocation Passing structure in function RAGHUDATHESH Pointers and structure Nesting structure

GP

Union
Difference between struct and union Syntax Union of structs RAGHUDATHESH GP

ASST PROF

C BASICS

Structure
Structure is a way in which a complex user-defined data type can be created using simple types. For example, an employee isG a data-type RAGHUDATHESH P consisting of employee number, name and salary. Structure allows us to define employee, and then assign variables to the employee structure type.
RAGHUDATHESH GP
ASST PROF

C BASICS

Defining structure: struct struct-name{ data-type variable-name1; data-type variable-name2; RAGHUDATHESH G P data-type variable-namen; };

Syntax

members

Declaring variable of struct-type: struct struct-name variable-name;


RAGHUDATHESH GP
ASST PROF

C BASICS

Example
struct employee{ int emp_num; defining char name[30]; RAGHUDATHESH G P double salary; }; struct employee emp1,emp2; declaring

RAGHUDATHESH GP

ASST PROF

C BASICS

Accessing members
Structure members can be accessed using . operator on the structure variable. Example: RAGHUDATHESH GP emp1.emp_num, emp2.name Structure members can be initialized during the declaration as: struct employee emp={123,Bobby,345.50};
RAGHUDATHESH GP
ASST PROF

C BASICS

struct emp{ int num; char name[30]; double sal; }; struct emp emps; main(){ RAGHUDATHESH G read(); display(); } read(){ printf("enter emp number:"); scanf("%d",&emps.num); printf("enter name:"); RAGHUDATHESH GP scanf("%s",emps.name);

Example- simple

emp1.c

ASST PROF

printf("enter salary:"); scanf("%lf", &emps.sal); } display(){ printf("Displaying data \n"); printf(" emp number: %d\n", emps.num); printf(" emp name: %s\n",emps.name); printf(" emp salary: %5.2lf\n",emps.sal); } RAGHUDATHESH G P Output:
C BASICS

enter emp number:123 enter name:Kanaka enter salary:12340 Displaying data emp number: 123 emp name: Kanaka emp salary: 12340.00 RAGHUDATHESH GP

You enter this

ASST PROF

C BASICS

main(){ struct ball{ int size; char color[30]; }; struct ball b[3]; RAGHUDATHESH G P int i; for(i=0;i<3;i++){ printf("enter size of the ball:"); scanf("%d",&b[i].size); printf("enter the color:"); scanf("%s",b[i].color); } printf("Displaying data \n"); RAGHUDATHESH GP for(i=0;i<3;i++){

Example array of structure ball.c

ASST PROF

printf(" ball size: %d\n",b[i].size); printf(" ball color: %s\n",b[i].color); }}


C BASICS

Output: enter size of the ball:12 enter the color:green enter size of the ball:13 You enter this enter the color:red enter size of the ball:10 RAGHUDATHESH GP enter the color:yellow Displaying data ball size: 12 ball color: green ball size: 13 ball color: red ball size: 10 ball color: yellowRAGHUDATHESH GP

ASST PROF

C BASICS

Structure Pointers

A pointer variable can be declared that points to a structure like it points to an ordinary variable. Example: struct emp emps={123,"Ganga", 12000}; struct emp *e=&emps; RAGHUDATHESH GP To access members through structure pointer, a special kind of symbol is used. Example: enum, ename Structure pointers are required when we pass a structure variable to a function and we want the changes made in the variable visible in the calling RAGHUDATHESH GP 10 function.
ASST PROF

struct emp{ emp2.c int num; char name[30]; double sal; }; main(){ struct emp emps={123,"Ganga", 12000}; increment(&emps); RAGHUDATHESH G P emps.sal display(&emps); emps.num } 123 Ganga 12000
C BASICS

2001

emps.name

13200

increment(struct emp *e){ e->sal=e->sal*0.10+e->sal; }


RAGHUDATHESH GP

2001
ASST PROF

e
11

display(struct emp *e){ printf("Displaying data \n"); printf(" emp number: %d\n",e->num); printf(" emp name: %s\n",e->name); printf(" emp salary: %5.2lf\n",e->sal); }
C BASICS

Output: RAGHUDATHESH Displaying data emp number: 123 emp name: Ganga emp salary: 13200.00

GP

RAGHUDATHESH GP

ASST PROF

12

C BASICS

Nested structure
A structure can have as its member a structure variable. Example: struct name{ char fname[10]; RAGHUDATHESH G P char lname[10]; }; struct student{ struct name nm; int rollno; Note: another way of } stud;
declaring structure variable
RAGHUDATHESH GP
ASST PROF

13

main(){ printf("enter first and last name: "); scanf("%s%s", stud.nm.fname,stud.nm.lname); printf("\nenter roll number:"); scanf("%d", &stud.rollno); printf("displaying data\n"); printf("Name:%s %s\n", RAGHUDATHESH GP stud.nm.fname,stud.nm.lname); printf("roll no %d\n", stud.rollno);}
C BASICS

Output: enter first and last name: John Ray enter roll number:12345 displaying data Name:John Ray RAGHUDATHESH GP roll no 12345

ASST PROF

14

C BASICS

unions

Union allows variables of different data types to share the same memory space. For example, a variable of int type and a variable of type char share same memory space. That means this memory RAGHUDATHESH G Pspace can be treated either as int or as char. Union allows us to choose between types of data based on the requirement of application.
RAGHUDATHESH GP
ASST PROF

15

C BASICS

Syntax

Defining union: union struct-name{ data-type member-name1; data-type member-name2; RAGHUDATHESH G P data-type variable-namen; }; Declaring variable of union-type: struct struct-name variable-name; Accessing members: variable-name.member_name
RAGHUDATHESH GP
ASST PROF

16

C BASICS

Difference between struct and union


c[1]
1004

a c[0] struct X{ int a; 1000 1002 1003 char c[2]; RAGHUDATHESH G P };

union X{ int a; char c[2]; };

a
1000 c[0] 1001 c[1] 1002
ASST PROF

RAGHUDATHESH GP

17

main(){ union X{ int a; char c[2]; } x1; x1.a=321; printf("%d\n",x1.a); printf("%c\n",x1.c[0]); RAGHUDATHESH printf("%c\n",x1.c[1]);}
C BASICS

un.c

Output: 321 A

GP
0 0 0 0 1

0 0 0 0 0 0 0 1 0

in memory low bit is stored on left and high on right!

0 1 0 0 0 0 0
c[0]=ascii(65)=A

0 1

RAGHUDATHESH GP

a=321

c[1]=ascii(0)= 18
ASST PROF

C BASICS

Enumerated data-type
Enumeration allows us to define a datatype for which a predefined set of values are defined. Any variable of this data-type then can have one of the predefined RAGHUDATHESH GP values. For example, gender can have only one of the two values male or female. Anything else would give error.
RAGHUDATHESH GP
ASST PROF

19

enum gender{ male, enum constants female }; main(){ enum gender g1,g2; g1=male; Assigning any other value would be an error. g2=female; RAGHUDATHESH G P print(g1); Output: print(g2); Male } Female print(enum gender g){ if(g==male) printf("Male \n"); else RAGHUDATHESH GP 20 printf("Female"); }
C BASICS ASST PROF

C BASICS

Internal working
Internally compiler treats enums as integers. Hence the values that enum constants take start from 0. In the previous example male RAGHUDATHESH G is P internally stored as 0 and female is 1. These values can be changed by explicitly : enum gender{ male=10, female=20 }; RAGHUDATHESH GP 21
ASST PROF

C BASICS

typedef is used to give a different name to a data type. Let us understand this with an example: struct fullname{ char fname[10]; char lname[10]; }; RAGHUDATHESH G P

typedef

To declare variable of the above type

struct fullname n1,n2;


If we have many such declarations throughout the code then typing this could be tedious.

Using typedef, we could just type RAGHUDATHESH GP name n1,n2;

ASST PROF

22

enum gender{ male, female }; typedef enum gender GEN; struct emp{ int num; char name[30]; double sal; RAGHUDATHESH G P GEN gen; }; typedef struct emp EMP; main(){ EMP emps={123,"Ganga", 12000, female}; increment(&emps); display(&emps); RAGHUDATHESH GP }
C BASICS ASST PROF

23

increment(EMP *e){ e->sal=e->sal*0.10+e->sal; }


C BASICS

display(EMP *e){ printf("Displaying data \n"); printf(" emp number: %d\n",e->num); printf(" emp name: %s\n",e->name); RAGHUDATHESH GP printf(" emp salary: %5.2lf\n",e->sal); if(e->gen==male) printf(" Gender: Male"); else printf(" Gender: Female"); }
RAGHUDATHESH GP
ASST PROF

24

C BASICS

Learning Outcomes
Preprocessor directives #define directives #include directives RAGHUDATHESH GP Conditional compilation directives

RAGHUDATHESH GP

ASST PROF

C BASICS

Learning Outcomes
Standard Library functions Standard I/O functions String functions RAGHUDATHESH G P Math functions

RAGHUDATHESH GP

ASST PROF

C BASICS

Preprocessor directives
Preprocessor directives are special type of commands that we include RAGHUDATHESH in C source code. GP These directives are processed before compilation by a special kind of program called preprocessor.
RAGHUDATHESH GP
ASST PROF

C BASICS

Structure of a C program
Preprocessor commands (directives) Global declarations Functions Statements RAGHUDATHESH G P Variable declaration statements Constants in statements IO statements Comments (any where in the code)
Must be among the first statements of the program. Only RAGHUDATHESH GP statement before a directive can be another directive! 4
ASST PROF

C BASICS

Preprocessor directives types


#define directive #include directive #undef directive

Conditional compilation directives

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

C BASICS

#define directive (or a macro) has two parts: string-part value-part #define string-part value-part RAGHUDATHESH GP When preprocessor encounters #define it replaces the string-part specified in code with the value-part. This is useful when the value-part is large and requires lot of typing or when the value-part is 6 likely to change. RAGHUDATHESH GP
ASST PROF

#define

#define PI 3.14
C BASICS

string-part No semicolon!

main(){ float area(float radius); float cir(float radius);

value-part

float radius; printf("enter radius of the G circle: "); RAGHUDATHESH P scanf("%f",&radius); printf("area is %5.2f\n", area(radius)); printf("circumference is %5.2f", cir(radius)); return 0; } RAGHUDATHESH GP cir.c 7
ASST PROF

float area(float radius){ return (radius * radius *PI); } float cir(float radius){ return (2* radius *PI); Preprocessor replaces all }
C BASICS

RAGHUDATHESH G P
Output: enter the radius of the circle: 13 area is 530.66 circumference is 81.64
RAGHUDATHESH GP

PI with 3.14. Then compilation takes place.

You enter this

ASST PROF

#define PI 3.14 #define PROD radius * PI


C BASICS

main(){ float area(float radius); float cir(float radius);


float radius; RAGHUDATHESH G P printf("enter radius of the circle: "); scanf("%f",&radius); printf("area is %5.2f\n", area(radius)); printf("circumference is %5.2f", cir(radius)); return 0; RAGHUDATHESH GP 9 }
ASST PROF

C BASICS

float area(float radius){ return (radius * PROD); } float cir(float radius){ return (2* PROD); }

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

10

C BASICS

Macro functions

A macro can also be defined with arguments just like functions. When an ordinary function is encountered in the code, the compiler transfers the control to RAGHUDATHESH GP the function ( a separate memory area). But macros (functions) are expanded in their places by the preprocessor. So there is no separate memory area. In fact compiler doesn't even know the existence of macro functions.
RAGHUDATHESH GP
ASST PROF

11

#define #define #define #define


C BASICS

PI 3.14 PROD radius *PI area(r) (r * PROD) cir(r) (2 * PROD)


Macro functions. Though not necessary it is advisable to put the macro function in parenthesis.

main(){ float radius; printf("enter radius of the G circle: "); RAGHUDATHESH P scanf("%f",&radius);

printf("area is %5.2f\n", area(radius)); printf("circumference is %5.2f", cir(radius) ); return 0; Expanded as: radius * radius *PI RAGHUDATHESH GP 12 }
ASST PROF

cir2.c

Word of caution while using macro functions


C BASICS

A macro function can only have one statement. There should be no space between macro functionRAGHUDATHESH name and argument.G P area( r ) not ok If the macro function has involves * and / then it is advisable to enclose it in brackets for it to have desired effect.
RAGHUDATHESH GP
ASST PROF

13

#define PI 3 #define VOL(radius,height) (PI*radius*radius*height)


C BASICS

den.c

main(){ float r=10, h=5, mass=1500; printf("density =%5.2f" , mass/VOL(r,h)); RAGHUDATHESH G P } density=mass/volume According to code : density=1500/ 3*10*10*1500 This is incorrect. This can be corrected by including brackets
RAGHUDATHESH GP
ASST PROF

14

C BASICS

#include directive

This directive causes a file to be included as a part of your c code. The file could contain any valid c code, either a RAGHUDATHESH set of functions or preprocessor GP directives. In fact the library functions like scanf() and printf() are provided in a file stdio.h that some compilers automatically include in the c code.
RAGHUDATHESH GP
ASST PROF

15

int square(int n){ return n*n; }


C BASICS

util.h

.h is commonly used extension (h implies header int cube(int n){ file ). Filename could be with return n*n*n; any extension or without any } extension also. RAGHUDATHESH G P int pow(int n, int p){ int i,res; res=n; for(i=1;i<p;i++) res=res*n; return res; RAGHUDATHESH GP 16 }
ASST PROF

#include "util.h" main(){


C BASICS

Preprocessor includes this header file as a part of this code.

printf("square =%d\n", square(10)); printf("pow =%d\n", pow(2,3)); }


Output: square =100 pow =8

RAGHUDATHESH G P

#include "util.h: preprocessor searches for the file in current directory as well as predefined directories where standard library files are set up. #include <util.h>: preprocessor searches for the file only in the predefined directories where standard library RAGHUDATHESH GP 17 files are set up.
ASST PROF

C BASICS

Conditional compilation directives


Conditional compilation directives allow us to specify when the compiler should compile a set of statements based on some condition. Syntax: #ifdef RAGHUDATHESH macro_name GP statement1; The compiler will execute the statements in the statement2; block only if If macro_name is defined. statementn; #endif
RAGHUDATHESH GP
ASST PROF

18

C BASICS

Conditional compilation directive statements are used in cases where we need to comment out some code for the time being. It is also used when we want to make C programs more portable#ifdef LINUX RAGHUDATHESH G P statement1; #else statement2; #endif

Uses

RAGHUDATHESH GP

ASST PROF

19

C BASICS

Contains standard library functions. Functions available:


printf() scanf() fopen() fclose() getc() RAGHUDATHESH G P fread() fopen() getchar() fwrite() fscanf() gets() fopen() fputc() putc() fprintf() ftell() putchar() fseek() fputchar() puts() malloc() RAGHUDATHESH GP 20 calloc() File handling functions
ASST PROF

<stdio.h>

C BASICS

<string.h>
Useful functions to manipulate the strings. unsigned int strlen(char *s) char * RAGHUDATHESH strcat(char *d, G char P *s) int strcmpi(char *s1,char *s2) char * strrev(char *s1) char * strlwr(char *s) char * strupr(char *s)
RAGHUDATHESH GP
ASST PROF

21

#include<string.h> main(){ char *n1="Bangalore"; char *n2="bangalore"; int i,j;


C BASICS

sman.c

printf("length of n1 :%d\n",strlen(n1)); i=strcmpi(n2,n1); RAGHUDATHESH G P if(i==0) printf("Case insensitive : Same %d\n", i); else printf("Case insensitive: Different %d\n"+i);
RAGHUDATHESH GP
ASST PROF

22

strcat(n2,n1); printf("concat n2 and n1 :%s\n",n2); strrev(n1); printf("reverse n1 :%s\n",n1); strlwr(n1); strupr(n2); printf("lower :%s\n",n1); printf("upper :%s\n",n2); G P } RAGHUDATHESH
C BASICS

Result of execution: length of n1 :9 Case insensitive : Same 0 concat n2 and n1 :bangaloreBangalore reverse n1 :erolagnaB lower :erolagnab RAGHUDATHESH GP upper :BANGALOREBANGALORE

ASST PROF

23

C BASICS

This library has all mathematical formulas. int abs(int x) double acos(double x) double asin(double x) Similarly cos, sin double atan(double x) and tan functions double exp(double x) RAGHUDATHESH G P double fabs(double x) double floor(double x) double ceil(double x) double log(double x) double pow(double x,double y) double atof(char *s) int atoi(char RAGHUDATHESH *s) GP 24
ASST PROF

<math.h>

#include<math.h> mat.c main(int n,char* args[]){ double d=13.4,f,c; int i,j,k; f=floor(d); c=ceil(d); printf("floor: %lf, ceil:%lf\n",f,c); if(n>1){ RAGHUDATHESH G P i=atoi(args[1]); printf("arg conversion %d\n",i); } if(n>2){ j=atoi(args[2]); k=pow(i,j); printf("%d pow %d=%d",i,j,k);} RAGHUDATHESH GP 25 }
C BASICS ASST PROF

C BASICS

Learning Outcomes
Types of files I/O functions Reading and writing unformatted text files RAGHUDATHESH G P Reading and writing formatted text files Reading and writing records

RAGHUDATHESH GP

ASST PROF

C BASICS

Types of File I/O


File I/O

RAGHUDATHESH G P Binary Text


unformatted formatted unformatted

RAGHUDATHESH GP

ASST PROF

C BASICS

Fundamental Steps
Open a file
Read or write Close a file

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

C BASICS

Opening a file
First step before reading or writing on to a file, is opening a file. The <stdio.h> library has all the necessary functions that allow us to work RAGHUDATHESH G P with files. The fopen() is used to open a file. FILE* fopen(char * filename, char *mode) FILE is a structure defined in <stdio.h> RAGHUDATHESH GP 4
ASST PROF

C BASICS

Modes
Mode r w a r+ w+
a+

File exist File does not exist Opens NULL Opens Creates new Opens Creates new RAGHUDATHESH G Opens NULL Opens
Opens

Creates new
Creates new
RAGHUDATHESH GP

operations read overwrites appends P Read, write and change read, overwrites
Read, write and change
ASST PROF

C BASICS

Unformatted reading and writing functions

int getc(FILE *stream) int fgetc(FILE *stream) int fgetc(FILE *stream) RAGHUDATHESH G P char * fgets(char *s, int maxlen, FILE *stream) int fputs(char *s, FILE *stream)

RAGHUDATHESH GP

ASST PROF

C BASICS

Closing a file
int fclose(FILE *stream) fclose() does two important things Any characters remaining in the buffer RAGHUDATHESH GP are written to the disk. Frees the link between the program and the files so that the file is available to other programs.
RAGHUDATHESH GP
ASST PROF

Reading and writing unformatted text file


C BASICS

#include<stdio.h> #include<string.h> FILE *fp; main(){ write(); Writing lines and reading char by char read(); RAGHUDATHESH G P } int write(){ char s[80]; fp=fopen("my.txt","w"); puts("enter a string and 1 to end"); while(1){ gets(s); RAGHUDATHESH GP 8 if(strcmpi(s,"1")==0)break;
ASST PROF

fputs(s,fp); fputs("\n",fp); } fclose(fp); } int read(){ char ch; RAGHUDATHESH fp=fopen("my.txt","r"); while(1){ ch=getc(fp); if(ch==EOF) break; End of file else printf("%c",ch);} RAGHUDATHESH GP fclose(fp); }

C BASICS

Result of execution: enter a string and 1 to end And miles to go before i sleep and miles to go before I sleep 1 And miles to go before i sleep and miles to go before I sleep

GP

ASST PROF

C BASICS

Formatted reading and writing functions

int fprintf(FILE *fp,char *format[, arguments]); int fscanf(FILE *fp,char *format[, address]); G P RAGHUDATHESH

RAGHUDATHESH GP

ASST PROF

10

#include<stdio.h> emp.c #include<string.h> FILE *fp; main(){ write(); read(); } int write(){ RAGHUDATHESH G P char name[30]; int empno; float salary; fp=fopen("emp.txt","w"); while(1){ printf("enter name or enter 1 to stop: "); RAGHUDATHESH GP scanf("%s",name);
C BASICS ASST PROF

11

if (strcmpi(name,"1")==0) break; printf("enter empno: "); scanf("%d",&empno); printf("enter salary: "); scanf("%f",&salary); fprintf(fp,"%s %d %7.2f\n",name,empno,salary); fflush(stdin);} RAGHUDATHESH G P fclose(fp); Flushes the input stream } int read(){ char name[30]; int empno; float salary; RAGHUDATHESH GP 12 fp=fopen("emp.txt","r");
C BASICS ASST PROF

while( fscanf(fp,"%s %d %f", name,&empno,&salary)!=EOF ) printf("%s %d %7.2f \n", name,empno,salary); Result: fclose(fp); } enter name: Veena
C BASICS

enter empno: 111 enter salary: 12000 enter name: RAGHUDATHESH G Anjali P enter empno: 123 enter salary: 15000 Veena 111 12000.00 enter name: Reena Anjali 123 15000.00 enter empno: 456 Reena 456 12000.00 enter salary: 12000 enter name: 1 emp.txt Veena 111 12000.00 Anjali RAGHUDATHESH GP 123 15000.00 Reena 456 12000.00

ASST PROF

13

C BASICS

Reading and writing records


Reading and writing records implies reading and writing structure variables. Here we open the file in binary mode. Functions: RAGHUDATHESH G P unsigned fwrite(void *ptr,unsigned size,unsigned n,FILE *stream) unsigned fread(void *ptr,unsigned size,unsigned n,FILE *stream) where n is number of records RAGHUDATHESH GP

ASST PROF

14

#include<stdio.h>
C BASICS

emp1.c

struct emp{ int num; char name[30]; double sal; } e;

RAGHUDATHESH G P FILE *fp;


main(){ write(); read();} int write(){ int c;

RAGHUDATHESH GP

ASST PROF

15

fp=fopen("emp1.dat","wb"); Binary mode while(c){ printf("enter emp number:"); scanf("%d",&e.num); printf("enter name:"); sizeof() operator returns scanf("%s",e.name); the size of the structure printf("enter salary:"); scanf("%lf",&e.sal); RAGHUDATHESH G P fwrite(&e,sizeof(e),1,fp); fflush(stdin); printf("enter 0 to stop"); scanf("%d",&c); } fclose(fp); } RAGHUDATHESH GP 16
C BASICS ASST PROF

int read(){ Binary mode fp=fopen("emp1.dat","rb"); while(fread(&e,sizeof(e),1,fp)) printf("%d %s %f\n",e.num,e.name,e.sal); fclose(fp); }


C BASICS

Result of execution: enter emp number:123 RAGHUDATHESH enter name:Jolly enter salary:3000 enter 0 to stop1 enter emp number:234 enter name:Kate enter salary:7000 enter 0 to stop0 123 Jolly 3000.000000 234 Kate 7000.000000 RAGHUDATHESH GP

GP

ASST PROF

17

C BASICS

Methods to move within the file


int fseek(FILE *stream, long int offset, int fromwhere) Enumerated values for fromwhere: RAGHUDATHESH G P
SEEK_END SEEK_CUR SEEK_SET

int ftell(FILE *stream) void rewind(FILE *stream)


RAGHUDATHESH GP
ASST PROF

18

Example demonstrating Append, modifying deleting and display of employee records


C BASICS

#include<stdio.h> struct emp{ int num; RAGHUDATHESH char name[30]; double sal; } e; FILE *fp; main(){ int i;

GP

RAGHUDATHESH GP

ASST PROF

19

fp=fopen("e.dat","rb+"); if(fp==NULL) fp=fopen("e.dat","wb+");


C BASICS

while(1){ printf("enter \n 1 to append\n 2 to modify salary\n 3 to delete\n 4 to print\n 5 to exit\n"); RAGHUDATHESH G P scanf("%d", &i); fflush(stdin); switch(i){ case 1: append(); break; case 2: modify(); break; RAGHUDATHESH GP

If the file already exists, open the file else create the file.

ASST PROF

20

case 3: delete(); break; case 4: read(); break; case 5: fclose(fp); exit(0); break; default: printf("invalid entry");}} RAGHUDATHESH G P } int append(){ Go to the end of fseek(fp,0,SEEK_END); the file to add. printf("enter emp number:"); scanf("%d",&e.num); printf("enter name:"); scanf("%s",e.name); RAGHUDATHESH GP
C BASICS ASST PROF

21

printf("enter salary:"); scanf("%lf",&e.sal); fwrite(&e,sizeof(e),1,fp); fflush(stdin); }


C BASICS

int read(){ rewind(fp); RAGHUDATHESH G P while(fread(&e,sizeof(e),1,fp)) printf("%d %s %lf\n",e.num,e.name,e.sal); fflush(stdin); }

RAGHUDATHESH GP

ASST PROF

22

int modify(){ int eno;


C BASICS

rewind(fp); printf("enter emp number to modify:"); scanf("%d",&eno); while(fread(&e,sizeof(e),1,fp)){ if(e.num==eno){ RAGHUDATHESH G P printf("enter salary\n"); scanf("%lf",&e.sal); fseek(fp,-40,SEEK_CUR); fwrite(&e,sizeof(e),1,fp); break; go back 40 bytes (that is the } size of the employee record) } to rewrite the record. RAGHUDATHESH GP 23 }
ASST PROF

Read the file record by record to find the employee number.

int delete(){ FILE *t; int eno;


C BASICS

Copy the file record by record to a temp file excluding the record which you want to delete.

t=fopen("temp.dat","wb"); printf("enter emp number to delete:"); scanf("%d",&eno); RAGHUDATHESH G P rewind(fp); while(fread(&e,sizeof(e),1,fp)){ if(e.num!=eno){ fwrite(&e,sizeof(e),1,t); }}
RAGHUDATHESH GP
ASST PROF

24

fclose(t); fclose(fp); remove("e.dat"); rename("temp.dat","e.dat"); fp=fopen("e.dat","rb+"); }


C BASICS

Remove the old employee file and rename the temp file with the old emp file name. Doing this requires you to close the file stream.

RAGHUDATHESH G P

RAGHUDATHESH GP

ASST PROF

25

You might also like