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

C PROGRAMMING

FOR PROBLEM SOLVING


(18CPS23)
MODULE 1
OVERVIEW OF C

Prof. Mahalakshmi C V, Assistant Professor, CSE, BIT


Email: mahalakshmicv@gmail.com
Website: https://sites.google.com/site/mahalakshmicvbitcse
HISTORY OF
C
INTRODUCTION TO C LANGUAGE

 Program development is a multistep process which


requires steps like understanding the problem,
developing a solution, writing the program and testing
it.
 There are three tools to develop the solution
 Pseudo code
 Flowchart

 Algorithm
PSEUDO CODE
 Pseudo code to perform addition of two number
Begin
Input a,b
sum=a+b
print sum
End
ALGORITHM
 A logical and concise list of steps required to solve a problem is
called algorithm.
 Languagically representation of the various steps involved in
solving problem is called algorithm.
 Points for developing an algorithm
 Name of the algorithm
 Step number
 Explanatory statement following the step number
 Termination
EXAMPLE
 Algorithm to perform addition of 2 numbers
Algorithm: To find sum of 2 number
Step 1:Start
Step 2: [input the values of a and b]
Read a,b
Step 3:[ find the sum]
sum<-a+b
Step 4:[output the result]
print sum
Step 5:[finished]
Stop
FLOWCHART
 A flowchart is a pictorial representation of an algorithm.
 Benefits of using flowcharts are
 Being a pictorial representations they are easier to understand.
 We can review our logic and debug the program with the help of
flowcharts.
 Easy to explain a program or discuss the solution.
 It separates the logic development and program syntax.
EXAMPLE
BASIC STRUCTURE OF C PROGRAMS
 PREPROCESSOR DIRECTIVES #INCLUDE<STDIO.H>
 GLOBAL DECLARATIONS
 VOID MAIN()
 {
 LOCAL DECLARATIONS
 STATEMENTS
 }
 COMMENTS
 BLOCK /*--------------------*/
 LINE //
EXECUTING A ‘C’
PROGRAM
 WRITE A C PROGRAM TO ADD TWO NUMBER
#include<stdio.h>
void main()
{
int a=5,b=6,sum;
sum=a+b;
printf(“sum=%d\n”,sum);
}
or
#include<stdio.h>
main()
{
int a,b,sum;
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“sum=%d\n”,sum);
}
FORMATTED INPUT
 It refers to an input data that has been arranged in a particular
format.

scanf(“control string”,arg1,arg2,…argn);

control string specifies field format in which data has to be


entered and arguments specify the address of locations where data is
stored.
FORMATTED OUTPUT
 Printf statement is used for formatted output to print captions and
numerical result on the terminal

printf(“control string”,arg1,arg2….argn);
SAMPLE PROGRAMS
 Write a C Program to add two numbers.
#include<stdio.h>
void main()
{
int a,b,c;
printf("\n Enter two numbers");
scanf("%d%d",&a,&b);
c=a+b;
printf("\n Sum=%d\n",c);
}
 Write C Program to demonstrate the use of arithmetic operators
#include<stdio.h>
void main()
{
int a,b;
printf("\n Enter two numbers\n");
scanf("%d%d",&a,&b);
printf("\n Sum=%d",(a+b));
printf("\n diff=%d",(a-b));
printf("\n product=%d",(a*b));
printf("\n Quatient=%d",(a/b));
printf("\n remainder=%d",(a%b));
}
 Write a C Program to display the ASCII value of given character
#include<stdio.h>
void main()
{
char c;
int a;
printf("\n Enter a character");
scanf("%c",&c);
a=c;
printf("\n ASCII value of %c=%d",a,c);
}
C TOKENS
 A token refers to the smallest unit of a C program.
 The following are the C tokens:
 Keywords
 Identifiers
 Constants
 Operators
 Special symbols
KEYWORDS
 Keywords are the tokens which have predefined meaning in C
language used to perform a specific task.
 They are also known as reserved word
 All keywords should be written in lower case.
 Ex: if, else, for, while, int, void, char etc..
IDENTIFIERS
 Identifiers are the names given to the various program elements such as
