0% found this document useful (0 votes)
36 views82 pages

Module 1

Uploaded by

ambika venkatesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views82 pages

Module 1

Uploaded by

ambika venkatesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

MODULE 1

INTRODUCTION to C PROGRAMMING
Contents
 Algorithms, flowcharts, pseudo codes,

 structure of a C program

 writing the first C program

 keywords, identifiers
 basic data types

 variables, constants

 input / output Statements,

 Operators and Expressions, Type conversion and Typecasting.

 Branching statements

 preprocessor directives.
Algorithms

 An algorithm is a precise specification of a sequence of


instructions to be carried out in order to solve a given
problem
 Characteristics

• Be precise
• Be unambiguous
• Not even a single instruction must be repeated infinitely
• After the algorithm gets terminated, the desired result
must be obtained
Key Features of Algorithms

 Sequence

- each step of the algorithm is executed in the specified order


 Decision

- used when the outcome of the process depends on some

condition
 Repetition

- involves executing one or more steps for a number of times


Example: Computing area of a rectangle

Step 1: READ length

Step 2: READ breadth

Step 3: COMPUTE AREA

area= length * breadth

Step 4. PRINT area


Flowcharts
 Graphical representation of a process
Example: Computing area of a rectangle
Significance of Flowcharts
 Facilitates communication between programmers and users

 Make users understand the solution easily and clearly

 Help the programmers to understand the logic of complicated


and lengthy problem

Advantages
• Help to analyze the problem in a more effective manner
• Act as a guide or blueprint for the programmers to code the
solution in any programming language
Limitations
 Laborious and a time-consuming activity

 Flowchart of a complex program becomes complex and clumsy

 A little bit of alteration in the solution may require complete

re-drawing of the flowchart


 No well-defined standards that limit the details that must be
incorporated into a flowchart
Pseudocode
 Outline of a program that can easily be converted into
programming statements.
 Consists of short English phrases that explain specific tasks
within a program’s algorithm
 Purpose is to enhance human understandability of the
solution

Keywords used while writing Pseudocodes


• Do While…..EndDo
• DO Until…..EndDo
• Case……..Endcase
• If……EndIf
• Call……with(parameters)
• Call
• Return
Parts of Pseudocodes

IF condition THEN IF age>=18 THEN

sequence 1 Display Eligible to vote

ELSE ELSE
sequence 2 Display Not Eligible
ENDIF ENDIF
Parts of Pseudocodes contd…

WHILE condition THEN WHILE i<10 THEN


sequence Print i
ENDWHILE Increment i

ENDWHILE
Parts of Pseudocodes contd…

FOR iteration bounds FOR each student in the class

sequence Add 10 as bonus marks

ENDFOR ENDFOR
Example
Pseudocode to find the area of rectangle

1. Read length and breadth

2. Calculate area= length * breadth

3. Print area

4. End
Introduction to C

 The programming language C was developed in the early 1970s


by Dennis Richie at Bell Laboratories
C is one of the most popular programming languages being used
on several different software platforms
 C is well suited for structured programming

C is a core language as many other programming languages are


based on C
 C is portable and extensible language
Structure of a C Program
Writing the first C program

#include<stdio.h>
int main()
{
printf(“\n Welcome to the world of C”);
return 0;
}
Using comments

 Comments are just a way of explaining what a program does


 C supports two types of commenting

1. //: Single line comment

2. /* */ : Multiline comment
Character Set
 Characters can be used to form words, numbers and expressions
 Categories:

1. Letters

2. Digits

3. Special characters

4. White spaces
Keywords

 Sequence of characters that have fixed meaning

 Must be written in lowercase letters


Identifiers
 Names given to the program elements such as variables, arrays
and functions.
 Consist of an alphabet, digit or an underscore

Rules for forming identifiers names

1.The identifier name must begin with an alphabet or an underscore

2.It cannot include any special characters or punctuation marks


except underscore.

3.There cannot be two successive underscores.

4.Keywords cannot be used as identifiers.

5.The case of alphabetic characters that form the identifier name is


significant.
6. Identifiers can be of any reasonable length.

 Examples of valid identifiers:

roll_number, marks,name,RollNo,sum1

 Examples of invalid identifiers:

23sum, %marks, #emp_num, auto


Basic Data Types in C
Variables

 Meaningful name given to the data storage location in


