SlideShare a Scribd company logo
1 of 102
www.SunilOS.com 1
C
www.sunilos.com
www.raystec.com
www.SunilOS.com 2
C is a Programming Language
It is a primitive programing language.
It is a procedural language.
It is case sensitive.
It can be compiled on variety of platforms.
Used for System Programming.
UNIX, Linux and MySQL database are
written in C.
www.SunilOS.com 3
Compiled and Run on multiple OS
It can be compiled on variety of platforms.
Compile
Linux
Hello.c
Compile
MacOS
Compile
Windows
 An approach to solve a
problem is called program.
 You can take multiple
actions to resolve the
problem. Here Ram will
take action pathD() to
reach to the destination.
 You have to keep some
values/data in your mind to
resolve the problem. Here
some values you have to
keep in mind Ram, Sita,
Lights, and Home.
www.SunilOS.com 4
What is a Program?
www.SunilOS.com 5
( What is today’s program? )
Program for Computer
 For a computer language, a Program is a set of
instructions to perform a task ( resolve a problem).
 Action taken to perform a task is called function.
 Instructions are called statements. One function may
contain multiple instructions.
 Data/Values used and changed by functions are called
variables.
 A program consists of:
o Functions: perform action
o Variables : remember the data
www.SunilOS.com 6
Hello C – My first program
Program that prints “Hello C” at console:
#include <stdio.h>
/* My first program */
void main() {
o printf("Hello C");
}
Code will be stored in file Hello.c
File extension of a C program must be .c
www.SunilOS.com 7
Program details
stdio.h is a library header file. Included by
preprocessor command #include.
printf is library function that prints passed value
at console.
main() is entry point function. Execution is begin
from this function.
void is a keyword.
/*..*/ is a comment statement that describes
something but does not do anything.
www.SunilOS.com 8
Compile and Execute
 Save program as Hello.c to directory c:myprg
 Open a command prompt and go to c:myprg directory
o cd c:myprg
 Compile program by:
o gcc Hello.c //for Linux
o tcc Hello.c //for Windows
o It will compile and create executable file Hello.exe
 Now execute program by:
o Hello.exe
o Output of this program will be “Hello C”
www.SunilOS.com 9
Hello.c
(text)
Hello.exe
(machine code)
Compile
www.SunilOS.com 10
Program
Program Structure
int i = 5 //global variable
void main(){
..
a(5);
}
void a(int k){
int j = 0; //local variable
..
}
www.SunilOS.com 11
Library
Library
Program 1 Program 2
Program 3 Program 4
 Library is made of multiple reusable programs.
www.SunilOS.com 12
C Application
ApplicationApplication
Library 1 Library 2
Library 3 Library 4
 Application is made of multiple C programs
Variables
 Memory area that stores a
value.
 Values are human
understandable data.
 These values can be
changed by executing a
function.
 Variable is declared and
referred by a name.
 Ex. int i = 5 ;
 Here “i” is variable and
stores value 5.
www.SunilOS.com 13
5
i
4 Bytes
1010
Naming Convention
Name is case sensitive and can be composed of
letters, digits and the underscore character.
Variable name should start with a character or
underscore.  
Ex:
o float salary = 1000.10; //correct
o char flag = ‘N’ ; //correct
o int emp_code123 = 101 ; //correct
o int #empCode = 101 ; // Incorrect
o int 9code = 101 ; // Incorrect
o int _code = 101 ; // Correct
www.SunilOS.com 14
Types of Variables
Type Description ( 32 Bit System)
char Typically a single byte contains a character
Ex. char ch = ‘A’ ;
int Contains non-decimal integer number, it occupies 4
bytes
Ex. int i = 5;
float A single-precision floating point value. it occupies 4 bytes
Ex. float f = 5.5;
double A double-precision floating point value. it occupies 8
bytes
Ex. double d = 5.5;
void Represents the absence of type.
www.SunilOS.com 15
C has following basic data types
Basic Data types program
 #include <stdio.h>
 void main() {
 char c = 'A';
 int i = 5;
 float f = 10.5;
 double d = 10.5;

 printf("This is char : %c n", c);
 printf("This is int : %d n", i);
 printf("This is float : %f n", f);
 printf("This is double : %lf n", d);
 }