variable, constants, function, array names etc…
 The rules for identifiers are as follows:
1 . First character must be alphabets or underscore
Ex: a, name , _a
2 . Identifiers must consists only of alphabets, digits or underscore, where as special
symbols and blank spaces are not allowed.
Ex: a1 , student_name
3 . Cannot duplicate a keyword or reserved word.
Ex: int , void, char etc cannot be used as a identifier.
4 . First 63 characters of an identifier are significant.
Ex: if the identifier is more then 63 characters, then only first 63 characters are used.
5 . Two successive underscores are not allowed.
Ex: student_name : valid
studen_ _name : invalid
6 . C is a case-sensitive language.
Ex : sum , SUM
Both the names are considered as different identifiers in the program.
DATA TYPES
 A data type defines the type of data that a variable can hold.
 It also defines a set of values and set of operations that can be applied on those values.
 It determines how mush memory should be allocated for a variable.
1. Void type
2 . Integral type
a . Boolean- bool
b . Character-char-ASCII
0-9=48-570
A-Z=65-90
a-z=97-122
c . Integer.-int
sizeof()-ex: sizeof(int)
3. Floating point types
a. Real-float,double, long double
b. Imaginary-float imaginary,double imaginary, long double
c. Complex
#include<stdio.h>
main()
{
int a,b,c;
a=sizeof(int);
b=sizeof(char);
c=sizeof(float);
printf(“the size of int=%d\n”,a);
printf(“the size of char=%d\n”,b);
printf(“the size of float=%d\n”,c);
}
Or
#include<stdio.h>
main()
{
printf(“the size of int=%d\n”,sizeof(int));
printf(“the size of char=%d\n”,sizeof(char));
printf(“the size of float%d\n”,sizeof(float));
}
CONSTANTS
 Constants are the data values that cannot be changed during the execution of a
program.
 These are classified into:
 Boolean constants- stdbool.h
 Character constants[‘a’] [\]
 String constants[“ “] ex:”h”, “hello” “ ”
 Char a=“bit”
 1110
 Integer constant int-%d-%ud-%ld
 Real constant
 Complex constants{I}
 12.3+14.4*I
CHARACTER CONSTANTS
 \ -escape character
 Ex: ‘n’
 \n-newline
 \t-horizontal tab
 \v-vertical tab
 \b-backspace
 \0-null
 \a-alert
 \f-formfeed
 \r-carriage return
 \”
 \’
 \?
 \\
CODING CONSTANTS
 There are three ways to code/define constants in program
 Literal constant
 Ex: a=b+5;

 Defined constant
 #define
 Ex: #define Pi 3.14
 Main()
 {
 A=b*Pi
 }

 Memory constant
 Const
 Syntax: const type identifier=value;
 Ex: const float cpi=3.14;
#include<stdio.h>
#define PI 3.1416 // define constant
void main()
{
const float cpi=3.1416; //memory constant
printf(“ literal constant:%f\n”,3.1416); //literal constant
printf(“ defined constant:%f\n”,PI);
printf(“memory constant:%f\n”cpi);
}
 Output
literal constant:3.141600
defined constant:3.141600
memory constant:3.141600
VARIABLES
 Variables are named memory locations that have a type such as integer or
character etc
 Variable declaration and defined
Declaration: used to name an object.
Definition: used to create an object.
Syntax: data_type variable_list;
Ex: int a,b;

 Variable initialization/assignment
 The process of assigning a value to a variable is called as initialization of a variable.
 Syntax: variable_name=value;
 Ex: a=10;
 We can initialize a variable at the same time when we declare it by
including an initializer.
 Ex: int a=10;
 Char c=‘a’;
INPUT/ OUTPUT FUNCTIONS
 I/O types
 Formatted I/O
 Input function- scanf()
 Output function- printf()

 Unformatted I/O
 Input functions
 getch()
 getche()

 gets()

 getchar()

 Output functions
 putch()
 putche()

 puts()

 putchar()
OUTPUT FORMATTING: PRINTF()
 The printf function converts data stored in the program into text