computer memory.

 C language supports two basic kinds of variables:

1. Numeric variables

- used to store either integer or floating point values

2. Character Variables

- include any letter from the alphabet and numbers that are
given with single quotes
Declaring Variables
 To declare a variable, specify the data type of the variable
followed by its name

datatype varname;
 Example:

int sum;

float salary;
 Variable names should always be meaningful and must
reflect the purpose of their usage in the program.
Initializing variables
 syntax:

varname = value;
 Example:

sum=0;
 Initialization of variables can be done at the time of declaration
 Example:

int sum=0;

float salary=35000.50;
 Variables declared but not initialized usually contains garbage
values
Constants
 Identifiers whose value does not change.
Integer Constants
 An integer constant refer to a sequence of digits
 There are 3 types of integers namely:
1. Decimal integer
2. octal integer
3. hexadecimal integer
1. Decimal integer
 Decimalinteger consist of a set of digits 0 through 9,precceded
by an optional – or + sign
ex: 123 -321 0 654321 +78
Embedded spaces, commas and non-digit characters are not
permitted between digits
15 750 20,000 $1234 ----- are illegal numbers
2. octal integer
An octal integer constant consist of any combination of digits from

the set 0 through 7 with a leading 0


Ex: 037 0456 0123

3. hexadecimal integer
A sequence of digits preceded by 0x or 0X is considered as
hexadecimal integer
 They may include alphabets A through F or a through f

 Letter A through F represents numbers 10 to 15

 Ex: 0X2 0x9F 0Xbcd 0x


Floating Point Constants

 These quantities are represented by numbers containing integer


part, decimal point , a fractional part and exponent field
containing an e or E .
 Example:

215.12 .95 -.71 +.34 2.1565e2 -2.5e-8


Single Character Constants

 Contains a single character enclosed within a pair of single quote


marks
 Example: ‘5’ ‘X’ ‘;’ ‘ ‘
 Character constants have integer values known as ASCII values
 Ex: printf(“%d”,’a’); ------ prints 97
String Constants

 sequence of characters enclosed in double quotes


 Characters may be letters, numbers, special characters and
blank spaces
 Ex: “hello” , “1987”, “?...!”
 Character constant(’X’) is not equivalent to single string
constant(“X”)
 single character string constant doesn’t have an equivalent
integer value while a character constant has an integer value
Declaring Constants

 To declare a constant, precede the normal variable declaration


with const keyword and assign it a value
 Example:

const float pi=3.14;


 Another way is to use the preprocessor command define
 Example :

#define PI 3.14159

#define service_tax 0.12


 Rules that applies to #define

1. Constants names are usually written in capital letter

2. No blanks space between # and define

3. Blank space must be used between

- #define and constant name

- constant name and constant value

4. #define is a preprocessor directive and not a statement.


Therefore it doesn’t end with a semicolon.
Input / Output statement in C

 Formatting input/output

1. printf()

2. scanf()

1. printf():

- display information required by the user and also prints the


values of the variables
- Syntax:

printf(“control string”,variable list);

- Example:

printf(“%d %f\n”,var1,var2);
2. scanf()
- Used to read formatted data from the keyboard
- Syntax:

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


- Example:

scanf(“%d%f”,&var1,&var2);
Operators in C
 A symbol that specifies the mathematical, logical, or relational operation to
be performed.
 Categorized into the following groups:

1. Arithmetic operators

2. Relational operators

3. Equality operators

4. Logical operators

5. Unary operators

6. Conditional operator

7. Bitwise operators

8. Assignment operators

9. Comma operators
1. Arithmetic Operators
2. Relational Operators
3. Equality Operators
4. Logical Operators

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Logical NOT table:
Logical NOT
!True False
!False True
5. Unary Operators

UNARY OPERATORS
Minus - b=10
a=-(b) //a=-10
Increment ++ ++a //a=a+1
Decrement -- --a //a=a-1
6. Conditional Operators

 A ternary operator pair “?:” is available in C to construct


conditional expression of the form:
exp1 ? exp2 : exp3;
Here exp1 is evaluated first
- If it is true then the expression exp2 is evaluated and becomes
the value of the expression
- If exp1 is false then exp3 is evaluated and its value becomes
the value of the expression
 Ex:

a=10;
b=15;
x=(a>b) ? a : b; --- x is assigned the value of b
This can be achieved using if…else statements as follows:
if(a>b)
x=a;
else
x=b;
7. Bitwise Operators

