Basics Of C Program
-
Upload
raghudathesh -
Category
Documents
-
view
217 -
download
0
Transcript of Basics Of C Program
-
8/13/2019 Basics Of C Program
1/260
Learning Outcomes
History of CA glance at a simple C program, its
compilation and execution
Data types
Variables
Keywords
Constants
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
2/260
Learning Outcomes
Console IOScope of a variable
Storage class specifiers
Structure of the C program
Compilation model
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
3/260
History of C
BCPL (Basic Combined Programming
Language): mid 60s
B: 1970
C: 1971
Originally designed for and implementedon UNIX system by Dennis Ritchie.
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
4/260
Simple C program/* First C Program */
main()
{
printf("Hello, my first C program");
}
1
2
3 4
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.
5
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
5/260
Simple C program
/* First C Program */main(){
printf("Hello, my first C program")
}
Compile
hello.obj
hello.c
File name
runHello, my first C program
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
6/260
Comments
Statements of information
Single line comment
//This is a// program for addition
Multi-line comment
/*This is a programfor addition*/
Why should we
commentour program?
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
7/260
Data types
Denotes kinds of data Primary data types
Integral types:
char, int
Floating point types:
float, double
Derived types
long int, short int, unsigned int, shortunsigned int etc.
Secondary data types
array, pointer, structure, union, enum LaterRAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
8/260
Sizes of primary types
char:
1 byte, ranging from -128 to 127
int:
2 bytes, ranging from -32768 to 32767
float :
4 bytes, ranging from -3.4e38 to 3.4e38
double:
8 bytes, ranging from -1.7e308 to1.7e308
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
9/260
Derived Types
From the primary types char, int, float,double, many more types called derivedtypes can be formed.
Apart from that, unsigned and signed canalso be specified to integral typesdepending on need.
Example: unsigned char gives range from 0 to 255 which is
actually what we want since ASCIIvalues also have the same range.
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
10/260
long and short
long int : 4 bytes
short int: 2 bytes which is same as int
short int that can also be written as short.
long int can also be written as long
?
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
11/260
Data types (primary and derived)
Data type Bytes Range
signed char 1 -128 to 127
unsigned char 1 0 to 255
short signed int 2 -32768 to 32767
short unsigned int 2 0 to 65535
long signed int 4 -2147483648 to2147483647
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.7e4932RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
12/260
Declaration statement
General format:
datatype variableName;
Example:
int x;
float y;
char c; But what is avariable ?
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
13/260
Variables
A variable has a name and represents the
memory location where a value (s) is
stored.
Every variable is associated with a data
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
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
14/260
Rules for variable names
Combination of alphabets, digits and
underscore
First character must be an alphabet
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
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
15/260
Variable declaration and initialization
Declare and then initialize
int i;
i=50;
int i,j;
i=20;j=20;
Declare and initialize together
int i = 50;
int i, j;
i=j=20;
Variable declaration must be the first statement in
any block before any of the other statements.RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
16/260
Keywords
Words in the C language whose meaning
are already defined
Keywords cannot be used as variable
names. They are reserved words
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
17/260
32 keywords in C
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed voiddefault goto sizeof volatile
do if static while
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
18/260
Constants
A constant is a value that does not change
C allows us to use the following constants Integer constants
Real or Floating Point (Float) constants
Logical constants
Character constants
String constants
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
19/260
Rules for integer constants
Must have at least one digit Can be either positive or negative. If no sign
precedes the constant, it is positive
Range allowed: 216to 216-1 or (-32768 to
32767)2 bytes Examples: 43, 343, -54, -5678
Cannot have decimal points
For integers that hold up to 4 bytes suffix lor L
Example : 5677188199292L, 67L
67L is forcing the computer to allocate 4
bytes for 67 instead of 2 bytes.
?
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
20/260
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: 0 1 2 3 4 5 6 7 10
int seven = 07; // decimal value 7
int eight = 010; // decimal value 8
What is the decimal equivalent of 0111?RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
21/260
Hexadecimal constants
A leading 0x or 0X can be specified to
indicate that the integer constant is
hexadecimal (base 16).
Counting from 0 through 15 in hex looks
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
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
22/260
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
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 orupper case.
Range -3.4e38 to 3.4e38RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
23/260
Rules for logical constants
A value representing True or False
Non-zero value is true
Zero is false
Example:
1 ( representing a true)
0 (representing a false), 8.7, -45 ( representing a true)
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
24/260
Rules for character constants
Single alphabet, digit or special symbol
Should be enclosed within single invertedcommas
Since characters are internally treated asintegers, the ASCII values of character iswhat is stored internally.
For example ASCII for Ais 65. Range : -128 to 127
Example: C,7,Escape sequence
like\n
?RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
25/260
Escape Sequence
Escape sequences are characters which are
not associated with any particular letter.
For example, a new line character: \n.
It is so called because it uses a \ to escape
the meaning of the character next to it.
What if we want a character constant withvalue ?
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
26/260
Escape sequence character table
\n New line
\b Backspace
\f Form feed
\ Single quote
\\ Backslash
\t Tab
\r Carriage return
\a Alert
\ Double quote
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
27/260
Rules for string constants
A set of characters enclosed within double
inverted commas
Example:
Let us learn C,
\Hello\,
7
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
28/260
#define
#define is used to associate a constant with a
name which can be used in the program.
Syntax:
#define constant-namevalue
Example:
#define PI 3.14
What is the advantage of associating a name
with the constant ?
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
29/260
Console Output
printf() is an inbuilt function used to displayoutput on the console (screen).
General form:
printf(,)
%c: for printing characters
%d for printing integers
%f for floating point
%s for strings
%lf for doubleRAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
30/260
Program to add two numbers (1)
/*Addition of two numbers*/main(){
int a, b, sum;
a=10;
b=2;
sum=a+b;
printf("a=%d, b=%d, sum=%d",
a,b,sum);
}RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
31/260
Console input
scanf() is an inbuilt function used to
accept input that users enter through the
keyboard.
General form:
scanf(,
&)
Note the & symbol. & indicates
address.
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
32/260
Program to add two numbers (2)
/*Addition of two numbers*/
main(){
int a, b, sum;
printf("please enter the value ofa and b");
scanf("%d%d",&a,&b);
sum=a+b;
printf("a=%d, b=%d, sum=%d",a,b,sum);
}
Read and store the
values entered into
memory location
allocated for a and b.
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
33/260
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 GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
34/260
Scope of variables
Global
-- declared outside all functions
-- accessible to all statements in theprogram
Local
declared inside functions accessible to statements within the
function where declared
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
35/260
Example
int j=10;main(){
int a=20;
printf("a=%d, a);
printf(j=%d, j);
}
fun(){
printf("a=%d, a);printf(j=%d, j);
}
Some other function
Global variable
Local variable
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
36/260
Storage Class Specifiers
Variables have data types and storageclasses associated with them
A variables storage class denotes
where the variable will be stored (memory /CPU registers)
what its default value will be (that is, if novalue is assigned)
the scope of the variable
the lifespan of the variable
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
37/260
Types of Storage Class Specifiers
automatic
register
static
externWe will deal with this in the functions chapte
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
38/260
Automatic storage class
Storage: memory
Default value: unpredictable value /
garbage
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
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
39/260
Register storage class
Storage: CPU registers
Default value: unpredictable value / garbage
Scope: local to the block where it is defined
Lifespan: till the control remains in the blockwhere it is defined
Example: register int sum;
Advantage in declaring a variable as registerstorage class is faster access. Variables that
are used very often can be declared as this.
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
40/260
Compilation model
RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
41/260
Learning Outcomes
OperatorsType Conversion
Flow Control Statements
1RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
42/260
Operators
Arithmetic Binary
Arithmetic Unary
Relational
Logical
Bitwise
Conditional
Assignment
A symbol that denotes an operationthat can be performed on some data
2RAGHUDATHESH GP
C BASICS
ASST PROF
A ith ti Bi
-
8/13/2019 Basics Of C Program
43/260
Arithmetic Binary
Operation Operator Example Result
Addition + a+b 30
Subtraction - a-b -10
Multiplication * a*b 200
Division / a/b 0
Modulo % 10%20 10
Assume the following declaration:
int a=10,b=20;
20) 10( 0
- 0
10
Back to
School
Applicable only to integral types. The sign of the result is the
same as that of the numerator.3RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
44/260
Arithmetic Unary
Sign Operator: + -
Example: +5, -5
Increment and Decrement by 1 ++ --
Pre-increment
y=++x; (x=x+1; and y=x;)
Post-increment
y=x++; (y=x; and x=x+1;)4RAGHUDATHESH GP
C BASICS
ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
45/260
Relational operators
Operators used tocompare two operands(variables, constants orexpressions)
Characters can becompared as well
These operators areused extensively withflow control statements.
Operator Meaning
< less than
> greater than
= greater than
or equal to
== equal to
!= not equal toExamples:
a!=b, a
-
8/13/2019 Basics Of C Program
46/260
Logical Operators: &&
To be used when a statement or set ofstatements are to be executed based onwhether two expressions are true
The expression on the RHS will beevaluated only if the expression on theLHS is true.
Example: (x>10)&&(y
-
8/13/2019 Basics Of C Program
47/260
Logical Operators: ||
To be used when a statement or set ofstatements are to be executed based onwhether at least any one of two
expressions are true The expression on the RHS will be
evaluated only if the expression on theLHS is false.
Example: (x>10)||(y
-
8/13/2019 Basics Of C Program
48/260
Truth table for && and ||
expression 1 expression 2 exp1&&exp2 exp1||exp2
0 0 0 0
0 non-zeronumber
0 1
non-zero
number
0 0 1
non-zero
number
non-zero
number
1 1
0 implies False and 1 (or any non-zero number) implies true8RAGHUDATHESH GP
C BASICS
ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
49/260
Logical operators
Logical not: !
to used when the truth value of an expression
is to be reversed
Example: !(x>10)
9RAGHUDATHESH GP
C BASICS
ASST PROF
-
8/13/2019 Basics Of C Program
50/260
C BASICS
-
8/13/2019 Basics Of C Program
51/260
~
~1 00000001 (1s complement)1s complement11111110
How to find the decimal equivalent of 11111110?
Since the sign bit is 1 the number is negative.
To get the decimal value ofve number get the binary
equivalent of 2s complement and convert it to decimal
2s complement -( 1s complement + 1)
1s complement of 11111110 0000000100000001
+ 1
-------------
00000010 decimal value 2. Hence the number is -2.
Back to School
Sign bit
11RAGHUDATHESH GP
C BASICS
ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
52/260
Conditional operators
? :
Also known as ternary operators as they work onthree operands
condition ? expression 1 : expression 2
Example: z=x>y?10:15
If condition results in true valueexecute expression 1
If condition results in false value
execute expression 2
12RAGHUDATHESH GP
C BASICS
ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
53/260
Assignment operator
=
variable=expression;
Assigns the value of the expression to the
variable
Examples: a=b, a=10, a=x+y, a=x++,
a=++x
13RAGHUDATHESH GP
C BASICS
ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
54/260
Compound Operators
expression equivalentx=x+1 x+=1
x=x-1 x-=1
x=x*(5+10) x*=(5+10)x=x/(5+10) x/= (5+10)
x=x%20 x%=20
+= -= *= /= %= >>= >>>=
-
8/13/2019 Basics Of C Program
55/260
sizeof
Returns the number of bytes the operand
occupies in memory.
Example:
sizeof(float)
sizeof(2)
int x=9;
sizeof(x) ;
15RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
56/260
Predict the output
1.printf(%d, -5%-3);
2.printf("%d",10j) && (j++>i);
printf("%d",j);5.printf(%d,!-1);
16RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
57/260
Conversions
What happens when two variables of differentdata types are used in an expression?
For example, what happens when a variable
of type int is added to a variable of type float?
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.
17RAGHUDATHESH GP ASST PROF
I li it iC BASICS
-
8/13/2019 Basics Of C Program
58/260
Implicit conversionThe implicit conversion in the direction
indicated happens automatically to one of theoperands when the operands of different typesare used.
charintlong intfloatdouble
If one of the operands is signed, the other is
automatically converted to signed.
When a variable of type int is added to avariable of type float, implicit type conversion
takes place where the variable of type int is
promoted to a float before the operation is done.18RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
59/260
Type Casting
Implicit conversion is done by the compiler
automatically.
Sometimes we may need to change
implicit behavior
In such cases we must explicitly request
the compiler by using a cast operator.
Cast operator: (datatype)
19RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
60/260
Example
int i=10, j=20;
float f;
f=i/j;
printf(%f, f); prints 0.0
But
f=(float)i/j;prints 0.500000
Casting i to float type.20RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
61/260
Predict the output
char c=127;
char c1=c+2;
printf("%d",c1);
char c=127;
printf("%d",c+2);
21RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
62/260
PrecedenceOperators Associativity
--------------------------------------------------------[] . () -> . 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
unary
22RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
63/260
Control Statements
Statements that enable us to order thesequence of flow of a program.
Decision control statements
ifstatement switch statement
Loopswhilestatement forstatement
do-whilestatement
23RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
64/260
if
if (condition is true)
execute this statement;
if (condition is true)
{
execute statement 1;
execute statement 2;
execute statement n;
}24RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
65/260
Examples for if
if (rate
-
8/13/2019 Basics Of C Program
66/260
if else if (condition is true)
execute this statement;
else
execute this statement;
if (condition is true){
execute statement 1;execute statement 2;
execute statement n; }
else{execute statement n+1;
execute statement n+2;
execute statement n+m; }26RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
67/260
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){printf(You do not have to pay tax.);
printf(But you need to pay asurcharge.);
}else
printf(You have to pay tax.);
27RAGHUDATHESH GP ASST PROF
s itchC BASICS
-
8/13/2019 Basics Of C Program
68/260
switch switch (integer expression 1){
case integer constant 1:statement 1;
statement 2;
statement n;
default:
statement n+1;
statement n+2;
statement n+m;
}
Can appear0, 1 or more
times for
different
constantvalues
Can appear 0or 1 time
28RAGHUDATHESH GP ASST PROF
switch exampleC BASICS
-
8/13/2019 Basics Of C Program
69/260
/* This is a menu-driven program forbasic arithmetic operations between twonumbers*/
main(){
int a,b,i;
printf("enter 2 integer numbers separatedby a blank space: ");
scanf("%d%d",&a,&b);
printf("please enter \n 1 to add\n 2 tosubtract\n 3 to divide\n 4 tomultiply\n 5 for modulo\n");
scanf("%d",&i);
switch example
cal1.c 29RAGHUDATHESH GP ASST PROF
switch(i){C BASICS
-
8/13/2019 Basics Of C Program
70/260
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 multiplicationis :%d ",(a*b));
case 5: printf("Result of modulo is :%d
",(a%b));
default:printf(Inappropriate valueentered");
}
} 30RAGHUDATHESH GP ASST PROF
executionC BASICS
-
8/13/2019 Basics Of C Program
71/260
execution
Execution path 1 :
enter 2 integer numbers separated by a blankspace: 12 2
please enter
1 to add
2 to subtract3 to divide
4 to multiply
5 for modulo
3
Result of division is :6 Result of multiplication is :24
Result of modulo is :0
Inappropriate value entered
You enter this
You enter this
31RAGHUDATHESH GP ASST PROF
Execution path 2 :C BASICS
-
8/13/2019 Basics Of C Program
72/260
Execution path 2 :
enter 2 integer numbers separated by a blank
space: 10 5
please enter1 to add
2 to subtract
3 to divide
4 to multiply
5 for modulo
1
Result of addition is :15 Result of subtraction is :5Result of division is :2
Result of multiplication is :50 Result of modulo is :0
Inappropriate value entered
You enter this
You enter this
32RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
73/260
Fall through problem
Do you see the problem ?
To correct this problem break is used at
the end of each case statement.
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.
33RAGHUDATHESH GP ASST PROF
switch(i){cal2.c
C BASICS
-
8/13/2019 Basics Of C Program
74/260
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));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");
}} 34RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
75/260
Execution
enter 2 integer numbers separated by a blank space:12 4
please enter
1 to add
2 to subtract3 to divide
4 to multiply
5 for modulo
2
Result of subtraction is :8
You enter this
You enter this
35RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
76/260
Example: case without any statementC BASICS
-
8/13/2019 Basics Of C Program
77/260
Example: case without any statement
main(){
int a,b;char i;
printf("enter 2 integer numbersseparated by a blank space: ");
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 tomultiply\n o for modulo\n any otherchar to exit\n");
scanf("%c",&i);?
cal3.c
37RAGHUDATHESH GP ASST PROF
i h(i){
C BASICS
-
8/13/2019 Basics Of C Program
78/260
switch(i){
case 'a':
case 'A': printf("Result of additionis :%d ",(a+b));
break;
case 's':
case 'S': printf("Result ofsubtraction is :%d ",(a-b));
break;
case 'd':
case 'D': printf("Result of divisionis :%d ",(a/b));
break;
Fall through
Fall through
Fall through
38RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
79/260
case 'm':
case 'M': printf("Result ofmultiplication is :%d ",(a*b));
break;
case 'o':
case 'O': printf("Result of modulois :%d ",(a%b));
break;
default: exit();
}
}
Fall through
Fall through
Exits out of the program
39RAGHUDATHESH GP ASST PROF
hil lC BASICS
-
8/13/2019 Basics Of C Program
80/260
while-loop
while(condition is true)statement;
while(condition is true){
statement 1;
statement 2;
statement n;
}
40RAGHUDATHESH GP ASST PROF
E l 1C BASICS
-
8/13/2019 Basics Of C Program
81/260
Example 1
/* program to display numbers divisibleby 2 and 3 between 1 to 100 */
main()
{
int i=1;while(i!=100){
if(i%2==0 && i%3==0)
printf("%d, ",i);
i++;}
}
div1.c
41RAGHUDATHESH GP ASST PROF
E l 2C BASICS
-
8/13/2019 Basics Of C Program
82/260
Example 2Suppose for our calculator program you wantto continue to display the menu until user exits,in such case while can be used.
main(){
int a,b;
char i;
int j=1;
while(j){
printf("enter 2 integer numbersseparated by a blank space: ");
scanf("%d%d",&a,&b);
New code added
cal4.c
42RAGHUDATHESH GP ASST PROF
switch(i){C BASICS
-
8/13/2019 Basics Of C Program
83/260
( ){
//same code
}
printf("\n enter 0 to stop");scanf("%d",&j);
} // end of while loop
}
New code added
43RAGHUDATHESH GP ASST PROF
d hilC BASICS
-
8/13/2019 Basics Of C Program
84/260
do-while
do-while is same as while with the only exceptionthat the condition is checked only at the end of
the loop.
Therefore do-while guarantees that the statementwithin the loop will execute at least once.
do{
statement(s)
}
while(condition);
44RAGHUDATHESH GP ASST PROF
T t!C BASICS
-
8/13/2019 Basics Of C Program
85/260
Try out!
How will you change the while-loop of thecalculator program to do-while loop ?
You may find that the do-while loop is more
appropriate in this case since we definitely
need the menu to be displayed at least once!
45RAGHUDATHESH GP ASST PROF
forC BASICS
-
8/13/2019 Basics Of C Program
86/260
for
In example 1 of the while loop, we saw thatwe set up an initial value for int i and thenexecuted the loop until i reached certainvalue, incrementing is value by 1 each time.
This can be more simply achieved through forloop.
for(initialize var;condition;increment var){
statement(s);
}
46RAGHUDATHESH GP ASST PROF
E l di 2C BASICS
-
8/13/2019 Basics Of C Program
87/260
Example
/* program to display numbersdivisible by 2 and 3 between 1 to100 this time using for loop */
main(){int i;
for(i=0;i
-
8/13/2019 Basics Of C Program
88/260
Count backwards/* factorial of a number*/
main(){
int num,i,f;
printf("enter a number");
scanf("%d",&num);f=num;
for(i=num-1;i>1;i--)
f=f*i;
printf("%d",f);}
48RAGHUDATHESH GP ASST PROF
b k i lC BASICS
-
8/13/2019 Basics Of C Program
89/260
break in loops
The keywordbreak is used to exit out ofthe loop anytime even when if it does not
satisfy the loop conditions.
When break is encountered the controljumps to the first statement after the loop.
49RAGHUDATHESH GP ASST PROF
ExampleC BASICS
-
8/13/2019 Basics Of C Program
90/260
p/* program to determine if an integerentered by the user is a prime number */
main(){int num,j,i,flag=1;
printf("enter an integer ");
scanf("%d",&num);
j=num/2;
for (i=2;i
-
8/13/2019 Basics Of C Program
91/260
continue in loop
The continue statement is used to skip therest of the statements in the loop and carry
on with the next iteration.
In other words, when continue isencountered, the control goes to the
beginning of the enclosing loop.
51RAGHUDATHESH GP ASST PROF
ExampleC BASICS
-
8/13/2019 Basics Of C Program
92/260
Example/* program to determine if an integergreater than 100 entered by the useris a prime number */
main(){
int num,j,i,flag=1;
while(1){
printf("enter an integer greater than100 ");
scanf("%d",&num);
if(num
-
8/13/2019 Basics Of C Program
93/260
for (i=2;i
-
8/13/2019 Basics Of C Program
94/260
Learning Outcomes
Function
Argument Passing
static variable
Command line argumentsRecursion
1RAGHUDATHESH GP ASST PROF
FunctionC BASICS
-
8/13/2019 Basics Of C Program
95/260
Function
A function is a block of code that performsa particular task.
A function can be called from the same oranother function whenever required. Hence
we can avoid rewriting the same code. Italso improves the readability of theprogram.
Function may take some input in the formof parameters and sent out some output inthe form of return value.
2RAGHUDATHESH GP ASST PROF
Example1: function without argumentd t t
C BASICS
-
8/13/2019 Basics Of C Program
96/260
and return type
/* Using function :program to determineif an integer greater than 100entered by the user is a prime number*/
int num;
main(){while(1){printf("enter an integer greater than
100 ");scanf("%d",&num);if(num
-
8/13/2019 Basics Of C Program
97/260
p p{int j,i,flag=1;
j=num/2;
for (i=2;i
-
8/13/2019 Basics Of C Program
98/260
return value
Did you notice the warnings that thecompiler throws?
Warning primefun.c 12: Function shouldreturn a value in function main
Warning primefun.c 27: Function shouldreturn 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.
5RAGHUDATHESH GP ASST PROF
Function declarationC BASICS
-
8/13/2019 Basics Of C Program
99/260
Function declaration return_type function_name(argument-
list)Where argument-list is
Data-type var-name1, Data-type var-name2, Data-type var-namen
If return_type is not specified it is assumed to bean int. argument-list can contain 0 one or more
arguments.
function_name must be unique. It should not clashwith any variable name or other function name.
Variables declared inside the function and theargument-list variables are local to the function.They cannot be accessed outside the function. 6RAGHUDATHESH GP ASST PROF
returnC BASICS
-
8/13/2019 Basics Of C Program
100/260
return
The returnstatement is used to return avalue from a function.
When return is encountered the control go
back to the calling function. Example: return (a);
return (15);
return 0;
return; Used with void. Does not return anything!
7RAGHUDATHESH GP ASST PROF
Correcting the prime number codeC BASICS
-
8/13/2019 Basics Of C Program
101/260
g p By adding return 0;at the end ofmain()andprintprime() function we can eliminate the
warnings.main(){
return 0;}
printprime(){
return 0;
}
We need to make return type of printprime as void
not int.
primef2c
8RAGHUDATHESH GP ASST PROF
PrototypingC BASICS
-
8/13/2019 Basics Of C Program
102/260
Prototyping Complier assumes that any C function
would return a type int.
Any function that returns types other thanint must inform the compiler by what is
called prototyping. Prototyping is declaring the function that
needs to be called within the callingfunction.
Note that declaration of a function isdifferent from definition of a function.
9RAGHUDATHESH GP ASST PROF
Changing the prime number code
C BASICS
-
8/13/2019 Basics Of C Program
103/260
Changing the prime number code
primef3.c
int num;int main(){void pprime();while(1){
printf("enter an integer greater than100 ");scanf("%d",&num);if(num
-
8/13/2019 Basics Of C Program
104/260
Function with parametersC BASICS
-
8/13/2019 Basics Of C Program
105/260
Function with parameters
It is possible for the calling function topass values into the called functionthrough what is called parameters orarguments.
Suppose we declare numvariable insidethemain(), then we will need to passnum into pprime() function since num will
be local to themain() function and so itnot be accessible to thepprime()function.
12RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
106/260
-
8/13/2019 Basics Of C Program
107/260
Example of function returning aC BASICS
-
8/13/2019 Basics Of C Program
108/260
value of importance
/* program that has a function whichcalulates the gross salary given thebasic salary*/
main(){double basic,gross;doublecalculateGross(double basic);printf("enter basic salary ");
scanf("%lf",&basic);gross= calculateGross(basic);printf("Gross=%lf",gross);}
gross.c
15RAGHUDATHESH GP ASST PROF
doublecalculateGross(double basic){double hra,ta,da, gross;
C BASICS
-
8/13/2019 Basics Of C Program
109/260
double hra,ta,da, gross;da=0.5 * basic;
hra=0.1 *basic;if(basic=10000 && basic
-
8/13/2019 Basics Of C Program
110/260
Suppose we attempt to write a code that printsthe number of times a function is called.
main(){void callMe();callMe();callMe();}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 notinitialized.
count1.c
17RAGHUDATHESH GP ASST PROF
If we initialize count to 0 then print
you called me 1 times three
C BASICS
-
8/13/2019 Basics Of C Program
111/260
you called me 1 times threetimes.
main(){void callMe();callMe();callMe();}
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
be retained.
18RAGHUDATHESH GP ASST PROF
static variableC BASICS
-
8/13/2019 Basics Of C Program
112/260
static variable
Solution to this is to declare the countvariable as static variable.
Static variables are automatically
initialized the first time to 0. It retains the value between the function
calls.
static can be declared only with thefunction.
19RAGHUDATHESH GP ASST PROF
Count example correctedC BASICS
-
8/13/2019 Basics Of C Program
113/260
Count example corrected
main(){void callMe();callMe();callMe();
callMe();}void callMe(){static int count;count++;printf("you called me %d times\n" ,
count);}
Prints:you called me 1 timesyou called me 2 timesyou called me 3 times
20RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
114/260
void f(int i,int j){printf("In f() before changing : value
C BASICS
-
8/13/2019 Basics Of C Program
115/260
of i=%d and value of j=%d\n", i,j);
i++;j++;
printf("In f() after changing: value ofi=%d and value of j=%d\n", i,j);}
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
After calling f(): value of i=0 and value of j=0
Result of execution
22RAGHUDATHESH GP ASST PROF
ObservationC BASICS
-
8/13/2019 Basics Of C Program
116/260
Observation
What do you observe? The parameter values changed in the
called function code are not reflected in the
calling function. This is because the parameters arepassed
by valueto the function.
Both functions have their own copy of thevariables. Only the values of the variablesof the calling function get copied to thevariables of the called function
23RAGHUDATHESH GP ASST PROF
1000
Addressmain()i
C BASICS
-
8/13/2019 Basics Of C Program
117/260
MEMORY
1001
1002
1003
1004
1005
j 0
0Call f(0,0)
f()i
j
0
0
i++;j++;
1
1i
j
i
j24RAGHUDATHESH GP ASST PROF
main()C BASICS
-
8/13/2019 Basics Of C Program
118/260
i=0
j=0Calls
f()
1000
1001
In memory
i=0
j=0
2000
2001
i++;
j++;
i=1
j=1
Value of i and j
in 1000 and1001 remain
the same!
25RAGHUDATHESH GP ASST PROF
Call by referenceC BASICS
-
8/13/2019 Basics Of C Program
119/260
Call by reference
What should be done so that the changedvalues of i and j are reflected in the callingfunction?
1. There should be some way in which we
pass the addresses of the variables of iand j from the calling function to thecalled function.
2. The called function should receive thesevariables in a way such that theypointtovalues rather than just receiving thevalues.
26RAGHUDATHESH GP ASST PROF
Call by reference contC BASICS
-
8/13/2019 Basics Of C Program
120/260
Call by reference cont
&variable-namerepresents the addressof the variable.
Address of a variable is of integer type.
We need a special kind of variable that iscapable 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.
27RAGHUDATHESH GP ASST PROF
Introduction to pointersC BASICS
-
8/13/2019 Basics Of C Program
121/260
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:
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;28RAGHUDATHESH GP ASST PROF
Getting the address and valueC BASICS
-
8/13/2019 Basics Of C Program
122/260
Getting the address and value
*variable-namereturns the value storedin the address that variable-name points to.
variable-namereturns the address value.
Example:double i=10;
double *p=&i;
printf(%lf,*p);
printf(%d,p);
Prints 10
Prints the address
point.c29RAGHUDATHESH GP ASST PROF
Question ?C BASICS
-
8/13/2019 Basics Of C Program
123/260
Question ?
It is important to specify the appropriate data-type
in the syntax if you want to use pointer arithmetic.
You can use ++ andoperators on the pointer
which allows pointer to jump to next location.
Whether the jump has to be 1 byte , 2 bytes , 4bytes, 8 bytes or 10 bytes is determined by the
data-type of the pointer.
?
The data-type of a pointer variable is always
integer. Then what is the significance of
specifying data-type in the declaration
syntax?
More details on it in the pointers part
of the C story.
30RAGHUDATHESH GP ASST PROF
Call by referenceC BASICS
-
8/13/2019 Basics Of C Program
124/260
Call by reference/* program : call by value demo */void main(){void f(int *i,int *j);
int i=0, j=0;
printf("Before calling f(): value ofi=%d and value of j=%d\n", i,j);
f(&i,&j);printf("After calling f(): value ofi=%d and value of j=%d\n", i,j);
}
31RAGHUDATHESH GP ASST PROF
void f(int *i int *j)
C BASICS
-
8/13/2019 Basics Of C Program
125/260
void f(int i,int j){
printf("In f() before changing : valueof i=%d and value of j=%d\n", *i,*j);
(*i)++;
(*j)++;
printf("In f() after changing: value of
i=%d and value of j=%d\n", *i,*j);}
32RAGHUDATHESH GP ASST PROF
Challenge question?C BASICS
-
8/13/2019 Basics Of C Program
126/260
g q
In the function f() of the previous slide, weused brackets to increment the values of i
and j.
(*i)++;(*j)++;
What will happen if the brackets are
removed? Will the effect be the same?*i++;
*j++;33RAGHUDATHESH GP ASST PROF
RecursionC BASICS
-
8/13/2019 Basics Of C Program
127/260
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 intoinfinite loop.
int i;main(){f();}
int f(){i++;if(i>5) return ;f();}
int i;main(){f();}
int f(){f();}
Without termination
condition : infinite loop
Termination
condition
specified.
Executes
successfully.
34RAGHUDATHESH GP ASST PROF
Prime number using recursionC BASICS
-
8/13/2019 Basics Of C Program
128/260
g
/* prime number using recursion */int num,k;main(){printf("enter an integer ");
scanf("%d",&num);k=prime(2);if(k==0)printf("not prime");elseprintf("prime");}
35RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
129/260
Flow
C BASICS
-
8/13/2019 Basics Of C Program
130/260
Assume num=9prime(2) {if(num%i==0) return 0; 9%2!=0i++;2++ 3if(i>num/2) return 1;3>(9/2) No!else
prime(i); prime(3) }
{if(num%i==0) return 0; 9%3i++;
if(i>num/2) return 1;else
prime(i);}
Return value: 0
1
2 3
Return value: 0
4
37RAGHUDATHESH GP ASST PROF
Attempt another exampleC BASICS
-
8/13/2019 Basics Of C Program
131/260
p p
Write a non-recursive code to generate 10
Fibonacci numbers.
38RAGHUDATHESH GP ASST PROF
Fibonacci numbersNon-recursive Recursive
C BASICS
-
8/13/2019 Basics Of C Program
132/260
main(){
int f1=0,f2=1,f3,i;printf("%d, %d,",f1,f2);for(i=0;i8) return;
f3=f1+f2;f1=f2; f2=f3;
printf("%d,", f2);count++;fibo(f1,f2);}fib.c
fibr.c
Non recursive Recursive
Termination condition
39RAGHUDATHESH GP ASST PROF
Use of recursionC BASICS
-
8/13/2019 Basics Of C Program
133/260
Recursive programs sometime seem ratherdifficult in comparison to non-recursive ones.
But in some cases it is actually easier to use
recursion.
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
-
8/13/2019 Basics Of C Program
134/260
main(){int num, res;printf("enter a number");scanf("%d",&num);res=fact(num);
printf("%d",res);}int fact(int n){int f;
if(n==0) return 1;f=n*fact(n-1);return f;} 41RAGHUDATHESH GP ASST PROF
Flownum=3
C BASICS
-
8/13/2019 Basics Of C Program
135/260
num 3
fact(3)
{int f;if(n==1) return 1; n=3f=n*fact(n-1); 3*fact(2)return f;}
{int f;if(n==1) return 1; n=2f=n*fact(n-1); 2*fact(1)return f;}
{int f;if(n==1) return 1; n=1f=n*fact(n-1);return f;}
Return 1
Return 2
Return 6
42RAGHUDATHESH GP ASST PROF
Challenge!C BASICS
-
8/13/2019 Basics Of C Program
136/260
g
Write recursive code to find the sum ofdigits
First attempt to write the recursive
formula. Then write the code.
43RAGHUDATHESH GP ASST PROF
Word of caution!C BASICS
-
8/13/2019 Basics Of C Program
137/260
Recursive code may be difficult tounderstand and debug. Hence it should be
used only in places where it makes the
overall program simpler.Recursive code adds to overhead of
multiple function calls.
44RAGHUDATHESH GP ASST PROF
Learning OutcomesC BASICS
-
8/13/2019 Basics Of C Program
138/260
Arrays
Single dimensional
Multidimensional
Console IO
Unformatted IO
Formatting
1RAGHUDATHESH GP ASST PROF
ArraysC BASICS
-
8/13/2019 Basics Of C Program
139/260
Suppose you have to work with 100numbers. Imagine the difficulty and time
taken to type in names of 100 variable
names. Arrays are here for our rescue!
Array is a collection of elements of same
data type.
2RAGHUDATHESH GP ASST PROF
Declaration and Initialization of
Single dimensional array
C BASICS
-
8/13/2019 Basics Of C Program
140/260
Single dimensional array
An array that is a list of elements is a singledimensional array.
data-type variable-name[size]
Example: double prices[10];
A single dimensional array can be initialized withthe declaration statement as shown in theexample 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 notdeclared as static) contains garbage values.
3RAGHUDATHESH GP ASST PROF
Accessing arraysA l t d i th i d
C BASICS
-
8/13/2019 Basics Of C Program
141/260
Array elements are accessed using the indexposition. Index position begins from 0.
main(){float price[]={120.50,100,175,50};int i;
for(i=0;i
-
8/13/2019 Basics Of C Program
142/260
When the array declaration statement isencountered, memory required for the
array is calculated and contiguous
memory space is allocated. For example, for int size[4]; 4*2=8 bytes contiguous memory space is
allocated.
1000 1002 1004 10085RAGHUDATHESH GP ASST PROF
Strings An array of char is a string
C BASICS
-
8/13/2019 Basics Of C Program
143/260
An array of char is a string.
charc[]={R,i,t,c,h,i,e,\0};
is same as
char c[]=Ritchie;
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:scanf(%s,c);
printf(%s,c);
Note the absence of & sign.Why? Because the value of
is the value of the starting
address of the array !
6RAGHUDATHESH GP ASST PROF
Two dimensional arrayC BASICS
-
8/13/2019 Basics Of C Program
144/260
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:
int emp_sal[3][2]; can be viewed as:
int k[2][2]={ {12,34},
{13,35}};
int k[][2]={ {12,34},{13,35}} ;
int k[][2]={ {12,34,13,35};
3 rows and
2 columns
7RAGHUDATHESH GP ASST PROF
/* getting the employee numbers andsalaries of three employees into a 2-dimensional array and displaying them */
C BASICS
-
8/13/2019 Basics Of C Program
145/260
y p y g /main(){
int emp_sal[3][2],i,j;for(i=0;i
-
8/13/2019 Basics Of C Program
146/260
What will happen if array is accessedbeyond its last index?
What is the initial value of array elements
that are not initialized? What will happen index isve?
9RAGHUDATHESH GP ASST PROF
Functions and arraysC BASICS
-
8/13/2019 Basics Of C Program
147/260
main(){
int a[]={1,2,3,4};int i;f(a);for(i=0;i
-
8/13/2019 Basics Of C Program
148/260
main(){af(a1000)}
1
2
3
4f(a){
a[i]++;}
1000
1002
1004
1008
2
3
4
5
&a[0]
&a[1]
&a[2]
&a[3]
11RAGHUDATHESH GP ASST PROF
Array and pointerC BASICS
-
8/13/2019 Basics Of C Program
149/260
A pointer variable can be assigned toarrays base address and using the pointer
increment operator all the array elements
can be accessed. Next slide shows the same code that we
wrote in the previous slide using pointers.
Like ++ operator, - - operator can also beused to jump one position before.
12RAGHUDATHESH GP ASST PROF
main(){int a[]={1,2,3,4};int i;
C BASICS
-
8/13/2019 Basics Of C Program
150/260
int i;
f(a);for(i=0;i
-
8/13/2019 Basics Of C Program
151/260
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 baseaddress of row 2 etc.
a1
2
3
4
5
614RAGHUDATHESH GP ASST PROF
Other wonders!C BASICS
-
8/13/2019 Basics Of C Program
152/260
int a[]={1,2,3,4};1.*(a+1) a[1]22.*(2+a)2[a] a[2]3
inta[3][2]={{1,2},{3,4},{5,6}};
a[1][1]*(a[1]+1)*(*(a+1)+1)
15RAGHUDATHESH GP ASST PROF
String and PointerC BASICS
-
8/13/2019 Basics Of C Program
153/260
main(){chars[]="Shankara";
char *p="Shankara";
printf("%s",s);
printf("%s",p);
}
Both the print statements
print Shankara.
s is an array of characters
p is a pointer to the first
character where Shankara isstored.
Note that the printf()
statement with %s prints the
string char by char withouthaving to increment the array
index or pointer position.
16RAGHUDATHESH GP ASST PROF
Strings and pointerC BASICS
-
8/13/2019 Basics Of C Program
154/260
Array of strings can be represented in twoways:
char str[][3]
char *str[];(array ofpointers to string)
First way is preferred to read the stringfrom the console.
Second way is the more preferred way tomanipulate and print!
17RAGHUDATHESH GP ASST PROF
main(){char
names1.c
C BASICS
-
8/13/2019 Basics Of C Program
155/260
n1[][4]={"John","Mary","Sita","Rama"};
int i;char*n2[]={"John","Mary","Sita","Rama"};for(i=0;i
-
8/13/2019 Basics Of C Program
156/260
pointers to string
main(){char *names[4];int i;
for(i=0;i
-
8/13/2019 Basics Of C Program
157/260
main(){char names[6][4];char *nm[4];int i;
for(i=0;i
-
8/13/2019 Basics Of C Program
158/260
Command line arguments are the datathat we can pass through command-line.
The command line arguments arereceived through a special kind of main()function:
main(int argc, char*argv[])
argc holds the number of arguments and
argv contains the address of the stringspassed from the command line.
21RAGHUDATHESH GP ASST PROF
Example command-line arguments
C BASICS
-
8/13/2019 Basics Of C Program
159/260
main(int argc, char *argv[]){int i;
for(i=0;i
-
8/13/2019 Basics Of C Program
160/260
IO is Input-Output. IO operations deal withreading from various input devices like
keyboard, disk, network and writing to various
output devices like VDU, disk, network etc.
C programming language by itself does notsupport 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.
23RAGHUDATHESH GP ASST PROF
Console IOC BASICS
-
8/13/2019 Basics Of C Program
161/260
Reading from the keyboard and writing on to thescreen.
Two types of functions
Unformatted
Formatted Formatted functions allows us to display the data
in the way that we want. For example, if we wantto display price with only 2 decimal places, thenit is possible only with the formatted IOfunctions.
24RAGHUDATHESH GP ASST PROF
Unformatted functions to read char
getchar(), getche(), getch()
C BASICS
-
8/13/2019 Basics Of C Program
162/260
getchar(), getche(), getch()
getche(), getch()return the input fromthe console. Unlike scanf(), they doesnt wait
for the enter button to be clicked before they
can consume the value typed in. getche() echoes( or displays ) the character
typed in.
getchar() also echoes( or displays ) thecharacter typed in but requires enter button to
be clicked like scanf().25RAGHUDATHESH GP ASST PROF
Back to calculator codemain(){int a b;
C BASICS
-
8/13/2019 Basics Of C Program
163/260
int a,b;
char i;printf("enter 2 integer numbers
separated by a blank space: ");scanf("%d%d",&a,&b);getchar();printf("please enter \n a to add\n
s to subtract\n d to divide\n m to
multiply\n o formodulo\n any other char to exit\n");
i=getchar(); } 26RAGHUDATHESH GP ASST PROF
Unformatted functions to print char
C BASICS
-
8/13/2019 Basics Of C Program
164/260
putch(char c), putchar(char c) Both are same and both print character on
the screen.\
Example:
putch(A);
char ch=B;putchar(ch);
27RAGHUDATHESH GP ASST PROF
Unformatted functions for strings
C BASICS
-
8/13/2019 Basics Of C Program
165/260
gets() and puts() gets() is used to read string from the
console and puts() is used to print.
scanf() does not work properly in caseswhere 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.
28RAGHUDATHESH GP ASST PROF
Difference scanf() and gets()
main(){
C BASICS
-
8/13/2019 Basics Of C Program
166/260
main(){
char clr[10];
printf("enter a color\n");scanf("%s",clr);
printf(" \n %s",clr);}
main(){char clr[10];
puts("enter a color\n");gets(clr);puts(clr);}
enter a color
light green
light
You enter this
enter a color
light blue
light blue
You enter this
29RAGHUDATHESH GP ASST PROF
Formattingprintf()can be used to format the output
C BASICS
-
8/13/2019 Basics Of C Program
167/260
p () p
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) 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
as it is
30RAGHUDATHESH GP ASST PROF
Formatting charactersD C i h
C BASICS
-
8/13/2019 Basics Of C Program
168/260
Data type Conversion char
short signed %d or %i
short unsigned %u
long signed %ld
long unsigned %lu
float %f
double %lf
signed and unsigned char %cstring %s
31RAGHUDATHESH GP ASST PROF
Format StringC BASICS
-
8/13/2019 Basics Of C Program
169/260
%[special_char][width] ][.precision]conversion char
special_char :
- : Left justify this argument
+: 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
32RAGHUDATHESH GP ASST PROF
ExampleC BASICS
-
8/13/2019 Basics Of C Program
170/260
main(){int i=10;double d=1245.678;signed short j=-10;
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);}
Result:
= 10= +10
=10
=00010
= -10=1245.68
33RAGHUDATHESH GP ASST PROF
Learning Outcomes
P i t f h t h
C BASICS
-
8/13/2019 Basics Of C Program
171/260
Pointers- summary of what we have seen
so far
Pointer operators
Dynamic memory allocation
Pointer to pointer
Pointer to function
1RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
172/260
Pointers- summary of what we
have seen so far
2RAGHUDATHESH GP ASST PROF
Basics
C BASICS
-
8/13/2019 Basics Of C Program
173/260
int i=10;i: gives the value10&i: gives the address002*(&i): gives the value10
101002
i name
Memory
address
int *j; :pointer to an int
j=&i; :pointer assignment.
j: gives the address of i1002&j: gives the address of j2002*j: give the value of i10
1002
2002
j name
Memory
address
value
value
pointer
3RAGHUDATHESH GP ASST PROF
1-D array and pointersint a[]={1,2,3,4};
11000 a
*a
C BASICS
-
8/13/2019 Basics Of C Program
174/260
a[0],0[a],*a, *a+0 1
a: base array address
1000
a+2: base array address+22 * sizeof(int)
1000+2*2 bytes
1000+4=1004
1
2
3
4
10021004
1006
a +1a +2
a +3
a
*(a +1)
*(a +2)
*(a +3)
int *b;
b=a;
b: base array address o
array a1000*b: value at 1000 1
*(b+1): value at 10022
1000 b2002
4RAGHUDATHESH GP ASST PROF
2-D array and pointersint a[2][2]={{5,6},{7,8}};
C BASICS
-
8/13/2019 Basics Of C Program
175/260
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
2004
1001
1002
5
6
2001
2002
7
8
2004
2006
a
a+1
a[0]*aa[1]*(a+1)
**a
**(a+1)
a[0][1],*(a[0]+1),*(*(a+0)+1) 6 5RAGHUDATHESH GP ASST PROF
Pointer Operators *: value at the address specified by the variable
C BASICS
-
8/13/2019 Basics Of C Program
176/260
: 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
+: addition of a pointer variable and a constantvalue
-: subtraction of pointer and a constant value and
subtraction of two pointers. ==: comparison of pointers
6RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
177/260
Array of pointers Array of pointers to int:
C BASICS
-
8/13/2019 Basics Of C Program
178/260
Array of pointers to int:
int *ptrs[2];int i=10,j=11;
ptrs[0]=&i;
ptrs[1]=&j;
*(ptrs[1]), ptrs[1][0]11
2001
2002
10
11
Array of pointers to int
2001
2002
ptrarr c
8RAGHUDATHESH GP ASST PROF
Pointer to PointerC BASICS
-
8/13/2019 Basics Of C Program
179/260
A pointer variable that points to anotherpointer variable is a pointer to a pointerrepresented by **.
int i=10int *j;
int **k;
j=&i;
k=&j;
**k10
k
2004 1003
j
10
i
k is a pointer to a pointer to an int
9RAGHUDATHESH GP ASST PROF
Pointers to function Like variables, functions also have
C BASICS
-
8/13/2019 Basics Of C Program
180/260
,
addresses. A pointer variable can point to anything in
the memory.
Therefore a pointer variable can point to anaddress of a function too.
The next example maintains a function
pointer which points to a particular functionbased on users input and then later
executes that function through the function
pointer.10RAGHUDATHESH GP ASST PROF
main(){int i;
int f();
i ()Prototype declaration
C BASICS
-
8/13/2019 Basics Of C Program
181/260
int g();
int (*fptr)();printf("type 0 for f() or 1 for g() ");
scanf("%d", &i);
if(i)
fptr=g;
else
fptr=f;
(*fptr)();return 0;
}
Prototype declaration
Function pointer
Assigning function addressto function pointer
Calling function through
function pointer
11RAGHUDATHESH GP ASST PROF
int f(){
printf("f() called");
return 0;
C BASICS
-
8/13/2019 Basics Of C Program
182/260
return 0;
}int g(){
printf("g() called");
return 0;
}
Output:
type 0 for f() or 1 for g() 1
g() called
You type this
12RAGHUDATHESH GP ASST PROF
Dynamic memory allocation Using arrays we can reserve a fixed memory
location
C BASICS
-
8/13/2019 Basics Of C Program
183/260
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
dept having 2 employee would be utter waste ofspace.
In such cases, we can use dynamic memory
allocation that allows us to allocate memorydynamically as and when required instead of
allocating and reserving it straight away.13RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
184/260
main(){int *empno, n,i;
printf("enter the number of employees: ");
C BASICS
-
8/13/2019 Basics Of C Program
185/260
scanf("%d",&n);
empno=(int *) malloc(n*2);
if(empno=='\0'){printf("memory not available");
exit(0);}
else
for(i=0;i
-
8/13/2019 Basics Of C Program
186/260
printf("\nemployee number %d : %d\n", i,
*(empno+i));
}Output:
enter the number of employees: 3
enter the employee number: 5432
enter the employee number: 6453
enter the employee number: 7654
printing all the employee numbersemployee number 0 : 5432
employee number 1 : 6453
employee number 2 : 7654
You enter this
16RAGHUDATHESH GP ASST PROF
Learning Outcomes
Structure and its need
C BASICS
-
8/13/2019 Basics Of C Program
187/260
Structure and its need
Syntax
Memory allocation
Passing structure in function
Pointers and structure
Nesting structure
Union
Difference between struct and union
Syntax
Union of structs 1RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
188/260
Syntax Defining structure:
C BASICS
-
8/13/2019 Basics Of C Program
189/260
struct struct-name{data-type variable-name1;
data-type variable-name2;
data-type variable-namen;
};
Declaring variable of struct-type:
struct struct-name variable-name;
members
3RAGHUDATHESH GP ASST PROF
ExampleC BASICS
-
8/13/2019 Basics Of C Program
190/260
struct employee{int emp_num;
char name[30];
double salary;};
struct employee emp1,emp2;
defining
declaring
4RAGHUDATHESH GP ASST PROF
Accessing membersC BASICS
-
8/13/2019 Basics Of C Program
191/260
Structure members can be accessed using. operator on the structure variable.
Example:
emp1.emp_num, emp2.name Structure members can be initialized
during the declaration as:
struct employeeemp={123,Bobby,345.50};
5RAGHUDATHESH GP ASST PROF
Example- simplestruct emp{int num;
emp1.c
C BASICS
-
8/13/2019 Basics Of C Program
192/260
char name[30];double sal;};struct emp emps;
main(){read();display(); }read(){
printf("enter emp number:");scanf("%d",&emps.num);printf("enter name:");scanf("%s",emps.name); 6RAGHUDATHESH GP ASST PROF
printf("enter salary:");scanf("%lf", &emps.sal); }display(){printf("Displaying data \n");
C BASICS
-
8/13/2019 Basics Of C Program
193/260
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);}Output:enter emp number:123enter name:Kanakaenter salary:12340
Displaying dataemp number: 123emp name: Kanakaemp salary: 12340.00
You enter this
7RAGHUDATHESH GP ASST PROF
Examplearray of structuremain(){struct ball{
ball.c
C BASICS
-
8/13/2019 Basics Of C Program
194/260
int size;char color[30];};struct ball b[3];
int i;for(i=0;i
-
8/13/2019 Basics Of C Program
195/260
Output:
enter size of the ball:12enter the color:greenenter size of the ball:13enter the color:red
enter size of the ball:10enter the color:yellowDisplaying databall size: 12ball color: greenball size: 13ball color: redball size: 10ball color: yellow
You enter this
9RAGHUDATHESH GP ASST PROF
Structure Pointers A pointer variable can be declared that points to a
structure like it points to an ordinary variable
C BASICS
-
8/13/2019 Basics Of C Program
196/260
structure like it points to an ordinary variable.
Example:
struct emp emps={123,"Ganga", 12000};
struct emp *e=&emps;
To access members through structure pointer, aspecial kind of symbol is used.
Example:
enum, ename Structure pointers are required when we pass a
structure variable to a function and we want thechanges made in the variable visible in the callingfunction. 10RAGHUDATHESH GP ASST PROF
struct emp{int num;char name[30];double sal;
emp2.cC BASICS
-
8/13/2019 Basics Of C Program
197/260
double sal;
};main(){struct emp emps={123,"Ganga", 12000};
increment(&emps);display(&emps);}
increment(struct emp *e){e->sal=e->sal*0.10+e->sal;}
123 Ganga 12000
emps.num
emps.name
emps.sal
2001 e
2001 13200
11RAGHUDATHESH GP ASST PROF
display(struct emp *e){printf("Displaying data \n");printf(" emp number: %d\n",e->num);printf(" emp name: %s\n" e >name);
C BASICS
-
8/13/2019 Basics Of C Program
198/260
printf(" emp name: %s\n",e->name);printf(" emp salary: %5.2lf\n",e->sal);}
Output:Displaying dataemp number: 123emp name: Ganga
emp salary: 13200.00
12RAGHUDATHESH GP ASST PROF
Nested structure A structure can have as its member a structure
C BASICS
-
8/13/2019 Basics Of C Program
199/260
variable. Example:struct name{char fname[10];
char lname[10];};struct student{struct name nm;
int rollno;} stud; Note: another way of
declaring structure variable13RAGHUDATHESH GP ASST PROF
main(){printf("enter first and last name: ");scanf("%s%s",stud nm fname stud nm lname);
C BASICS
-
8/13/2019 Basics Of C Program
200/260
stud.nm.fname,stud.nm.lname);
printf("\nenter roll number:");scanf("%d", &stud.rollno);printf("displaying data\n");printf("Name:%s %s\n",stud.nm.fname,stud.nm.lname);printf("roll no %d\n", stud.rollno);}
Output:
enter first and last name: John Ray
enter roll number:12345
displaying data
Name:John Ray
roll no 12345 14RAGHUDATHESH GP ASST PROF
unions Union allows variables of different data
C BASICS
-
8/13/2019 Basics Of C Program
201/260
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 space
can be treated either as int or as char.
Union allows us to choose between types
of data based on the requirement of
application.
15RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
202/260
Difference between struct andunion
a c[0] c[1]
C BASICS
-
8/13/2019 Basics Of C Program
203/260
struct X{int a;
char c[2];
};
union X{
int a;char c[2];
};
a
1000 1002 1003
c[0] c[1]
1004
a
1000 1002c[0] c[1]1001
17RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
204/260
-
8/13/2019 Basics Of C Program
205/260
enum gender{male,female};
enum constants
C BASICS
-
8/13/2019 Basics Of C Program
206/260
main(){enum gender g1,g2;g1=male;g2=female;
print(g1);print(g2);}print(enum gender g){if(g==male)printf("Male \n");else
i f(" l ") }
Output:
Male
Female
Assigning any other value would be an error.
20RAGHUDATHESH GP ASST PROF
Internal working
Internally compiler treats enums as
C BASICS
-
8/13/2019 Basics Of C Program
207/260
Internally compiler treats enums as
integers. Hence the values that enum constants take
start from 0.
In the previous example male is internallystored as 0 and female is 1.
These values can be changed by explicitly :
enum gender{
male=10,female=20};
21RAGHUDATHESH GP ASST PROF
typedef typedef is used to give a different name to a data type.
Let us understand this with an example:
C BASICS
-
8/13/2019 Basics Of C Program
208/260
struct fullname{char fname[10];
char lname[10];
}; To declare variable of the above type
struct fullname n1,n2;If we have many such declarations throughout thecode then typing this could be tedious.
Using typedef, we could just type
name n1,n2; 22RAGHUDATHESH GP ASST PROF
enum gender{male,female };typedef enum gender GEN;
C BASICS
-
8/13/2019 Basics Of C Program
209/260
struct emp{int num;char name[30];double sal;
GENgen;};typedef struct emp EMP;main(){EMP emps={123,"Ganga", 12000, female};increment(&emps);display(&emps);
}
23RAGHUDATHESH GP ASST PROF
increment(EMP *e){e->sal=e->sal*0.10+e->sal;}
C BASICS
-
8/13/2019 Basics Of C Program
210/260
display(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);if(e->gen==male)printf(" Gender: Male");
elseprintf(" Gender: Female");}
24RAGHUDATHESH GP ASST PROF
Learning OutcomesC BASICS
-
8/13/2019 Basics Of C Program
211/260
Preprocessor directives
#define directives
#include directives
Conditional compilation directives
1RAGHUDATHESH GP ASST PROF
Learning OutcomesC BASICS
-
8/13/2019 Basics Of C Program
212/260
Standard Library functions
Standard I/O functions
String functions
Math functions
2RAGHUDATHESH GP ASST PROF
Preprocessor directivesC BASICS
-
8/13/2019 Basics Of C Program
213/260
Preprocessor directivesare special type of
commands that we
include in C source code.
These directives are
processed before
compilation by a special
kind of program called
preprocessor.3RAGHUDATHESH GP ASST PROF
Structure of a C program
Preprocessor commands (directives)
C BASICS
-
8/13/2019 Basics Of C Program
214/260
Preprocessor commands (directives)
Global declarations
Functions
Statements
Variable declaration statements
Constants in statements
IO statements
Comments (any where in the code)
Must be among the f i rst statements of the prog ram. Only
statement before a direct iv e can be ano ther direct ive! 4RAGHUDATHESH GP ASST PROF
Preprocessor directives types
C BASICS
-
8/13/2019 Basics Of C Program
215/260
#definedirective
#includedirective
#undef directive
Conditional compilation directives
5RAGHUDATHESH GP ASST PROF
#define #define directive (or a macro) has two
parts:
C BASICS
-
8/13/2019 Basics Of C Program
216/260
string-part
value-part
#define string-part value-part
Whenpreprocessor 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
likely to change. 6RAGHUDATHESH GP ASST PROF
#define PI 3.14
main(){float area(float radius);
string-part
value-part No semicolon!
C BASICS
-
8/13/2019 Basics Of C Program
217/260
float cir(float radius);
float radius;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;}
cir.c 7RAGHUDATHESH GP ASST PROF
float area(float radius){return (radius * radius *PI);}float cir(float radius){
C BASICS
-
8/13/2019 Basics Of C Program
218/260
return (2* radius *PI);} Preprocessor replaces all
PI with 3.14. Then
compilation takes place.
Output:
enter the radius of the circle: 13
area is 530.66
circumference is 81.64
You enter this
8RAGHUDATHESH GP ASST PROF
#define PI 3.14#define PROD radius * PI
main(){
C BASICS
-
8/13/2019 Basics Of C Program
219/260
float area(float radius);float cir(float radius);
float radius;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;} 9RAGHUDATHESH GP ASST PROF
float area(float radius){return (radius * PROD);
C BASICS
-
8/13/2019 Basics Of C Program
220/260
}float cir(float radius){return (2* PROD);}
10RAGHUDATHESH GP ASST PROF
Macro functions
A macro can also be defined with arguments
C BASICS
-
8/13/2019 Basics Of C Program
221/260
just like functions. When an ordinary function is encountered in
the code, the compiler transfers the control to
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 compilerdoesn't even know the existence of macro
functions.11RAGHUDATHESH GP ASST PROF
#define PI 3.14#define PROD radius *PI#define area(r) (r * PROD)#define cir(r) (2 * PROD)
C BASICS
-
8/13/2019 Basics Of C Program
222/260
( ) ( )
main(){float radius;
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;}
Macro functions. Though not
necessary it is advisable to put the
macro function in parenthesis.
cir2.c
Expanded as: radius * radius *PI12RAGHUDATHESH GP ASST PROF
Word of caution while using macrofunctions
C BASICS
-
8/13/2019 Basics Of C Program
223/260
A macro function can only have onestatement.
There should be no space between macro
function name and argument. area( r ) not ok
If the macro function has involves * and /
then it is advisable to enclose it in bracketsfor it to have desired effect.
13RAGHUDATHESH GP ASST PROF
#define PI 3#define VOL(radius,height)(PI*radius*radius*height)
den.cC BASICS
-
8/13/2019 Basics Of C Program
224/260
main(){float r=10, h=5, mass=1500;printf("density =%5.2f" ,
mass/VOL(r,h));}
density=mass/volume
According to code : density=1500/ 3*10*10*1500
This is incorrect.This can be corrected by including brackets
14RAGHUDATHESH GP ASST PROF
#includedirective
C BASICS
-
8/13/2019 Basics Of C Program
225/260
This directive causes a file to be includedas a part of your c code.
The file could contain any valid c code,either a set of functions or preprocessor
directives. In fact the library functions like scanf() and
printf() are provided in a file stdio.h that
some compilers automatically include inthe c code.
15RAGHUDATHESH GP ASST PROF
int square(int n){return n*n;}
util.h
.h is commonly used
C BASICS
-
8/13/2019 Basics Of C Program
226/260
int cube(int n){return n*n*n;}
int pow(int n, int p){int i,res;res=n;
for(i=1;i
-
8/13/2019 Basics Of C Program
227/260
printf("pow =%d\n", pow(2,3)); }
Output:
square =100
pow =8
#include "util.h: preprocessor searches for
the file in current directory as well as predefined
directories where standard library files are set up.#include : preprocessor searches for the file
only in the predefined directories where standardlibrary
files are set up.17RAGHUDATHESH GP ASST PROF
Conditional compilation directives Conditional compilation directives allow us to
C BASICS
-
8/13/2019 Basics Of C Program
228/260
specify when the compiler should compile a setof statements based on some condition.
Syntax:
#ifdef macro_name
statement1;
statement2;
statementn;
#endif
The compiler will execute
the statements in the
block only if If
macro_name is defined.
18RAGHUDATHESH GP ASST PROF
Uses Conditional compilation directive statements are
used in cases where we need to comment out
C BASICS
-
8/13/2019 Basics Of C Program
229/260
some code for the time being. It is also used when we want to make C
programs more portable-#ifdef LINUX
statement1;#elsestatement2;
#endif
19RAGHUDATHESH GP ASST PROF
Contains standard library functions.
C BASICS
-
8/13/2019 Basics Of C Program
230/260
Functions available:printf()scanf()
getc()getchar()gets()putc()
putchar()puts()malloc()calloc()
fclose()fopen()fwrite()fputc()fprintf()
fseek()
fopen()fread()fscanf()fopen()ftell()
fputchar()
File handling functions20RAGHUDATHESH GP ASST PROF
C BASICS
-
8/13/2019 Basics Of C Program
231/260
Useful functions to manipulate the strings.
unsigned int strlen(char *s)char * strcat(char *d, char *s)
int strcmpi(char *s1,char *s2)char * strrev(char *s1)char * strlwr(char *s)
char * strupr(char *s)
21RAGHUDATHESH GP ASST PROF
#includemain(){char *n1="Bangalore";char *n2="bangalore";
sman.cC BASICS
-
8/13/2019 Basics Of C Program
232/260
int i,j;
printf("length of n1 :%d\n",strlen(n1));
i=strcmpi(n2,n1);if(i==0)printf("Case insensitive : Same %d\n",i);
elseprintf("Case insensitive: Different%d\n"+i);
22RAGHUDATHESH GP ASST PROF
-
8/13/2019 Basics Of C Program
233/260
This library has all mathematical formulas. int abs(int x)
C BASICS
-
8/13/2019 Basics Of C Program
234/260
double acos(double x) double asin(double x) double atan(double x) double exp(double x)
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 *s)
Similarly cos, sin
and tan functions
24RAGHUDATHESH GP ASST PROF
mat.c#includemain(int n,char* args[]){double d=13.4,f,c;int i,j,k;
C BASICS
-
8/13/2019 Basics Of C Program
235/260
f=floor(d);c=ceil(d);printf("floor: %lf, ceil:%lf\n",f,c);
if(n>1){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);}} 25RAGHUDATHESH GP ASST PROF
Learning OutcomesC BASICS
-
8/13/2019 Basics Of C Program
236/260
Types of files I/O functions
Reading and writing unformatted text
files
Reading and writing formatted text
files
Reading and writing records
1RAGHUDATHESH GP ASST PROF
Types of File I/O
C BASICS
-
8/13/2019 Basics Of C Program
237/260
File I/O
Text Binary
unformatted unformattedformatted
2RAGHUDATHESH GP ASST PROF
Fundamental Steps
C BASICS
-
8/13/2019 Basics Of C Program
238/260
Open a file
Read or write
Close a file
3RAGHUDATHESH GP ASST PROF
Opening a file First step before reading or writing on to a
C BASICS
-
8/13/2019 Basics Of C Program
239/260
file, is opening a file. The library has all the
necessary functions that allow us to work
with files. The fopen()is used to open a file.
FILE* fopen(char * filename,
char *mode) FILE is a structure defined in 4RAGHUDATHESH GP ASST PROF
Modes
Mode File exist File does not exist operations
C BASICS
-
8/13/2019 Basics Of C Program
240/260
r Opens NULL read
w Opens Creates new overwrites
a Opens Creates new appends
r+ Opens NULL Read, writeand change
w+ Opens Creates new read,
overwritesa+ Opens Creates new Read, write
and change5RAGHUDATHESH GP ASST PROF
Unformatted reading and writingfunctions
C BASICS
-
8/13/2019 Basics Of C Program
241/260
int getc(FILE *stream) int fgetc(FILE *stream)
int fgetc(FILE *stream)
char * fgets(char *s, int maxle