stream for output to the monitor.

 Syntax: printf(“format control string”,list of variables);


 the parameter passed to printf function are
 Format control string which includes:
 Textual data to be inserted into the text stream

 Contains zero or more “conversion specifications”

 Contains control characters[escape characters]


 Ex:
 Conversion specification for printf function
% Flag Minimum precision size code
width
 %: start token
 Code: ex:%d, %c, %s, %f
 Size: h[%hd], l[%ld], ll[%lld], L[%Lf]
 Minimum width: used to specify the minimum number of positions
in the output.
 Precision: used for floating point number. It specifies the number of
decimal places to be printed.[.m]
 Ex: printf(“%.2f”,3.1427); //output: 3.14
 printf(“%f”,3.1427); //output: 3.142700
 Flag: there are 3 flags:
 justification
 Right justification

 Left justification: -
0 0 1 . 2 0
 Ex: printf(“%6.2f”,1.2);

 printf(“%-6.2f”,1.2);

 padding
 Space

 Zero
1 . 2 0
 print(“%-06.3f”,1.2568498);

 Sign
 Default formatting

 Ex: int a=10,b=-5;

 printf(“%d”,a); //10

 printf(%d”,b); //-5
 Print signed values

 Ex: int a=10,b=-5;

printf(“%+d”,a); //+10
printf(“%+d”,b); //-5
INPUT FORMATTING: SCANF()
 It converts the text stream given from the keyboard into values and
stores it in program variables.

 Syntax: scanf(“format control string”,address list);


 Ex: scanf(“%d %d”,&a,&b);
 Ex: scanf(“%d/%d/%c”,&a,&b,&c); 6 5 K
 SCANF(“ %C”,&CH);
 Scanf(“%c %c %d”,&a,&b,&c);
 Conversion specification for scanf function
% Flag Maximum size code
width

 There are only three optional modifier


 There is no precision.
 There is only one flag
 *: assignment suppression
 Ex: scanf(“%d%c%*f”);
 Maximum width: it specifies the maximum number of characters
that are to be read.
UNFORMATTED INPUT/OUTPUT
 this function works with character datatype[char]
 getchar() and putchar()

 Syntax:

char ch;
ch=getchar();
putchar(ch);
 Ex:

#include<stdio.h>
void main()
{
char ch;
ch=getchar();
putchar(ch);
}
 gets() and puts()
 Syntax:

char str1[10];
gets(str1);
puts(str1);
 Write a C program to swap two numbers.
#include<stdio.h>
void main()
{
int a,b,temp;
printf(“enter two number”\n);
scanf(“%d%d”,&a,&b);
printf(“the a =%d\t b=%d before swapping\n”,a,b);
temp=a;
a=b;
b=temp;
printf(“a=%d \t b=%d after swapping\n”,a,b);
}
 Write a c program to compute area of circle.
#include<stdio.h>
void main()
{
int area,r;
printf(“enter the radius\n”);
scanf(“%d”,&r);
area=3.14*r*r;
printf(“the area of circle is=%d\n”,area);
}
EXPRESSION
 An expression is a sequence of operands and operators that reduces to single value.
 Expression can be :
1. Simple Expression:
Ex: 2+5
2. Complex Expression
Ex: 2+5*7
2+35
37
2*5*7
10*7
70
 Precedence:
The order in which the operators in a complex expression are evaluated is
determined by a set of priorities.
 Associativity:
If two operators with the same precedence occurs in a complex expression, then
associativity will follow the direction.
EXAMPLE
 2+5*7
 3*4/6
EXPRESSION CATEGORIES
 A simple expression is divided into 6 categories based on