~ Bitwise NOT
8. Assignment Operators

 Used to assign the result of an expression to a variable


 Syntax:

v = exp
where v → variable,
= → assignment operator
exp → expression
 C has a set of ‘shorthand’ assignment operators of the form

v op = exp;
where op = shorthand assignment operator
Ex: x=x+3
x+=3
9. Comma Operator

 The comma operator can be used to link the related expressions


together
 A comma-linked list of expressions are evaluated left to right
and the value of right-most expression is the value of the
combined expression
 Example : value = (x = 10, y = 5, x + y); first assigns the value 10
to x, then assigns 5 to y, and finally assigns 15(i.e,10+5) to value
10. Sizeof Operator

 The sizeof is a compiler time operator and, when used with an


operand, it returns the number of bytes the operand occupies
 The operand may be a variable, a constant or a data type
qualifier
 Ex: 1) m = sizeof(sum);
2) n = sizeof( int)
 The sizeof operator is normally used to
- determine the lengths of arrays and structures when their
sizes are not known to the programmer
- allocate memory space dynamically to variables during
execution of a program
Evaluation of Expressions

 Expressions are evaluated using an assignment statement of the


form:

variable = expression;

where variable is any valid C variable name


 When the statement is encountered, the expression is evaluated
first and the result then replaces the previous value of the
variable on the left-had side
 All the variables used in the expression must be assigned values
before evaluation is attempted
 Ex:

1) x = a * b – c;
2) y = b / c * a;
Precedence of Arithmetic Operators

 An arithmetic expression without parenthesis will be evaluated


from left to right using the rule of precedence of operators
 There are two distinct priority levels of arithmetic operators in C

High priority * / %

Low priority +-
 The basic evaluation procedure includes ‘two’ left-to-right
passes through the expression
 During the first pass, the high priority operators(if any) are
applied as they are encountered
 During second pass, the low priority operators(if any) are
applied as they are encountered
Operator Precedence
Ex: x = a – b / 3 + c * 2 - 1 where a=9,b=12,c=3

X= 9 - 12 / 3 + 3 * 2 – 1 is evaluated as follows

First pass

Step 1: x = 9 - 4 + 3 * 2 - 1

Step 2: x = 9 – 4 + 6 - 1

Second pass

Step 3: x = 5 + 6 - 1

Step 4: x = 11 - 1

Step 5: x = 10
 The order of evaluation can be changed by introducing
parenthesis into an expression
 Ex: 9 – 12 / (3 + 3 ) * ( 2 – 1 )

First pass: Second pass:

step 1: 9 -12 / 6 * ( 2 – 1 ) step 3: 9 – 2 * 1

step 2: 9 – 12 / 6 * 1 step 4: 9 - 2

Third pass

step 5: 7
 This time procedure consists of three left-to-right passes
 The number of evaluation is 5(i.e., equal to the number of
arithmetic operators)
 Parentheses may be nested, and in such cases, evaluation of the expression
will proceed outward from the innermost set of parentheses

 Note: Make sure that every opening parantheses has a matching closing
parantheses

 Ex: 9 - ( 12 / ( 3 + 3 ) * 2 ) – 1 = 4

9 – (( 12 / 3 ) + 3 * 2) – 1 = - 2

Rules for evaluation of expression

1. First parenthesized sub expression from left to right are evaluated

2. If parentheses are nested, the evaluation begins with the innermost sub
expression

3. The precedence rule is applied in determining the order of application of


operators in evaluating sub expressions

4. The associatively rule is applied when two or more operators of the same
5. Arithmetic expressions are evaluated from left to right using the
rules of precedence

6. When parentheses are used, the expressions within parentheses


assume highest priority
Type conversion and Typecasting.

 Refers to changing a variable of one data type into another

 Type conversion is done implicitly

 Typecasting has to be don explicitly by the programmer

Type Conversion
 Done when the expression has variables of different data types
 Data type is promoted from a lower to higher level
 Example:

int a=5;

float b=6.5,c;

c=a+b; // c=11.5
 If the two operands in an assignment operation are of different
type, the right hand side(RHS) of the operand is automatically
converted to the data type of left hand side(LHS)
 Example:

int a;

float b=65.5;

