The document provides information about the C programming language. It discusses that C is a procedural language that is case sensitive and can be compiled on various platforms. It also provides examples of C programs, including printing "Hello World", using data types like int and float, and control structures like if-else statements and for loops. The document contains code snippets to demonstrate basic C programming concepts.
www.SunilOS.com 2
C isa 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 andRun on multiple OS
It can be compiled on variety of platforms.
Compile
Linux
Hello.c
Compile
MacOS
Compile
Windows
4.
An approachto 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?
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 isa 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
Variables
Memory areathat 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 iscase 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
TypeDescription ( 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 typesprogram
#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.com17
Data Type
Primitive Derived User Defined
char
int
float
double
void
array
pointer
function
enum
structure
union
18.
Data Types
Primitive datatypes 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 keywordsused 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 shortint 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
Modifiers ( Cont.)
Keyword
Identifier
(FormatSpecifier) 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.com23
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 tofixed 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 thefix 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
oValue 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
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
Using functions
Functionis 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 sametype 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 52
What’s anoperator?
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 54
Unary operators
OperatorDescription 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
Whyvalue 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
Arithmetic binary operators
OperatorDescription 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 binaryoperators
== 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 60
Binary operators
Expressionsinvolving 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
Expressionsinvolving 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 binaryoperators
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 binaryoperators
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
AZERO 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 binaryoperators
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
Expressionsconnected 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 binaryoperators
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 ofBinary 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 bitwisecomplement
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
Miscellaneous Operators
Operator DescriptionExample
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
Operator Precedence
Category OperatorAssociativity
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 havethe 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
Ascope 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 insidea 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 isdefined 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
intg = 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 andGlobal 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 elselong 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 isa 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. )
Pointersmust 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 toFunction
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 referenceexample
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
Bothare custom data types defined by
users.
Structures are defined using struct key
word.
www.SunilOS.com 92
93.
Structure
It is userdefined 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
String Handling
voidmain(){
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.)
Whena 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(){
oint a, fact;
o a=5;
o fact = disp(a);
o printf(“Factorial is: %d”,fact);
o getch();
o }...
www.SunilOS.com 98
Disclaimer
This is aneducational 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