1. number of operands
2. relative positions of the operand and operator
3. the precedence of operator.
Those are:
1. Primary Expression: Names(Ex: a,sum), Literal
Constants(Ex:5,123.96,’A’),Parenthetical Expression(Ex:2*(2*3+4))
2. Postfix Expression
3. Prefix Expression
4. Unary Expression
5. Binary Expression
6. Ternary Expression
POSTFIX AND PREFIX EXPRESSION
Postfix Prefix
Consists of one operand followed by The operator comes before the
one operator. operand
Syntax: operand operator Syntax: operator operand
a++, a-- ++a, --a
Function call[a()] Prefix increment[++a]
Postfix increment[a++] Prefix decrement[--a]
Postfix decrement[a--]
Precedence is 16 Precedence is 15
a++ as a=a+1 ++a as a=a+1
The increment takes place after the The increment takes place before the
expression is evaluated expression is evaluated
A=5 A=5
A++=5 ++a=6
A=6 A=6
a– as a=a-1 --a as a=a-1
A=4 A=4
A--=4 --a=3
#include<stdio.h>
void main()
{
int a;
a=4;
printf(“value of a:%d\n”,a);
printf(“the value of a++:%d\n”,a++);
printf(“ the value of a:%d”,a);
}
Output:
Value of a: 4
Value of a++:4
Value of a:5
#include<stdio.h>
void main()
{
int a;
a=4;
printf(“value of a:%d\n”,a);
printf(“the value of ++a:%d\n”,++a);
printf(“ the value of a:%d”,a);
}
#include<stdio.h>
void main()
{
int a;
a=4;
printf(“value of a:%d\n”,a);
printf(“the value of a--:%d\n”,a--);
printf(“ the value of a:%d”,a);
}
#include<stdio.h>
void main()
{
int a;
a=4;
printf(“value of a:%d\n”,a);
printf(“the value of --a:%d\n”,--a);
printf(“ the value of a:%d”,a);
}
UNARY EXPRESSION

 It consists of one operator and one operand


syntax: operator operand
1. sizeof: Ex: sizeof(int)
2. Unary plus/minus:
1. Plus operator
2. Minus operator.
Ex1: a=3 Ex2:a=-5
+a=+3 +a=-5
-a=-3 -a=+5
3. Cast operator:
Ex: int x;
float(x);
BINARY EXPRESSION

 Binary Expression are formed by an operand-operator-operand


combination.
Syntax: Operand operator operand
1. Multiplicative Expression
1. Multiply (*).
1. Ex: 10*3
2. true*3
3. ‘A’*2
4. 22.3*2
2. Divide(/)
1. Ex: 10/3
1. True/4
2. ‘A’/2
3. 22.3/2
3. Modulus(%)
Ex: 10%3
1. True%4
2. ‘A’%10
3. 22.3%2
3. Additive Expression
Ex: 3+7
3-7
4. Assignment Expression
1. Simple assignment
Ex: a=5
b=x+1
i=i+1
2. Compound assignment

Ex: a+=5 which is evaluated as a=a+5


x*=y+3--X=X*(Y+3)

Compound Expression Equivalent Simple


Expression
a*=expression a=a*expression
a/=expression a=a/expression
a%=expression a=a%expression
a+=expression a=a+expression
a-=expression a=a-expression
RELATIONAL OPERATORS
 It is used to test the relation between two entities.
 Zero=false
 Non zero= true
 The different relational operators are
 <, <=, >, >=, ==,!=
 Ex: 5==3
 5==5

 5>3

 5>=5

 5<3
A program to illustrate the use of relational operators
#include<stdio.h>
void main()
{
printf(“\n 4>5:%d\n”,4>5);
printf(“\n 4>=5:%d\n”,4>=5);
printf(“\n 4<5:%d\n”,4<5);
printf(“\n 4<=5:%d\n”,4<=5);
printf(“\n 4==5:%d\n”,4==5);
printf(“\n 4!=5:%d\n”,4!=5);
}
LOGICAL OPERATORS
 The different logical operators are
 ! [Negation]
 Ex: a=0

!a=1
 && [Logical AND]
 Ex: if((5>2)&&(5>3))

 || [Logical OR]
 Ex: if((a==0)||(b==0)||(c==0))
 Write a C program to swap two numbers without using temp
variable.
 Write a C program to find the area and circumference of circle
 Write a C program to find the area of equilateral triangle
BITWISE OPERATORS
 There are 6 bit operators in c
 &[AND]
 | [OR]
 ^ [XOR]
 ~[COMPLEMENT]
 << [left shift]
 >> [right shift]