a=b; // a=65
Typecasting

 also known as forced conversion


 Eg: ratio = female_number / male_number
 If female_number and male_number are declared as integers the
ratio would represent a wrong figure. Hence it should be
converted to float

ratio = (float) female_number / male_number


 The general form of a cast is:

(type-name) expression

where, type-name is one of the standard C data types

expression may be a constant, variable or an expression


 Casting may be used to round-off a given value
 Ex:
x=(int) (y+0.5)
if y=27.6, the result would become 28
Branching Statements

Conditional branching statements


 if statement
 if-else statement
 if-else-if statement
 switch statement
if statement

 Simplest form of decision control statement


 Syntax:

if(test expression)
{
statement 1;
………………
statement n;
}
statement-x;
#include<stdio.h>

int main()

int x=0;

if(x>0)

x++;

printf(“\n x=%d”,x);

}
If-else statement
 Syntax:

If(test expression)
{
statement block1;
}
else
{
statement block 2;
}
Statement x;
 Example: to find largest of two numbers

#include<stdio.h>
main()
{
int a,b,large;
printf(“\n Enter the values of a and b:”);
scanf(“%d %d”,&a,&b);
if(a>b)
large=a;
else
large=b;
printf(“\n Large=%d”, large);
}
if-else-if statement
 also known as nested if construct
 syntax:
if(test expression 1)
{
statement block 1;
}
else if(test expression 2)
{
statement block 2;
}

else
{
statement block x;
}
Statement y;
Example: to test whether a number entered is positive, negative or
equal to zero

#include<stdio.h>
main()
{
int num;
printf(“\nEnter any number:”);
scanf(“%d”,&num);
if(num==0)
printf(“the value is equal to zero”);
else if(num>0)
printf(“\n the number is positive”);
else
printf(“\n the number is negative”);
}
Dangling else problem
 Created when there is no matching else for every if statement
 C always pair an else statement to the most recent unpaired if
statement in the current block
 Ex:

if(a>b)

if(a>c)

printf(“a is greater than b and c”);

else

printf(“a is not greater than b and c”);


 Ensure that every if statement is paired with an appropriate else
statement
Ex:

if(condition) if(condition)

if(condition-1) {

if(condition-2) if(condition-1)

else if(condition-2)

Statement; }

else

Statement;
Rules for using if, if-else and if-else-f statement

1. The expression must be enclosed in parentheses

2. No semicolon is placed after the if/if-else/if-else-if.


Semicolon is placed only at the end of statements in the
statement block

3. A statement block begins and ends with curly brace.


switch case
 Multi-way decision statement
 Syntax:
switch(variable)
{
case value1:
statement block1;
break;
case value2:
statement block2;
break;
……………..
case valuen:
statement blockn;
break;
default:
statement block;
break;
}
Example:
Char grade=‘C’;
Switch(grade)
{
case ‘A’:
printf(“\nExcellent”);
break;
case ‘B’:
printf(“\nGOOD”);
break;
case ‘C’:
printf(“\nFair”);
break;
case ‘F’:
printf(“\nFail”);
break;
default:
printf(“\nInvalid Grade”);
break;
}
Rules
1. The control expression that follows the keyword switch must
be of integral type(i.e., either be an integer or any value that
can be converted to an integer)
2. Each case label should be followed with a constant or a
constant expression.
3. Every case label must evaluate to unique constant expression
value.
4. Case labels must end with colon
5. Two case labels may have the same set of actions associated
with it
6. The default label is optional and is executed only when the
value of the expression doesn’t match with any case label
7. The default can be place anywhere in the switch statement
8. There can be only one default label in a switch statement
9. C permits nested switch statements
include <stdio.h>
void main ()
{
int a = 100; int b = 200;
switch(a)
{
case 100: printf("This is part of outer switch\n", a );
switch(b)
{
case 200: printf("This is part of inner switch\n", a );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
}
Comparison between the switch and if-else construct

Generalized switch statement Generalized if-else statement

switch(x) If(exp1)
{ {
case 1: // do this // do this
case 2: // do this }
case 3: // do this else if(exp2)
…….. {
default: // do this
// do this } else if(exp3)
} {
// do this
}
Advantages of using a switch case statement
 Easy to debug
 Easy to read and understand
 Ease of maintenance as compared with its equivalent if-else
statements
 Like if-else statements, switch statements can also be nested
 Executes faster than its equivalent if-else construct

You might also like