www.SunilOS.com 16
OUTPUT
This is char : A
This is int : 5
This is float : 10.500000
This is double : 10.500000
Other Data Types
www.SunilOS.com 17
Data Type
Primitive Derived User Defined
char
int
float
double
void
array
pointer
function
enum
structure
union
Data Types
Primitive data types are the basic data types
Derived data types are a derivative of primitive
data types known as arrays, pointer and function.
User defined data types are those data types
which are defined by the user/programmer
himself.
www.SunilOS.com 18
Modifiers
Modifiers are keywords used to increase or
decrease the storage capacity of basic data types.
Modifiers are prefixed with data type.
There are 4 modifiers :
o short: It applies on int and reduces size to 2 bytes.
o long : It applies on int and double data types. It
doubles the size of int (4 to 8 bytes) and double (8 to
16 bytes) data types.
o unsigned: It accepts only +ve value.
o Signed: It accepts both +ve and –ve value.
www.SunilOS.com 19
Modifiers
Example declaration
o short int a = 100;
o long int i = 100;
o long double d = 100.10;
o signed int a = -10; //correct
o signed int a = 10; //correct
o unsigned int b = 10; //correct
o unsigned int b = -10; //incorrect
www.SunilOS.com 20
Size of Data types
 #include <stdio.h>
 void main() {
 printf(“char= %dn", sizeof(char));
 printf("int= %dn", sizeof(int));
 printf("float= %dn", sizeof(float));
 printf("double = %dn", sizeof(double));
 printf("short int= %dn", sizeof(short int));
 printf(“long int = %dn", sizeof(long int));
 printf("long double = %dn", sizeof(long double));
 printf("long long = %dn", sizeof(long long));
 }
www.SunilOS.com 21
OUTPUT
char= 1
int= 4
float= 4
double = 8
short int= 2
long int= 8
long double = 16
long long = 8
Modifiers ( Cont.)
Keyword
Identifier
(Format Specifier) Size ( Bytes) Data Range
char %c 1 -128 to +127
int %d 4 -231
 to +231
float %f 4 -3.4e38
 to +3.4e38
double %lf 8 -1.7e38
 to +1.7e38
long int %ld 8 -263
 to +263
unsigned int %u 4 0 to 232
long double %Lf 16 -3.4e38
 to +3.4e38
unsigned char %c 1 0 to 255
www.SunilOS.com 22
Signed vs Unsigned
www.SunilOS.com 23
0 1 00 0 100
1 Byte
0 1 00 0 100
1 Byte
char a = ‘A’;
unsigned char a = ‘A’;
Sign bit
Data bit
Value Range: -27
to +27
Value Range: 0 to 28
Constants
Constants refer to fixed values that can not be
changed during program execution.
Constants can be of any of the basic data types.
There are enumeration constants as well.
The const qualifier is used to tell C that the
variable value can not change after initialization.
o Ex.
 const float PI=3.14159;
 OR
 const float PI;
 PI=3.14159;
www.SunilOS.com 24
Literals
These are the fix values assigned to a
variable.
For example
o int i = 5;
o float f = 10.5;
o char c =‘A’ ;
www.SunilOS.com 25
% Format specifier
 Function printf uses “format specifiers” to print formatted
output at console.
 There are many format specifies:
o %i and %d for int
o %c for char
o %f for float
o %s for string
o %e for float or double exponential format
o %o for unsigned octal value
o %x for unsigned hex value
o %p pointer address stored in pointer
www.SunilOS.com 26
Format Specifier Program
 void main() {
 int a = 7;
 float b = 12.345678;
 int c = -10;

 printf("%dn",a);
 printf("%3dn",a); //places leading spaces
 printf("%03dn",a);// places leading zero
 printf("%+dn",a);// always displays sign
 printf("%+dn",c);// always displays sign
 printf("%fn",b);
 printf("%3.2fn",b); //3 digits and 2 decimal
 printf("%sn","Hello");
 printf("%10sn","Hello"); //right justify in length of 10
 printf("%-10sn","Hello"); //left justify in length of 10
www.SunilOS.com 27
OUTPUT
7
7
007
+7
-10
12.345678
12.35
Hello
Hello
Hello
Format Specifier Modifiers
 Modifiers
o can be preceded with specifier to format the value. Its format is:
 flag width.precision
o - flag will be used for left justify
o + flag always displays sign
o 0 flag displays leading zeros
o Width specifies total displayed width
o Precision indicates number of digits after decimals
 Control Codes
o b backspace , f formfeed
o n new line, r carriage return
o t horizontal tab, ' single quote
o 0 null
www.SunilOS.com 28
Input and Output
Input
o Value or Data given to a program is called input.
o It is given from a file or command prompt.
o C has scanf()function to get input from command
prompt.
o Some other library functions are available for data input.
Output
o It means to display data on Screen, Printer or a File.
o Function printf() is frequently used for output data.
www.SunilOS.com 29
Input – scanf()
 It is used to read an input from the command line.
 Following program will read an integer from command line:
 int a; int flag ;
 printf("Enter an integer: ");
 scanf("%d", &a))
 if (a == 0) {
 printf("Error: not an integern");
 } else {
 printf("Read in %dn", a);
 }
 If invalid value is entered then scanf() function will return 0 value.
Here &a denotes memory address of ‘a’ variable.
www.SunilOS.com 30
Control Statement
Branching
o if-else
o switch
Looping
o while
o for
o do-while
o Loop Control
Statements
 break
 continue
 goto
www.SunilOS.com 31
If-else
 #include <stdio.h>
 void main () {
 int rs = 100;
 if (rs > 100) {
 printf("I can buy pizza");
 } else {
 printf("I can not buy pizza");
 }
 }
www.SunilOS.com 32
www.SunilOS.com
While Loop
33
www.SunilOS.com
While Loop
 #include <stdio.h>
 void main() {
o int = 0;
o int round = 0;
o while ( == 0 ) {
 printf( “ !!! n");
 if (++round > 500 ){
• = 1;
 }
o }
 }
34
www.SunilOS.com
For Loop
₹10 for 5 shots
How Much?
Okay!!
35
 void main()
 {
o int shot ;
o for (shot=1; shot <= 5; shot++)
o {
o printf("Shot Balloon %d n" , shot);
o }
o }
 }
www.SunilOS.com
For Loop – Five shots
36
www.SunilOS.com 37
Do-While
#include <stdio.h>
void main () {
o int i = 0 ;
o do {
printf("Hello %d n" , ++i);
o }while (i<5);
}
www.SunilOS.com 38
Switch statement
 main(){
 int grade = 'A';
 switch( grade )
 {
 case 'A' : printf( "Excellentn" ); break;
 case 'B' : printf( "Goodn" );break;
 case 'C' : printf( "OKn" );break;
 case 'D' : printf( “Improve next time....n" );break;
 default : printf( “Where is your result?n" );break;
 }
 }
break statement
It breaks the correct loop or switch
statement
void main () {
int i = 0 ;
while( i == 1) {
printf("Hello %d n" , ++i);
if(i>=5){
break; // breaks the loop
}
};
}
www.SunilOS.com 39
continue statement
It skips 1 iteration of loop
void main () {
int i = 0 ;
while(i < 10) {
++i;
if(i<5){
continue; //Skips this iteration
}
printf("Hello %d n" , i);
};
}
www.SunilOS.com 40
www.SunilOS.com 41
Add two numbers
 #include <stdio.h>
 void main () {
 int n1 = 5 ;
 int n2 = 10 ;
 int sum ;

 sum = n1 + n2;

 printf("Num 1 %d n" , n1);
 printf("Num 2 %d n" , n2);
 printf("Sum %d n" , sum);
 printf("%d = %d + %d n" , sum, n1, n2);
 }
Using functions
 Function is a set of statements that performs a particular
task.
 It is independent and reusable block of code.
 It can be called from other functions.
 It takes number of parameters or no parameters.
 After executing its task it may or may not return a value.
 We already have seen a library function printf()
 Syntax
o returnValue functionName ( dataType param1, dataType param2, .. ) {.. }
www.SunilOS.com 42
Define a function
 void main () {
 int a = 5 ; int b = 10 ;
 int maxValue ;
 maxValue = max(a,b);
 printf(" Max of %d and %d is %dn" , a, b, maxValue);
 }
 int max (int a, int b){
 if (a > b){
 return a;
 }else{
 return b;
 }
 }
www.SunilOS.com 43
Function
definition
Return
value
Return
value
Function
call
Parameters
Arrays
List of same type of elements.
Fix size list.
Elements are accessed by Index
number.
Index number is started by 0.
Made of contiguous memory locations.
Declared as
o dataType arrayName[arraySize];
o int table[10] ; // integer array of size 10
www.SunilOS.com 44
20
[0]
18
..
10
8
6
4
2
[1]
[8]
[9]
[2]
[3]
[4]
[n]
www.SunilOS.com 45
One Dimension Array
20
[0]
18
..
10
8
6
4
2
[1]
[8]
[9]
[2]
[3]
[4]
[n]
int table[10];
int a = table[4];
int a = table[2];
printf("%d", table[2]);
www.SunilOS.com 46
Initialize an Array
20
[0]
18
..
10
8
6
4
2
[1]
[8]
[9]
[2]
[3]
[4]
[n]
int table[10];
table[0] =2;
table[1] =4;
…
Or
int table[] = {2,4,6,8,10,12,14,16,18,20};
Print All elements of Array
void main () {
 int table[] = {2,4,6,8,10,12,14,16,18,20};
 int i ;
 for(i=0; i<10;i++){
 printf("Table[%d] : %d n",i, table[i]);
 }
}
www.SunilOS.com 47
OUTPUT
Table[0] : 2
Table[1] : 4
Table[2] : 6
Table[3] : 8
Table[4] : 10
Table[5] : 12
Table[6] : 14
Table[7] : 16
Table[8] : 18
Table[9] : 20
www.SunilOS.com 48
Other Data Type Arrays
char chList[5];
chList[0] = ‘A’….
o Or
char[] chList = {‘A’,’B’,’C’,’D’,’E’}
double balance[5] ;
balance[1] = 2.0;
o Or
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
www.SunilOS.com 49
[0]
20
18
..
10
8
6
4
2
[1]
[8]
[9]
[2]
[3]
[4]
[n]
30
27
..
15
12
9
6
3
40
36
..
20
16
12
8
4
90
81
..
45
36
27
18
9
100
90
..
50
40
30
20
10
…
[0] [1] [2] [7] [8]
Multidimensional Arrays – 2D
//Declare array
int table[10][9] ;
//Assign values
table[0][0] =2;
table[1][1] =6;
…
M-Array Initialization
 int table[2][3] = {{1,2,3},{4,5,6}}; OR
 int table[][3] = {{1,2,3},{4,5,6}}; OR
 int table[2][3] = {{1,2,3,4,5,6}};
Print all elements of 2D array
 void main () {
 int table[2][3] = {{1,2,3},{4,5,6}};
 int i,j ;
 for(i=0; i<2;i++){
 for(j=0; j<3;j++){
 printf("Table[%d][%d] : %dn", i, j, table[i][j]);
 }
 }
 } www.SunilOS.com 50
OUTPUT
Table[0][0] : 1
Table[0][1] : 2
Table[0][2] : 3
Table[1][0] : 4
Table[1][1] : 5
Table[1][2] : 6
www.SunilOS.com 51
3D Array
20
[0]
18
..
10
8
6
4
2
[1]
[8]
[9]
[2]
[3]
[4]
[n]
30
27
..
15
12
9
6
3
40
36
..
20
16
12
8
4
90
81
..
45
36
27
18
9
100
90
..
50
40
30
20
10
[0] [1] [2] [8] [9]
20
18
..
10
8
6
4
2
30
27
..
15
12
9
6
3
40
36
..
20
16
12
8
4
20
18
..
10
8
6
4
30
27
..
15
12
9
6
20
18
..
10
8
6
4
2
30
27
..
15
12
9
6
3
40
36
..
20
16
12
8
4
90
81
..
45
36
27
18
9
100
90
..
50
40
30
20
10
90
81
..
45
36
27
18
9
100
90
..
50
40
30
20
10
…
[0]
[1]
[2]
www.SunilOS.com 52
What’s an operator?
Operators are tokens that trigger some
computation when applied to variables.
Operators can be categorized into:
o Arithmetic operators
o Relational operators
o Logical operators
o Bitwise operators
o Assignment operators
o Misc operators
www.SunilOS.com 53
Operators
()
++
--
!
~
sizeof
*
/
%
+
-
<<
>>
<
>
<=
>=
==
!=
&
^
|
&&
||
?:
=
op=
www.SunilOS.com 54
Unary operators
Operator Description Example
() Group expression a = (b+c) * d;
+ Unary plus a = +5;
- Unary Minus a = -5;
~ Bitwise complement a = ~b;
! Logical negation if ( !(a == b){…}
++ Pre or Post increment ++i ; or i++;
-- Pre or Post decrement --i ; or i--;
Used with one operand (value)
www.SunilOS.com 55
Unary operators
Why value of count variable is different in
pre and post increments?
i = 0;
count = 2 + i++;
i = 0;
count = 2 + i++;
ii
countcount
11
22
i = 0;
count = 2 + ++i;
i = 0;
count = 2 + ++i;
ii
countcount
11
33
www.SunilOS.com 56
Binary operators
 yyyy
OperandOperand
xxxx
OperandOperand
OperatorOperator
Arithmetic binary operators
Operator Description Example
+ Plus a = b + c;
- Minus a = b - c;
* Multiply a = b * c;
/ Division a = b / c;
% Reminder a = b % c;
www.SunilOS.com 57
void main () {
int a =5;
int b =2;
int r;
r =a%b;
printf("Reminder value : %d n", r);
}
Try
www.SunilOS.com 58
Assignment binary operators
== AssignmentAssignment
 Assignment is a binary operator.
 The left-hand operand of an assignment must be an
LVALUE.
 An LVALUE is an expression that refers to a region of
memory.
o Names of variables are LVALUES.
o Names of functions and arrays are NOT LVALUES.
www.SunilOS.com 59
Binary operators
void main () {
int result, val_1, val_2;
result = (val_1 = 1) + (val_2 = 2);
printf("val_1 = %d n",val_1);
printf("val_2 = %d n",val_2);
printf("result = %d n", result);
}
void main () {
int result, val_1, val_2;
result = (val_1 = 1) + (val_2 = 2);
printf("val_1 = %d n",val_1);
printf("val_2 = %d n",val_2);
printf("result = %d n", result);
} val_1 = 1
val_2 = 2
result = 3
val_1 = 1
val_2 = 2
result = 3
www.SunilOS.com 60
Binary operators
Expressions involving only integers are
evaluated using integer arithmetic.
float result;
int i=25;
int j=10;
result = i/j;
printf("Result %f", result);
float result;
int i=25;
int j=10;
result = i/j;
printf("Result %f", result);
resultresult 2.02.0
www.SunilOS.com 61
Binary operators
Expressions involving only integers are
evaluated using integer arithmetic.
float result;
int i=25;
int j=10;
result = (float) i/j;
printf("Result %f", result);
float result;
int i=25;
int j=10;
result = (float) i/j;
printf("Result %f", result);
resultresult 2.52.5
www.SunilOS.com 62
Assignment binary operators
Operator Description Example
+= Assign sum a += a;
-= Assign difference a -= a;
*= Assign product a *= a;
/= Assign quotient a /= a;
%= Assign reminder a %= a;
Compound operators provide a convenient shorthand.
int i;
i = i + 5;
//or
i += 5;
int i;
i = i + 5;
//or
i += 5;
www.SunilOS.com 63
Relational binary operators
Operator Description Example
< Less than if( a > b ) {..}
> Greater than if( a < b ) {..}
>= Greater than equal to if( a >= b ) {..}
<= Less than equal to if( a <= b ) {..}
== Equal to if( a == b ) {..}
!= Not equal to if( a != b ) {..}
Try above examples with following variable values
int a = 10;
int b = 20
Relational binary operators
A ZERO value is considered logical false
and Non-ZERO value is considered true
value in logical operators.
www.SunilOS.com 64
void main () {
int i= 0; //change to +ve value
if(i){
printf("true %d",i);
}else{
printf("false %d", i);
}
}
Try
www.SunilOS.com 65
Logical binary operators
Operator Description Example
&& Logical AND if( a > b && b > c) {..}
|| Logical OR if( a < b || b > c) {..}
! Logical NOT – reverse
the logical state
if ( !( a == b ) ) {..}
Try above examples with following variable values
int a = 10;
int b = 20;
int c = 40;
www.SunilOS.com 66
Binary operators
Expressions connected by && and || are
evaluated from left to right.
void main () {
int i=0;
int flag = ((2<3) || (0<i++));
printf("Test: %d n" , flag);
printf("I: %d",i);
}
void main () {
int i=0;
int flag = ((2<3) || (0<i++));
printf("Test: %d n" , flag);
printf("I: %d",i);
} Test: 1
I:0
Test: 1
I:0
This never gets
evaluated!
This never gets
evaluated!
www.SunilOS.com 67
Bitwise binary operators
Operator Description
<< Shift Left
>> Shift Right
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Unary bitwise complement
It works on bits and perform bit-by-bit operation.
Truth Table of Binary Operators
a b a & b a | b a ^ b
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
www.SunilOS.com 68
www.SunilOS.com 69
Unary bitwise complement
1 1 11 0 101
~
1 Byte
0 0 00 1 010
int a = 10;
int b = ~a;
www.binaryhexconverter.com/binary-to-decimal-converter
www.SunilOS.com 70
Left Shift <<
1 1 01 0 101
<<
1 Byte
1 0 10 0 001
int a = -101;
int b = a<<2;
1
1
Value of b will be -20
www.SunilOS.com 71
Right Shift >>
1 1 01 0 101
>>
1 Byte
1 0 10 1 100
int a = -101;
int b = a>>2;
1
0
Value of b will be -25
www.SunilOS.com 72
And bitwise &
0 0 00 1 010
&
1 Byte
0 0 11 1 001
int a = 10;
int b = 60;
int c = a & b;
0 0 00 1 000
Value of c will be 8
www.SunilOS.com 73
OR bitwise |
1 1 01 0 101
|
1 Byte
0 0 11 1 100
int a = -101;
int b = 57;
int c = a | b;
1 1 11 1 101
Value of c will be 125
www.SunilOS.com 74
XOR bitwise ^
1 1 01 0 101
^
1 Byte
0 0 11 1 100
int a = -101;
int b = 57;
int c = a ^ b;
1 1 10 1 011
Value of c will be -94
www.SunilOS.com 75
XOR bitwise ^
1 1 01 0 101
^
1 Byte
0 0 11 1 100
byte a = 10;
int b = 20;
int c = a ^ b;
1 1 10 1 001
www.SunilOS.com 76
Ternary operators
a?x:ya?x:y
“if a then x else y”
Conditional
result = (x<y) ? x : y;result = (x<y) ? x : y;
Miscellaneous Operators
Operator Description Example
sizeof() Returns the size of a
variable.
sizeof(a), where a is integer, will
return 4.
& Returns the address of
a variable.
&a; returns the actual address of
the variable.
* Pointer to a variable. *a;
www.SunilOS.com 77
void main () {
int a =10;
int *b = &a;
printf("value of c : %d n", a);
printf("value of c : %p n", &a);
printf("value of c : %p n", b);
}
Try
www.SunilOS.com 78
Operator Precedence
int a = 2+ 4 + 8;
int a = 2+ 4 * 8;
int a = b = c = 5;
Operator Precedence
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
www.SunilOS.com 79
www.SunilOS.com 80
Precedence
Operators have the precedence. Higher
precedence operator will be evaluated before the
lower precedence operator.
o int data = a * b + c ;
since * (multiply) has higher precedence than +
(plus) so a & b will be multiplied first then result
will be added to c.
Expression is equivalent to
o int data = (a * b) + c ;
Variable Scope
 A scope is a region of the program where a defined
variable can be accessed.
 Outside its scope variable can not be accessed.
 There are 3 places where variable can be defined:
o Inside a function or a block which is called Local
variable. It will be accessible only inside block or
function.
o Outside of all functions which is called Global
variable. It will be accessible in all functions of its
program.
o As function parameter which are called formal
parameter.
www.SunilOS.com 81
Local Variable
Declared inside a function or block.
Accessible to statements inside that
function or block of code.
Can’t be accessed outside function or block.
void main () {
 int a=10; //local variable
 int b=15; //local variable
 printf ("Value of a = %d", a);
}
www.SunilOS.com 82
Global Variable
It is defined outside a function, usually on top of
the program.
It exist in memory throughout the lifetime of your
program.
It can be accessed inside any of the functions
defined for the program.
A program may have global and local variables of
same name but the value of local variable inside a
function will take preference.
www.SunilOS.com 83
Global example
 int g = 20; //global variable
 int gl = 20; //global variable
 void main () {
 int l = 10; //local variable
 int gl = 10; //local variable
 printf ("l = %dn", l);
 printf ("g = %dn", g);
 printf ("gl = %dn", gl);

 printVal();
 }
 int printVal(){
 printf (“Print Val g = %dn", g);
 }
www.SunilOS.com 84
Try
OUTPUT
l = 10
g = 20
gl = 10
printVal g = 20
Initializing Local and Global Vs
It is good programming practice to initialize
variables properly.
Global variables are initialized automatically by the
system at the time of declaration.
Data type int, float, double are initialized by
0, char is initialized by ‘0’ character, and
pointer is initialized by NULL.
Local variables are NOT initialized at the time of
declaration.
www.SunilOS.com 85
Reserved Keywords
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
www.SunilOS.com 86
Pointers
 It is a variable.
 A pointer variable stores a
memory address of
another variable .
 Memory address can be
accessed by ampersand
(&) operator.
 Here p is a pointer variable
that stores address of a:
o int a = 1;
o int *p = &a;
www.SunilOS.com 87
Pointers ( Cont. )
 #include <stdio.h>
 void main () {
 int a = 10;
 int *p = NULL;
 //store address of ‘a’ in pointer variable
 p = &a ;
 printf("Address of a : %xn", &a );
 printf("Address stored in p : %xn", p );
 printf("Value of *ip variable: %dn", *p );
 }
www.SunilOS.com 88
0 0 00 1 010
int a = 10;
a= 1110
int *p = &a;
1 011
p= 1100
OUPUT
Address of a : 7903aab4
Address stored in p : 7903aab4
Value of *ip variable: 10
Pointers (Cont. )
Pointers must be defined before using them.
Pointer can be of any C data type:
o int *ip ;
o char *cp;
o float *fp;
o double *dp
NULL Pointers
o It is recommended to initialize a pointer by NULL value.
o int *p = NULL;
o If a pointer has NULL value then it is called NULL
pointer.
www.SunilOS.com 89
Passing parameters to Function
There are two ways to pass parameters to a
function:
Pass by Value: C creates a local copy of this
variable. All the changes made on local copy will
not impact original variable.
Pass by Reference: In this case address of the
variable is passed to function. Any changes made
on this address will change the value of original
variable.
www.SunilOS.com 90
Pass by reference example
 void test(int a, int *p){
 a = 20; //Make changes on local copy
 *p = 20; //Make changes on address, will change original variable
 }
 void main () {
 int a = 10; int b = 10;

 //Pass value of ‘a’ and address of ‘b’
 test (a, &b);
 printf(" a = : %dn", a );
 printf(" b = : %dn", b );
 }
www.SunilOS.com 91
OUTPUT
a = : 10
b = : 20
Structure and Union
Both are custom data types defined by
users.
Structures are defined using struct key
word.
www.SunilOS.com 92
Structure
It is user defined data type. That combines basic
data types to make custom data type.
It can combine different type of data types.
Custom Data types can be used as basic data
types.
o struct telephone {
 char *name;
 int number;
o };
www.SunilOS.com 93
www.SunilOS.com 94
File Handling and IO
www.SunilOS.com 95
String Handling
 void main(){
o int i,j;
o char name[10], nameCopy[10]; //Define char arrays
o printf(“Enter first String :”);
o scanf(“%s”,name); //Get string from Keyboard
o printf(“n %s”,name); // Print string at console
o i=strlen(name); // Length of String
o printf(“length of name is :%d”,i);
o strcpy(nameCopy,name); //Copy a string
o printf(“n %s”, nameCopy);
}
www.SunilOS.com 96
Recursion ( Cont.)
When a function call itself, called recursion.
o int disp(int x){
o int f ;
o if(x ==1 ){
o f = x ;
o }else{
o f = x * disp(x-1);
o }
o return f;
o }
www.SunilOS.com 97
Recursion
o void main(){
o int a, fact;
o a=5;
o fact = disp(a);
o printf(“Factorial is: %d”,fact);
o getch();
o }...
www.SunilOS.com 98
Math.h
www.SunilOS.com 99
Graphics.h
www.SunilOS.com 100
Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 101
Thank You!
www.SunilOS.com 102
www.SunilOS.com

More Related Content

What's hot

Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Threads V4
Threads  V4Threads  V4
Threads V4Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3Sunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++ Bharat Kalia
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - PointersWingston
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage classkapil078
 

What's hot (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Threads V4
Threads  V4Threads  V4
Threads V4
 
JDBC
JDBCJDBC
JDBC
 
Log4 J
Log4 JLog4 J
Log4 J
 
PDBC
PDBCPDBC
PDBC
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Introduction to C++
Introduction to C++ Introduction to C++
Introduction to C++
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 

Viewers also liked

Viewers also liked (20)

JUnit 4
JUnit 4JUnit 4
JUnit 4
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
C programming
C programmingC programming
C programming
 
MIPS Assembly Language I
MIPS Assembly Language IMIPS Assembly Language I
MIPS Assembly Language I
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
best notes in c language
best notes in c languagebest notes in c language
best notes in c language
 
C Programming - Refresher - Part IV
C Programming - Refresher - Part IVC Programming - Refresher - Part IV
C Programming - Refresher - Part IV
 
Cmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowchartsCmp104 lec 7 algorithm and flowcharts
Cmp104 lec 7 algorithm and flowcharts
 
C Programming - Refresher - Part I
C Programming - Refresher - Part I C Programming - Refresher - Part I
C Programming - Refresher - Part I
 
C Programming - Refresher - Part II
C Programming - Refresher - Part II C Programming - Refresher - Part II
C Programming - Refresher - Part II
 
Introduction to Basic C programming 02
Introduction to Basic C programming 02Introduction to Basic C programming 02
Introduction to Basic C programming 02
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 

Similar to C Programming Language Guide for Beginners

Similar to C Programming Language Guide for Beginners (20)

Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Reduce course notes class xii
Reduce course notes class xiiReduce course notes class xii
Reduce course notes class xii
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. AnsariBasic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
 
2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt2. Data, Operators, IO.ppt
2. Data, Operators, IO.ppt
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
Basic c
Basic cBasic c
Basic c
 
Programming in C
Programming in CProgramming in C
Programming in C
 
What is c
What is cWhat is c
What is c
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
Data Input and Output
Data Input and OutputData Input and Output
Data Input and Output
 
1584503386 1st chap
1584503386 1st chap1584503386 1st chap
1584503386 1st chap
 
C programming
C programmingC programming
C programming
 
00 C hello world.pptx
00 C hello world.pptx00 C hello world.pptx
00 C hello world.pptx
 

More from Sunil OS

Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 

More from Sunil OS (9)

DJango
DJangoDJango
DJango
 
OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Angular 8
Angular 8 Angular 8
Angular 8
 

Recently uploaded

Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapIshara Amarasekera
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...kalichargn70th171
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsDEEPRAJ PATHAK
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 

Recently uploaded (20)

Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery Roadmap
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software Projects
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 

C Programming Language Guide for Beginners

  • 2. www.SunilOS.com 2 C is a Programming Language It is a primitive programing language. It is a procedural language. It is case sensitive. It can be compiled on variety of platforms. Used for System Programming. UNIX, Linux and MySQL database are written in C.
  • 3. www.SunilOS.com 3 Compiled and Run on multiple OS It can be compiled on variety of platforms. Compile Linux Hello.c Compile MacOS Compile Windows
  • 4.  An approach to solve a problem is called program.  You can take multiple actions to resolve the problem. Here Ram will take action pathD() to reach to the destination.  You have to keep some values/data in your mind to resolve the problem. Here some values you have to keep in mind Ram, Sita, Lights, and Home. www.SunilOS.com 4 What is a Program?
  • 5. www.SunilOS.com 5 ( What is today’s program? )
  • 6. Program for Computer  For a computer language, a Program is a set of instructions to perform a task ( resolve a problem).  Action taken to perform a task is called function.  Instructions are called statements. One function may contain multiple instructions.  Data/Values used and changed by functions are called variables.  A program consists of: o Functions: perform action o Variables : remember the data www.SunilOS.com 6
  • 7. Hello C – My first program Program that prints “Hello C” at console: #include <stdio.h> /* My first program */ void main() { o printf("Hello C"); } Code will be stored in file Hello.c File extension of a C program must be .c www.SunilOS.com 7
  • 8. Program details stdio.h is a library header file. Included by preprocessor command #include. printf is library function that prints passed value at console. main() is entry point function. Execution is begin from this function. void is a keyword. /*..*/ is a comment statement that describes something but does not do anything. www.SunilOS.com 8
  • 9. Compile and Execute  Save program as Hello.c to directory c:myprg  Open a command prompt and go to c:myprg directory o cd c:myprg  Compile program by: o gcc Hello.c //for Linux o tcc Hello.c //for Windows o It will compile and create executable file Hello.exe  Now execute program by: o Hello.exe o Output of this program will be “Hello C” www.SunilOS.com 9 Hello.c (text) Hello.exe (machine code) Compile
  • 10. www.SunilOS.com 10 Program Program Structure int i = 5 //global variable void main(){ .. a(5); } void a(int k){ int j = 0; //local variable .. }
  • 11. www.SunilOS.com 11 Library Library Program 1 Program 2 Program 3 Program 4  Library is made of multiple reusable programs.
  • 12. www.SunilOS.com 12 C Application ApplicationApplication Library 1 Library 2 Library 3 Library 4  Application is made of multiple C programs
  • 13. Variables  Memory area that stores a value.  Values are human understandable data.  These values can be changed by executing a function.  Variable is declared and referred by a name.  Ex. int i = 5 ;  Here “i” is variable and stores value 5. www.SunilOS.com 13 5 i 4 Bytes 1010
  • 14. Naming Convention Name is case sensitive and can be composed of letters, digits and the underscore character. Variable name should start with a character or underscore.   Ex: o float salary = 1000.10; //correct o char flag = ‘N’ ; //correct o int emp_code123 = 101 ; //correct o int #empCode = 101 ; // Incorrect o int 9code = 101 ; // Incorrect o int _code = 101 ; // Correct www.SunilOS.com 14
  • 15. Types of Variables Type Description ( 32 Bit System) char Typically a single byte contains a character Ex. char ch = ‘A’ ; int Contains non-decimal integer number, it occupies 4 bytes Ex. int i = 5; float A single-precision floating point value. it occupies 4 bytes Ex. float f = 5.5; double A double-precision floating point value. it occupies 8 bytes Ex. double d = 5.5; void Represents the absence of type. www.SunilOS.com 15 C has following basic data types
  • 16. Basic Data types program  #include <stdio.h>  void main() {  char c = 'A';  int i = 5;  float f = 10.5;  double d = 10.5;   printf("This is char : %c n", c);  printf("This is int : %d n", i);  printf("This is float : %f n", f);  printf("This is double : %lf n", d);  } www.SunilOS.com 16 OUTPUT This is char : A This is int : 5 This is float : 10.500000 This is double : 10.500000
  • 17. Other Data Types www.SunilOS.com 17 Data Type Primitive Derived User Defined char int float double void array pointer function enum structure union
  • 18. Data Types Primitive data types are the basic data types Derived data types are a derivative of primitive data types known as arrays, pointer and function. User defined data types are those data types which are defined by the user/programmer himself. www.SunilOS.com 18
  • 19. Modifiers Modifiers are keywords used to increase or decrease the storage capacity of basic data types. Modifiers are prefixed with data type. There are 4 modifiers : o short: It applies on int and reduces size to 2 bytes. o long : It applies on int and double data types. It doubles the size of int (4 to 8 bytes) and double (8 to 16 bytes) data types. o unsigned: It accepts only +ve value. o Signed: It accepts both +ve and –ve value. www.SunilOS.com 19
  • 20. Modifiers Example declaration o short int a = 100; o long int i = 100; o long double d = 100.10; o signed int a = -10; //correct o signed int a = 10; //correct o unsigned int b = 10; //correct o unsigned int b = -10; //incorrect www.SunilOS.com 20
  • 21. Size of Data types  #include <stdio.h>  void main() {  printf(“char= %dn", sizeof(char));  printf("int= %dn", sizeof(int));  printf("float= %dn", sizeof(float));  printf("double = %dn", sizeof(double));  printf("short int= %dn", sizeof(short int));  printf(“long int = %dn", sizeof(long int));  printf("long double = %dn", sizeof(long double));  printf("long long = %dn", sizeof(long long));  } www.SunilOS.com 21 OUTPUT char= 1 int= 4 float= 4 double = 8 short int= 2 long int= 8 long double = 16 long long = 8
  • 22. Modifiers ( Cont.) Keyword Identifier (Format Specifier) Size ( Bytes) Data Range char %c 1 -128 to +127 int %d 4 -231  to +231 float %f 4 -3.4e38  to +3.4e38 double %lf 8 -1.7e38  to +1.7e38 long int %ld 8 -263  to +263 unsigned int %u 4 0 to 232 long double %Lf 16 -3.4e38  to +3.4e38 unsigned char %c 1 0 to 255 www.SunilOS.com 22
  • 23. Signed vs Unsigned www.SunilOS.com 23 0 1 00 0 100 1 Byte 0 1 00 0 100 1 Byte char a = ‘A’; unsigned char a = ‘A’; Sign bit Data bit Value Range: -27 to +27 Value Range: 0 to 28
  • 24. Constants Constants refer to fixed values that can not be changed during program execution. Constants can be of any of the basic data types. There are enumeration constants as well. The const qualifier is used to tell C that the variable value can not change after initialization. o Ex.  const float PI=3.14159;  OR  const float PI;  PI=3.14159; www.SunilOS.com 24
  • 25. Literals These are the fix values assigned to a variable. For example o int i = 5; o float f = 10.5; o char c =‘A’ ; www.SunilOS.com 25
  • 26. % Format specifier  Function printf uses “format specifiers” to print formatted output at console.  There are many format specifies: o %i and %d for int o %c for char o %f for float o %s for string o %e for float or double exponential format o %o for unsigned octal value o %x for unsigned hex value o %p pointer address stored in pointer www.SunilOS.com 26
  • 27. Format Specifier Program  void main() {  int a = 7;  float b = 12.345678;  int c = -10;   printf("%dn",a);  printf("%3dn",a); //places leading spaces  printf("%03dn",a);// places leading zero  printf("%+dn",a);// always displays sign  printf("%+dn",c);// always displays sign  printf("%fn",b);  printf("%3.2fn",b); //3 digits and 2 decimal  printf("%sn","Hello");  printf("%10sn","Hello"); //right justify in length of 10  printf("%-10sn","Hello"); //left justify in length of 10 www.SunilOS.com 27 OUTPUT 7 7 007 +7 -10 12.345678 12.35 Hello Hello Hello
  • 28. Format Specifier Modifiers  Modifiers o can be preceded with specifier to format the value. Its format is:  flag width.precision o - flag will be used for left justify o + flag always displays sign o 0 flag displays leading zeros o Width specifies total displayed width o Precision indicates number of digits after decimals  Control Codes o b backspace , f formfeed o n new line, r carriage return o t horizontal tab, ' single quote o 0 null www.SunilOS.com 28
  • 29. Input and Output Input o Value or Data given to a program is called input. o It is given from a file or command prompt. o C has scanf()function to get input from command prompt. o Some other library functions are available for data input. Output o It means to display data on Screen, Printer or a File. o Function printf() is frequently used for output data. www.SunilOS.com 29
  • 30. Input – scanf()  It is used to read an input from the command line.  Following program will read an integer from command line:  int a; int flag ;  printf("Enter an integer: ");  scanf("%d", &a))  if (a == 0) {  printf("Error: not an integern");  } else {  printf("Read in %dn", a);  }  If invalid value is entered then scanf() function will return 0 value. Here &a denotes memory address of ‘a’ variable. www.SunilOS.com 30
  • 31. Control Statement Branching o if-else o switch Looping o while o for o do-while o Loop Control Statements  break  continue  goto www.SunilOS.com 31
  • 32. If-else  #include <stdio.h>  void main () {  int rs = 100;  if (rs > 100) {  printf("I can buy pizza");  } else {  printf("I can not buy pizza");  }  } www.SunilOS.com 32
  • 34. www.SunilOS.com While Loop  #include <stdio.h>  void main() { o int = 0; o int round = 0; o while ( == 0 ) {  printf( “ !!! n");  if (++round > 500 ){ • = 1;  } o }  } 34
  • 35. www.SunilOS.com For Loop ₹10 for 5 shots How Much? Okay!! 35
  • 36.  void main()  { o int shot ; o for (shot=1; shot <= 5; shot++) o { o printf("Shot Balloon %d n" , shot); o } o }  } www.SunilOS.com For Loop – Five shots 36
  • 37. www.SunilOS.com 37 Do-While #include <stdio.h> void main () { o int i = 0 ; o do { printf("Hello %d n" , ++i); o }while (i<5); }
  • 38. www.SunilOS.com 38 Switch statement  main(){  int grade = 'A';  switch( grade )  {  case 'A' : printf( "Excellentn" ); break;  case 'B' : printf( "Goodn" );break;  case 'C' : printf( "OKn" );break;  case 'D' : printf( “Improve next time....n" );break;  default : printf( “Where is your result?n" );break;  }  }
  • 39. break statement It breaks the correct loop or switch statement void main () { int i = 0 ; while( i == 1) { printf("Hello %d n" , ++i); if(i>=5){ break; // breaks the loop } }; } www.SunilOS.com 39
  • 40. continue statement It skips 1 iteration of loop void main () { int i = 0 ; while(i < 10) { ++i; if(i<5){ continue; //Skips this iteration } printf("Hello %d n" , i); }; } www.SunilOS.com 40
  • 41. www.SunilOS.com 41 Add two numbers  #include <stdio.h>  void main () {  int n1 = 5 ;  int n2 = 10 ;  int sum ;   sum = n1 + n2;   printf("Num 1 %d n" , n1);  printf("Num 2 %d n" , n2);  printf("Sum %d n" , sum);  printf("%d = %d + %d n" , sum, n1, n2);  }
  • 42. Using functions  Function is a set of statements that performs a particular task.  It is independent and reusable block of code.  It can be called from other functions.  It takes number of parameters or no parameters.  After executing its task it may or may not return a value.  We already have seen a library function printf()  Syntax o returnValue functionName ( dataType param1, dataType param2, .. ) {.. } www.SunilOS.com 42
  • 43. Define a function  void main () {  int a = 5 ; int b = 10 ;  int maxValue ;  maxValue = max(a,b);  printf(" Max of %d and %d is %dn" , a, b, maxValue);  }  int max (int a, int b){  if (a > b){  return a;  }else{  return b;  }  } www.SunilOS.com 43 Function definition Return value Return value Function call Parameters
  • 44. Arrays List of same type of elements. Fix size list. Elements are accessed by Index number. Index number is started by 0. Made of contiguous memory locations. Declared as o dataType arrayName[arraySize]; o int table[10] ; // integer array of size 10 www.SunilOS.com 44 20 [0] 18 .. 10 8 6 4 2 [1] [8] [9] [2] [3] [4] [n]
  • 45. www.SunilOS.com 45 One Dimension Array 20 [0] 18 .. 10 8 6 4 2 [1] [8] [9] [2] [3] [4] [n] int table[10]; int a = table[4]; int a = table[2]; printf("%d", table[2]);
  • 46. www.SunilOS.com 46 Initialize an Array 20 [0] 18 .. 10 8 6 4 2 [1] [8] [9] [2] [3] [4] [n] int table[10]; table[0] =2; table[1] =4; … Or int table[] = {2,4,6,8,10,12,14,16,18,20};
  • 47. Print All elements of Array void main () {  int table[] = {2,4,6,8,10,12,14,16,18,20};  int i ;  for(i=0; i<10;i++){  printf("Table[%d] : %d n",i, table[i]);  } } www.SunilOS.com 47 OUTPUT Table[0] : 2 Table[1] : 4 Table[2] : 6 Table[3] : 8 Table[4] : 10 Table[5] : 12 Table[6] : 14 Table[7] : 16 Table[8] : 18 Table[9] : 20
  • 48. www.SunilOS.com 48 Other Data Type Arrays char chList[5]; chList[0] = ‘A’…. o Or char[] chList = {‘A’,’B’,’C’,’D’,’E’} double balance[5] ; balance[1] = 2.0; o Or double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
  • 49. www.SunilOS.com 49 [0] 20 18 .. 10 8 6 4 2 [1] [8] [9] [2] [3] [4] [n] 30 27 .. 15 12 9 6 3 40 36 .. 20 16 12 8 4 90 81 .. 45 36 27 18 9 100 90 .. 50 40 30 20 10 … [0] [1] [2] [7] [8] Multidimensional Arrays – 2D //Declare array int table[10][9] ; //Assign values table[0][0] =2; table[1][1] =6; …
  • 50. M-Array Initialization  int table[2][3] = {{1,2,3},{4,5,6}}; OR  int table[][3] = {{1,2,3},{4,5,6}}; OR  int table[2][3] = {{1,2,3,4,5,6}}; Print all elements of 2D array  void main () {  int table[2][3] = {{1,2,3},{4,5,6}};  int i,j ;  for(i=0; i<2;i++){  for(j=0; j<3;j++){  printf("Table[%d][%d] : %dn", i, j, table[i][j]);  }  }  } www.SunilOS.com 50 OUTPUT Table[0][0] : 1 Table[0][1] : 2 Table[0][2] : 3 Table[1][0] : 4 Table[1][1] : 5 Table[1][2] : 6
  • 51. www.SunilOS.com 51 3D Array 20 [0] 18 .. 10 8 6 4 2 [1] [8] [9] [2] [3] [4] [n] 30 27 .. 15 12 9 6 3 40 36 .. 20 16 12 8 4 90 81 .. 45 36 27 18 9 100 90 .. 50 40 30 20 10 [0] [1] [2] [8] [9] 20 18 .. 10 8 6 4 2 30 27 .. 15 12 9 6 3 40 36 .. 20 16 12 8 4 20 18 .. 10 8 6 4 30 27 .. 15 12 9 6 20 18 .. 10 8 6 4 2 30 27 .. 15 12 9 6 3 40 36 .. 20 16 12 8 4 90 81 .. 45 36 27 18 9 100 90 .. 50 40 30 20 10 90 81 .. 45 36 27 18 9 100 90 .. 50 40 30 20 10 … [0] [1] [2]
  • 52. www.SunilOS.com 52 What’s an operator? Operators are tokens that trigger some computation when applied to variables. Operators can be categorized into: o Arithmetic operators o Relational operators o Logical operators o Bitwise operators o Assignment operators o Misc operators
  • 54. www.SunilOS.com 54 Unary operators Operator Description Example () Group expression a = (b+c) * d; + Unary plus a = +5; - Unary Minus a = -5; ~ Bitwise complement a = ~b; ! Logical negation if ( !(a == b){…} ++ Pre or Post increment ++i ; or i++; -- Pre or Post decrement --i ; or i--; Used with one operand (value)
  • 55. www.SunilOS.com 55 Unary operators Why value of count variable is different in pre and post increments? i = 0; count = 2 + i++; i = 0; count = 2 + i++; ii countcount 11 22 i = 0; count = 2 + ++i; i = 0; count = 2 + ++i; ii countcount 11 33
  • 56. www.SunilOS.com 56 Binary operators  yyyy OperandOperand xxxx OperandOperand OperatorOperator
  • 57. Arithmetic binary operators Operator Description Example + Plus a = b + c; - Minus a = b - c; * Multiply a = b * c; / Division a = b / c; % Reminder a = b % c; www.SunilOS.com 57 void main () { int a =5; int b =2; int r; r =a%b; printf("Reminder value : %d n", r); } Try
  • 58. www.SunilOS.com 58 Assignment binary operators == AssignmentAssignment  Assignment is a binary operator.  The left-hand operand of an assignment must be an LVALUE.  An LVALUE is an expression that refers to a region of memory. o Names of variables are LVALUES. o Names of functions and arrays are NOT LVALUES.
  • 59. www.SunilOS.com 59 Binary operators void main () { int result, val_1, val_2; result = (val_1 = 1) + (val_2 = 2); printf("val_1 = %d n",val_1); printf("val_2 = %d n",val_2); printf("result = %d n", result); } void main () { int result, val_1, val_2; result = (val_1 = 1) + (val_2 = 2); printf("val_1 = %d n",val_1); printf("val_2 = %d n",val_2); printf("result = %d n", result); } val_1 = 1 val_2 = 2 result = 3 val_1 = 1 val_2 = 2 result = 3
  • 60. www.SunilOS.com 60 Binary operators Expressions involving only integers are evaluated using integer arithmetic. float result; int i=25; int j=10; result = i/j; printf("Result %f", result); float result; int i=25; int j=10; result = i/j; printf("Result %f", result); resultresult 2.02.0
  • 61. www.SunilOS.com 61 Binary operators Expressions involving only integers are evaluated using integer arithmetic. float result; int i=25; int j=10; result = (float) i/j; printf("Result %f", result); float result; int i=25; int j=10; result = (float) i/j; printf("Result %f", result); resultresult 2.52.5
  • 62. www.SunilOS.com 62 Assignment binary operators Operator Description Example += Assign sum a += a; -= Assign difference a -= a; *= Assign product a *= a; /= Assign quotient a /= a; %= Assign reminder a %= a; Compound operators provide a convenient shorthand. int i; i = i + 5; //or i += 5; int i; i = i + 5; //or i += 5;
  • 63. www.SunilOS.com 63 Relational binary operators Operator Description Example < Less than if( a > b ) {..} > Greater than if( a < b ) {..} >= Greater than equal to if( a >= b ) {..} <= Less than equal to if( a <= b ) {..} == Equal to if( a == b ) {..} != Not equal to if( a != b ) {..} Try above examples with following variable values int a = 10; int b = 20
  • 64. Relational binary operators A ZERO value is considered logical false and Non-ZERO value is considered true value in logical operators. www.SunilOS.com 64 void main () { int i= 0; //change to +ve value if(i){ printf("true %d",i); }else{ printf("false %d", i); } } Try
  • 65. www.SunilOS.com 65 Logical binary operators Operator Description Example && Logical AND if( a > b && b > c) {..} || Logical OR if( a < b || b > c) {..} ! Logical NOT – reverse the logical state if ( !( a == b ) ) {..} Try above examples with following variable values int a = 10; int b = 20; int c = 40;
  • 66. www.SunilOS.com 66 Binary operators Expressions connected by && and || are evaluated from left to right. void main () { int i=0; int flag = ((2<3) || (0<i++)); printf("Test: %d n" , flag); printf("I: %d",i); } void main () { int i=0; int flag = ((2<3) || (0<i++)); printf("Test: %d n" , flag); printf("I: %d",i); } Test: 1 I:0 Test: 1 I:0 This never gets evaluated! This never gets evaluated!
  • 67. www.SunilOS.com 67 Bitwise binary operators Operator Description << Shift Left >> Shift Right & Bitwise AND | Bitwise OR ^ Bitwise XOR ~ Unary bitwise complement It works on bits and perform bit-by-bit operation.
  • 68. Truth Table of Binary Operators a b a & b a | b a ^ b 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 www.SunilOS.com 68
  • 69. www.SunilOS.com 69 Unary bitwise complement 1 1 11 0 101 ~ 1 Byte 0 0 00 1 010 int a = 10; int b = ~a; www.binaryhexconverter.com/binary-to-decimal-converter
  • 70. www.SunilOS.com 70 Left Shift << 1 1 01 0 101 << 1 Byte 1 0 10 0 001 int a = -101; int b = a<<2; 1 1 Value of b will be -20
  • 71. www.SunilOS.com 71 Right Shift >> 1 1 01 0 101 >> 1 Byte 1 0 10 1 100 int a = -101; int b = a>>2; 1 0 Value of b will be -25
  • 72. www.SunilOS.com 72 And bitwise & 0 0 00 1 010 & 1 Byte 0 0 11 1 001 int a = 10; int b = 60; int c = a & b; 0 0 00 1 000 Value of c will be 8
  • 73. www.SunilOS.com 73 OR bitwise | 1 1 01 0 101 | 1 Byte 0 0 11 1 100 int a = -101; int b = 57; int c = a | b; 1 1 11 1 101 Value of c will be 125
  • 74. www.SunilOS.com 74 XOR bitwise ^ 1 1 01 0 101 ^ 1 Byte 0 0 11 1 100 int a = -101; int b = 57; int c = a ^ b; 1 1 10 1 011 Value of c will be -94
  • 75. www.SunilOS.com 75 XOR bitwise ^ 1 1 01 0 101 ^ 1 Byte 0 0 11 1 100 byte a = 10; int b = 20; int c = a ^ b; 1 1 10 1 001
  • 76. www.SunilOS.com 76 Ternary operators a?x:ya?x:y “if a then x else y” Conditional result = (x<y) ? x : y;result = (x<y) ? x : y;
  • 77. Miscellaneous Operators Operator Description Example sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 4. & Returns the address of a variable. &a; returns the actual address of the variable. * Pointer to a variable. *a; www.SunilOS.com 77 void main () { int a =10; int *b = &a; printf("value of c : %d n", a); printf("value of c : %p n", &a); printf("value of c : %p n", b); } Try
  • 78. www.SunilOS.com 78 Operator Precedence int a = 2+ 4 + 8; int a = 2+ 4 * 8; int a = b = c = 5;
  • 79. Operator Precedence Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right www.SunilOS.com 79
  • 80. www.SunilOS.com 80 Precedence Operators have the precedence. Higher precedence operator will be evaluated before the lower precedence operator. o int data = a * b + c ; since * (multiply) has higher precedence than + (plus) so a & b will be multiplied first then result will be added to c. Expression is equivalent to o int data = (a * b) + c ;
  • 81. Variable Scope  A scope is a region of the program where a defined variable can be accessed.  Outside its scope variable can not be accessed.  There are 3 places where variable can be defined: o Inside a function or a block which is called Local variable. It will be accessible only inside block or function. o Outside of all functions which is called Global variable. It will be accessible in all functions of its program. o As function parameter which are called formal parameter. www.SunilOS.com 81
  • 82. Local Variable Declared inside a function or block. Accessible to statements inside that function or block of code. Can’t be accessed outside function or block. void main () {  int a=10; //local variable  int b=15; //local variable  printf ("Value of a = %d", a); } www.SunilOS.com 82
  • 83. Global Variable It is defined outside a function, usually on top of the program. It exist in memory throughout the lifetime of your program. It can be accessed inside any of the functions defined for the program. A program may have global and local variables of same name but the value of local variable inside a function will take preference. www.SunilOS.com 83
  • 84. Global example  int g = 20; //global variable  int gl = 20; //global variable  void main () {  int l = 10; //local variable  int gl = 10; //local variable  printf ("l = %dn", l);  printf ("g = %dn", g);  printf ("gl = %dn", gl);   printVal();  }  int printVal(){  printf (“Print Val g = %dn", g);  } www.SunilOS.com 84 Try OUTPUT l = 10 g = 20 gl = 10 printVal g = 20
  • 85. Initializing Local and Global Vs It is good programming practice to initialize variables properly. Global variables are initialized automatically by the system at the time of declaration. Data type int, float, double are initialized by 0, char is initialized by ‘0’ character, and pointer is initialized by NULL. Local variables are NOT initialized at the time of declaration. www.SunilOS.com 85
  • 86. Reserved Keywords auto else long switch break enum register typedef case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double www.SunilOS.com 86
  • 87. Pointers  It is a variable.  A pointer variable stores a memory address of another variable .  Memory address can be accessed by ampersand (&) operator.  Here p is a pointer variable that stores address of a: o int a = 1; o int *p = &a; www.SunilOS.com 87
  • 88. Pointers ( Cont. )  #include <stdio.h>  void main () {  int a = 10;  int *p = NULL;  //store address of ‘a’ in pointer variable  p = &a ;  printf("Address of a : %xn", &a );  printf("Address stored in p : %xn", p );  printf("Value of *ip variable: %dn", *p );  } www.SunilOS.com 88 0 0 00 1 010 int a = 10; a= 1110 int *p = &a; 1 011 p= 1100 OUPUT Address of a : 7903aab4 Address stored in p : 7903aab4 Value of *ip variable: 10
  • 89. Pointers (Cont. ) Pointers must be defined before using them. Pointer can be of any C data type: o int *ip ; o char *cp; o float *fp; o double *dp NULL Pointers o It is recommended to initialize a pointer by NULL value. o int *p = NULL; o If a pointer has NULL value then it is called NULL pointer. www.SunilOS.com 89
  • 90. Passing parameters to Function There are two ways to pass parameters to a function: Pass by Value: C creates a local copy of this variable. All the changes made on local copy will not impact original variable. Pass by Reference: In this case address of the variable is passed to function. Any changes made on this address will change the value of original variable. www.SunilOS.com 90
  • 91. Pass by reference example  void test(int a, int *p){  a = 20; //Make changes on local copy  *p = 20; //Make changes on address, will change original variable  }  void main () {  int a = 10; int b = 10;   //Pass value of ‘a’ and address of ‘b’  test (a, &b);  printf(" a = : %dn", a );  printf(" b = : %dn", b );  } www.SunilOS.com 91 OUTPUT a = : 10 b = : 20
  • 92. Structure and Union Both are custom data types defined by users. Structures are defined using struct key word. www.SunilOS.com 92
  • 93. Structure It is user defined data type. That combines basic data types to make custom data type. It can combine different type of data types. Custom Data types can be used as basic data types. o struct telephone {  char *name;  int number; o }; www.SunilOS.com 93
  • 95. File Handling and IO www.SunilOS.com 95
  • 96. String Handling  void main(){ o int i,j; o char name[10], nameCopy[10]; //Define char arrays o printf(“Enter first String :”); o scanf(“%s”,name); //Get string from Keyboard o printf(“n %s”,name); // Print string at console o i=strlen(name); // Length of String o printf(“length of name is :%d”,i); o strcpy(nameCopy,name); //Copy a string o printf(“n %s”, nameCopy); } www.SunilOS.com 96
  • 97. Recursion ( Cont.) When a function call itself, called recursion. o int disp(int x){ o int f ; o if(x ==1 ){ o f = x ; o }else{ o f = x * disp(x-1); o } o return f; o } www.SunilOS.com 97
  • 98. Recursion o void main(){ o int a, fact; o a=5; o fact = disp(a); o printf(“Factorial is: %d”,fact); o getch(); o }... www.SunilOS.com 98
  • 101. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 101