1. & [AND]
Ex: a=5, b=4
c=a&b
a=00000101
b=00000100
00000100 which is equal to 4
c=4
2. | [OR]
Ex: c=a|b
a=00000101
b=00000100
00000101 which is equal to 5
c=5
3. ^ [XOR]
Ex: c=a ^b
a=00000101
b=00000100
00000001 which is equal to 1
c=1
4. ~[COMPLEMENT]
Ex: a=5 00000101
b=~a 11111010
5. << [Left shift]
Ex: a=5
b=a<<1; A=10 ;B=A>>1
0 0 0 0 0 0 1 0 1

0 0 0 0 1 0 1 0 0

b=10
6. >> [Right Shift]
Ex: a=10
b=a>>2;

0 0 0 0 1 0 1 0 0

0 0 0 0 0 0 1 0 1

b=5
CONDITIONAL OPERATORS[TERNARY
OPERATOR]
Syntax: exp1?exp2:exp3

Exp1 is evaluated first, if true and then exp2 is evaluated, if exp1 is


false, then exp3 is evaluated.

Ex: a=25, b=95

result= a>b? a:b

//false
EXAMPLE
 Precedence:
 2+3*4=14
 -b++
 Associativity:
 3*8/4%4*5
 a +=b*=c-=5; a=3,b=5,c=8
 Side Effects
 A side effects is an action that results from the evaluation of an expression.
 Ex: x=4
x=x+4
x=8
 There are six operators that generates side effects
 Postfix increment & decrement (a++,a--)
 Prefix increment & decrement (++a,--a)
 Assignment (=)
 Function call (fun())
EVALUATING EXPRESSIONS
 Expressions without side effects
 Ex: a * 4 + b / 2 – c * b
 Consider
 a= 3
 b= 4

 c= 5

Step1 : replace the variables by their values


3*4+4/2-5*4
Step 2: evaluate the highest precedence operator
(3*4)+(4/2)-(5*4)
12+2-20
Step 3: repeat step 2
14-20
-6
EXPRESSION WITH SIDE EFFECTS
 Ex: --a*(3+b)/2-c++*b
 a=3
 b=4
 c=5

A=2
B=4
C=6
 WRITE A C PROGRAM TO EVALUATE THE GIVEN
EXPRESSIONS(TAKE A=3,B=4,C=5)
X=A*4+B/2-C*B;
Y=--A*(3+B)/2-C++*B;
TYPE CONVERSION
 Implicit Type Conversion
When the types of the two operands in a binary
expression are different, C automatically converts one type to
another. This is known as implicit type conversion.
Real
 Conversion Rank
9. Long double
8. Double
Integer 7. float
6. Long long
5. Long
4. int
Character 3. short
2. char
Boolean
1. bool
CONVERSIONS IN ASSIGNMENT
EXPRESSIONS
 A simple assignment involves an assignment operator & two
operands.
 C tries to either promote or demote the right expression to make it the same
rank as the left variable.
 Promotion occurs if the right expression has lower rank.
 Ex: bool b = true;
int i = 1234;
i=b; // value of i is 1
 Ex: char c = ‘A’;
int i = 1234;
i=c; // value of i is 65
 Ex: int i = 1234;
float d = 125.502
d=i; // value of d is 1234.0
 Demotion occurs if the right expression has a higher rank.
 Ex: int a=0;
bool b;
b=a;
 int i=65;
char c;
c=i; c=A
c=i+1; c=B
 Int i=65;
 Flaot f=125.25;
 i=f; i=125
CONVERSION IN OTHER BINARY
EXPRESSIONS
 The operand with higher rank is determined using the ranking
 The lower-ranked operand is promoted to the rank defined in step 1.
 The operation is performed with the expressions having the type of
promoted rank
 EX: bool b=true;
char c=‘A’;
int i=365;
float f=2.5;
b+c; //result B
i*f;
EXPLICIT TYPE CONVERSION
 Rather than let the compiler implicitly converting the data, we can
convert data from one type to another using explicit type
conversion.
 To cast data from one type to another, we specify the new type in
parentheses before the value we want to convert.
 Ex: int a=5;
(float)a;
 In the above Ex, the value stored in a is still of type int, but the
value of the expression is promoted to float.

You might also like