0% found this document useful (0 votes)
3 views44 pages

CTP Module2

It's my notes

Uploaded by

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

CTP Module2

It's my notes

Uploaded by

4mt23mt053
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE-2

PROGRAMMING CONSTRUCTS
HISTORY OF C
C is a general purpose, procedural, structured computer programming language developed by
Dennis Ritchie in the year 1972 at AT&T Bell Labs.
C language was developed on UNIX and was invented to write UNIX system software.
C is a successor of B language.
There are different C standards: K&R C std, ANSI C, ISO C.

Characteristics of C:
• C is easy to learn.
• C is a general purpose language.
• C is a structured and procedural language.
• It is portable.
• It can extend itself

Examples of C:
• Operating system
• Language compilers
• Assemblers
• Text editors
• Databases

C Character Set:
A C character set defines the valid characters that can be used in a source program. The basic C
character set are:
1. Letters: Uppercase: A, B, C, ……, Z Lowercase: a, b, c ……, z
2. Digits: 0, 1, 2,….., 9
3. Special characters:! , . # $ ( ,), }, { etc.
4. White spaces: Blank space, Horizontal tab space, carriage return, new line character, form
feed character.
MODULE-2
PROGRAMMING CONSTRUCTS
Basic structure of C Program

Every c program is made up of one or more pre-processor commands, global declarations, and one
or more functions.
Documentation section :consists of a set of comment line giving the name of the program, the
author, and other details. Compiler ignores these comments when it translates the program into
executable code. C uses 2 different formats
1. Block comments /*this is multi line comments*/
2. Line comments //this is single line comments
The Link section: provides instruction to the compiler to link functions from system library. This
Section is also called as pre-processor Statements.

The definition section: defines all symbolic constants

Global Declaration section: there are some variables that are used in more than on function, such
a variable are called global variable and are declared in the global declaration section that is outside
of all functions. This section also defines user defined functions.
Every C program must have one main () function section. This section contains two parts
declaration part and executable part
MODULE-2
PROGRAMMING CONSTRUCTS
Declaration part declares all the variables used in the executable part
There is at least one statement in an executable part. These two part must appear at the beginning
of the brace and ends at the closing brace. All statement in the declaration and executable part ends
with semicolon (;).
The sub program section: contains all the user defined functions that are called in the main
function although they appear in any order.
Here is a small program that displays a sentence “Welcome to C Programming for Problem
solving” on the monitor screen:

/* C program to display a welcome message */


#include<stdio.h>
void main( )

{
printf(“Welcome to C Programming for Problem solving”);
}

This program doesn’t have all the parts of typical C program.


The first line begins with /* and ending with */ is the comment line which is used to enhance
program readability and understanding.
The second line it has pre-processor directive #include which includes a header file stdio.h, the
standard input /output header file. The definitions of printf and scanf functions are defined in this
header file. Hence this line is always necessary.
The third line is main(), this is the special function used by C system to tell where the program
starts. Every program have exactly one main function. The empty pair of parenthesis following
main indicates that main has no arguments. Void indicates that main function does not return any
value to operating system. By default main returns integer value to operating system.
The opening brace “}” in the 4th line marks the beginning of the function main and closing brace
“}” at the last line indicates the end of the function.
All the statements between these braces form the function body. The function body contains set of
instruction to perform the given task.
In this program the function body contains only one executable statement printf. The printf is a
predefined function for printing output. It prints everything within the double quote. In this it will
print Welcome to C Programming for Problem solving on the monitor

C Tokens: In C program the smallest logically meaning full individual units are known as c tokens.
These are also called as the basic building blocks of C program which cannot be further broken
into subparts. C has 6 Different types of tokens. C programs are written using these tokens and
syntax of the language.
MODULE-2
PROGRAMMING CONSTRUCTS

i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
vi. Special symbols

1. Keywords: These are predefined words in C compiler which are ment for specific purpose.
These words are also called as reserved words. These words cannot be used as variable names.
These words are usually case sensitive and are usually written in lower case letters only. There are
32 keywords in C.
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

2. Identifiers: These are the names given to various elements of the C program like variables,
functions, arrays, etc. These are user defined names and consist of sequence letters, digits or
underscore.
Rules to define an Identifiers
1. The first character of the identifier must always be a letter or an underscore followed by any
number of letters digits or underscore.
2. Keywords cannot be used as identifiers or variables.
3. An Identifier or a variable should not contain two consecutive underscores
4. Whitespaces and special symbols cannot be used to name the identifiers.
5. Identifiers are case sensitive (A same variable name declared in uppercase letters and lower case
letters are two different variables in C program).
Examples
food_court valid identifier
$num Invalid identifier ($ is a special symbol)
_mite2021 valid identifier
mite mangalore Invalid identifier (white spaces are not allowed)
continue Invalid identifier (continue is a keyword)
MODULE-2
PROGRAMMING CONSTRUCTS
3. Constants: These are the fixed values assigned to the variables which cannot be cannot be
changed or modified in the program. Constants are broadly classified as

Numeric Constants:
Integer Constant: These contain digits or whole numbers without decimal point which can be
either positive or negative.
(i) Decimal: It is an integer constant consisting of numbers from 0-9. It can be preceded by + or –
(ii) Octal: It is an integer constant consisting of numbers from 0-7. It is preceded by o
(iii) Hexadecimal: It is an integer constant consisting of numbers from 0-9, A-F (A=10, B=11, C=12,
D=13, E=14, F=15). It is preceded by 0x

Real Constant: These contain an decimal point or an exponent or both. It can be either positive
or negative or both.
Example: 21.5, 3.142, 6.6260X10-34 , 2.15X102 → 2.15e2

Character Constants:
Single Character Constant: can be single character enclosed within single quotes or a ‘\’
(backslash) followed by any character. ‘\’ is called escape character as it alters the meaning of
character following it. Following are the complete list of escape sequence.

‘\a’ alert (bell)character ‘\ \’ backslash character


‘\b’ backspace ‘\?’ Question mark
‘\f’ formfeed ‘\’ ’ Single quote
MODULE-2
PROGRAMMING CONSTRUCTS
‘\n’ newline character ‘\”’ double quotes
‘\r’ carriage return ‘\ooo’ octal number
‘\t’ horizontal tab ‘\xxh’ hexadecimal number
‘\v’ vertical tab ‘\0’ Null character

String Constant: String constants also termed as string literal are sequences of characters enclosed
in double quotes. The character may be letters, numbers, special characters and blank space. a
String literal always ends with a Null character (‘\0’)
Example:
M I T E ‘\0’

5. Operators: An operator is a symbol that tells the compiler to perform specific mathematical
and logical functions. The different operators supported in ‘C’ are:
(i) Arithmetic Operators
(ii) Relational Operators
(iii) Logical Operators
(iv) Assignment Operators
(v) Bitwise Operators
(vi) Unary Operators→ Increment and Decrement
(vii) Ternary/ Conditional Operator
(viii) Special Operators

(i) Arithmetic Operators: These operators are used to perform basic arithmetic operations
Operator Name Result Syntax Example (b=5, c=2)
+ Addition Sum a=b+c a=7
- Subtraction Difference a=b-c a=3
* Multiplication Product a=b*c a = 10
/ Division Quotient a=b/c a=2
% Modulus Remainder a=b%c a=1

(ii) Relational Operators: This operator compares two operands inorder to find out the relation
between them. The output will be either 0 (False) or 1 (True).
MODULE-2
PROGRAMMING CONSTRUCTS
Operator Name Syntax Example (b=5, c=2)
< Lesser than a=b<c a = 0 (False)
> Greater than a=b>c a = 1 (True)
<= Lesser than or Equal to a = b <= c a = 0 (False)
>= Greater than or Equal to a = b >= c a = 1 (True)
== Equal to a=b==c a = 0 (False)
!= Not equal to a = b!= c a = 1 (True)
(iii) Logical Operators: These are used to test more than one condition and make decision. The
different logical operators are:
❖ Logical NOT
❖ Logical AND
❖ Logical OR

❖ Logical NOT (!) The output is true when input is false and vice versa. It accepts only one
input.
Input Output
X !X
0 1
1 0

❖ Logical AND (&&) The output is true only if both inputs are true. It accepts two or
more inputs.
Input Output
X Y X && Y
0 0 0
0 1 0
1 0 0
1 1 1

❖ Logical OR (||) The output is true only if any of its input is true. It accepts two or more
inputs.
Input Output
X Y X || Y
0 0 0
0 1 1
1 0 1
1 1 1
MODULE-2
PROGRAMMING CONSTRUCTS
(iv) Assignment Operators: The assignment operator is used to assign the values to the variables
on the left hand side. The symbol “=” is used as an assignment operator.
Example: x = 10, c = a+b
Shorthand Assignment: An expression can be written in a compact manner i.e. if the operand on
the left hand side of the assignment operator is same as the first operand of the right hand side
expression it can be written using the shorthand assignment operator
Example: x = x+2 → x+=2
Multiple Assignment: If more than one variable holds the same value we can use multiple
assignment to avoid rewriting of the same values repeatedly.
Example: a=10,b=10,c=10 → a=b=c=10

(v) Bitwise Operators:


These works on bits and performs bit by bit operations. The different types of bitwise operators
are:
Bitwise NOT (~) Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^) → Output is True when odd number of 1’s are present.
Bitwise left shift (<<) Bitwise right shift (>>)
Bitwise NOT (~)
X ~X
0 1
1 0

Bitwise AND (&), Bitwise OR (|),Bitwise XOR (^)


X Y X&Y X|Y X^Y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Bitwise Left Shift (<<): Shift specified number of bits to left side
X 0 1 0 0 0 1 1 0
X<<2 0 0 0 1 1 0 0 0

Bitwise Right Shift (>>): Shift specified number of bits to right side.
X 0 1 0 0 0 1 1 0
X>>2 0 0 0 1 0 0 0 1
MODULE-2
PROGRAMMING CONSTRUCTS

(vi) Unary Operators:


Unary Plus Operator Unary Minus Operator
Increment (++) Decrement (--)
Unary Plus and Unary Minus Operator : These operators are used to determine the sign of the
operand the only unary operators are + and –
Increment (++): An increment operator adds one to the operand. The types of increment are Pre
increment and Post increment
Pre increment: The increment operator followed by an operand is called Pre increment operator
here the value on the right hand side is first incremented by one and then the value is assigned to
the variable at the left.
Example: If a=8, b= ++a what will be the value of a and b?
Since ++a is a pre increment operator first the value of a is incremented by 1
hence the new value of a=9 now this new value is assigned to the variable b i.e.
b=9 Therefore a=9 and b=9
Post increment: An Operand followed by an increment operator is called post increment operator
here the value is first assigned to the variable at the left and then the value of the variable in the
right will be incremented by 1

Example: If q=6, p= q++ what will be the value of p and q?


Since q++ is a post increment operator first the value of q is assigned to the
variable p i.e. p=6 now the value of q is incremented by 1 hence the new value
of q=7, this new value of q will be used for the upcoming iteration Therefore p=6
and q=7
Decrement (--): A decrement operator subtracts 1 from the operand. The types of decrement are Pre
decrement and Post decrement
Pre decrement: The decrement operator followed by an operand is called Pre decrement operator
here the value on the right hand side is first decremented by one and then the value is assigned to
the variable at the left.
Example: If y=4, x= --y what will be the value of x and y?
Since --y is a pre decrement operator first the value of y is decremented by 1
hence the new value of y=3 now this new value is assigned to the variable x i.e.
x=3 Therefore x=3 and y=3
MODULE-2
PROGRAMMING CONSTRUCTS
Post decrement: An Operand followed by an decrement operator is called post decrement operator
here the value is first assigned to the variable at the left and then the value of the variable in the
right will be decremented by 1

Example: If n=5, m= n-- what will be the value of m and n?


Since n-- is a post decrement operator first the value of n is assigned to the
variable m i.e. m=5 now the value of n is decremented by 1 hence the new value
of n=4, this new value of n will be used for the upcoming iteration Therefore m=5
and n=4

(vii) Ternary/ Conditional Operator: It takes three arguments


Expression1 ? Expression2 : Expression3
Where,
Expression1→ Condition
Expression2→ Statement followed if condition is true
Expression3→ Statement followed if condition is false
Example:
large = (4 > 2) ? 4: 2 →large = 4

(viii) Special Operators:


Comma Operator: It can be used as operator in expression and as separator in declaring
variables.

sizeof() operator: It is used to determine the size of variable or value in bytes.

Address Operator: It is used to find the address of the operators


Data Types: These are the keywords that are used to assign the type of a variable based on the
type of data stored in it. Data types are used to
❖ Identify the type of variable when it is used
❖ Identify the type of return value of the function
❖ Identify the type of parameter expected by the function
The data types are broadly classified into 3 types
I. Primary or built-in or primitive data type
II. Derived data type
III. User defined data type

I. Primary or built-in or primitive data type: These are the data types which are already
predefined by the compiler.
(i) Integer data type: It is used to store whole numbers and its range depends on the word length
defined for a computer. It usually occupies 2 bytes of memory, for signed integers the value ranges
MODULE-2
PROGRAMMING CONSTRUCTS
from -2n-1 to +2n-1-1 and for unsigned integers the value ranges from 0 to 2n-1. Keyword int is used
to declare variables of integer data type.

(ii) Floating point data type: It is used to store decimal numbers that have single precision
floating point value. It provides 6 digits after the decimal point and occupies 4 bytes of memory.
Keyword float is used to declare variables of floating point data type.

(iii) Double data type: These are used to store real numbers that have double precision floating
point value. It provides 16 digits after the decimal point. this data type is used when performing
complex calculations to get accurate results. It occupies 8 bytes of memory. Keyword double is
used to store the variables of double data type.

(iv) Char data type: This data type basically stores character type of data. the character data can
be an Alphabet [a to z or A to Z] , digits [0 to 9] and all special characters or
symbols[@,$,&,#,...]which is enclosed with in single quotes. It occupies one byte of memory.
Keyword char is used to declare variables of character data type.

(v) Void data type: It does not store any value hence we cannot store any operation on the variable
declared as void. It has no range. Keyword void is used to specify non return data type.

Type Data type Size (Bytes) Range


Signed: -128 to +127
Character char 1
Unsigned: 0 to 255
Signed -32768 to +32767
Integer int 2
Unsigned 0 to 65535
Floating point or real float 4 3.4e-38 to 3.4e+38
Double precision
double 8 1.7e-308 to 1.7e+308
floating point
Non specific void 0 -

II. Derived data type: These are the data types which are derived from the primitive data types.
There are mainly three derived data types
(i) Arrays: Sequence of data items having homogeneous values.

(ii) References: Function pointers allow referencing with a particular signature.

(iii) Pointers: These are used to access the memory and deal with their addresses

III. User defined data type: The type definition feature of C allows the user to define an identifier
which acts as data type using an existing basic data type. Such identifier is called as user defined
data types.
MODULE-2
PROGRAMMING CONSTRUCTS
(i) Structure: It is a package of variable of different types under a single name. struct keyword is
used to define a structure.

(ii) UNION: This allows storing various data types in the same memory locations.

(iii) ENUM: Enumeration is a special data type that consists of integral constants and each of them
is assigned with a specific name. enum keyword is used to create the enumerated data type.

Data type Qualifiers and Data type Modifiers


Data type Qualifiers: American National Standard Institute (ANSI) introduced two types of data
type qualifiers
const: The value of the variable is constant during execution of the program. Such variables are
declared using keyword "const".
Example: const float pi = 3.142
volatile: The value of a variable might change at any time by an outside factor such variables are
declared using keyword "volatile".
Example: volatile float a; volatile int b = 10;

Data type Modifiers: Built in data types except void data type can easily be modified by using
data type modifier. There are mainly 4 data type modifiers:
(i) Signed (ii) Unsigned (iii) Long (iv) Short

(i) Signed: it indicates that the variable is capable of storing the negative numbers. The values will
be in this range. -2n-1 to +2n-1-1. Where, n is the size of the particular data type in bits. In declaration
we have to use signed keyword. Example: signed int a;

(ii) Unsigned: it indicates that the variable is capable of storing only positive numbers The values
will be in this range. 0 to 2n-1. Where, n is the size of the particular data type in bits. In declaration
we have to use unsigned keyword. Example: unsigned int a;

(iii) Long: It is used to increase the storage capacity of the variable. long keyword can be used as
shown long int a; //long int occupies 4 bytes of memory.
(iv) Short: It is used to decrease the storage capacity of the variable (capacity is reduced to half).
short keyword can be used as shown short int a; //short int occupies 1 bytes of memory.

Format Specifiers: These are used to tell the compiler about the type of data being used
Data Type Format Specifier Meaning
%d Decimal integer
Integer (int) %o Octal integer
%x Hexadecimal integer
MODULE-2
PROGRAMMING CONSTRUCTS
%i Decimal, hex or octal int
%u Unsigned integer
%h Short integer
%e
Floating Point
%f floating point
(float)
%g
%c Single character
Character (char)
%s String data
Double (double) %lf Floating point number or double
Long Integer %ld long integer value

Type Conversion: It is a process of converting an expression from one data type to another data
type
There are two types:
Implicit Type conversion
Explicit Type Conversion

Implicit Type Conversion: This type of conversion is done by the compiler, so it is called as
implicit type conversion. Without user intervention this process is carried out. Whenever we are
converting narrow operand (lower data type variable) into wide operand (higher data type variable)
then compiler will do it implicitly.
Example:
#include<stdio.h>
void main( )
{
char b= ‘A’;
int a;
a=b;
printf(“%d”,a);
}

OUTPUT: 65

Explicit Type Conversion: This type of conversion is done by the user so it is called explicit type
conversion. Whenever we are converting wider operand (higher data type variable) into a narrower
operand (lower data type variable) then its called explicit conversion.
Example:
#include<stdio.h>
void main()
{
MODULE-2
PROGRAMMING CONSTRUCTS
int a=4;
float b;
b=1/(float)a;
printf(“%f”,b);
}

OUTPUT: 0.250000
Expressions: It is combination of operands (variables, constants) and operators.
Precedence: The order in which operators are evaluated is based on the priority value.
Associativity: It is the parsing direction used to evaluate an expression. It can be left to right or
right to left.
Evaluation of expressions: Expressions are evaluated using an assignment statement.
Example: variable = expression
sum = a + b

Following table provides the Precedence and Associativity of operators:


Operator Description Associativity Precedence(Rank)
() Function call
Left to right 1
[] Array element reference
+ Unary plus
- Unary minus
++ Increment
-- Decrement
! Logical negation
Right to left 2
~ Ones complement
* Pointer to reference
& Address
Sizeof Size of an object
(type) Type cast (conversion)
* Multiplication
/ Division Left to right 3
% Modulus
+ Addition
Left to right 4
- Subtraction
<< Left shift
Left to right 5
>> Right Shift
< Less than
<= Less than or equal to
Left to right 6
> Greater than
>= Greater than or equal to
MODULE-2
PROGRAMMING CONSTRUCTS
Operator Description Associativity Precedence(Rank)
== Equality
Left to right 7
|= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional expression Right to left 13
=
*= /= %=
+= -= &= Assignment operators Right to left 14
^= |=
<<= >>=
, Comma operator Left to right 15

Examples:
1. If a=8, b=15 and c=4 calculate the expression

2*((a%5)*(4+(b–3)/(c+2)))

= 2 * ( ( 8 % 5 ) * ( 4 + ( 15 – 3 ) / ( 4 + 2 ) ) ) //Substitution of values

= 2 * (3 * ( 4 + ( 15 – 3 ) / ( 4 + 2 ) ) ) //Brackets having the highest priority

= 2 * ( 3 * ( 4 +12 /( 4 + 2 ) ) ) //inner most brackets are evaluated first

= 2 * ( 3 * ( 4 +12 / 6 ) ) //Brackets having the highest priority

= 2 * ( 3 * ( 4 + 2 ) ) //within the brackets ‘/’ has the highest priority

= 2 * ( 3 * 6 ) // inner most brackets are evaluated

= 2 * 18 // Brackets having the highest priority

= 36 //Final Result

2. Evaluate the expression

a += b *= c -=5 , Given a=3, b=5, c=8.

a += b *= c -=5 //Apply Associativity i.e. evaluate from right to left

a += b *= ( c = c – 5 ) //Deduce the short hand Expression


MODULE-2
PROGRAMMING CONSTRUCTS
a += b *= ( c = 8 – 5 ) //Substitute the given value of c

a += b *= ( c = 3 ) //Reduce the equation to simplified form

a += b *= 3 //Apply Associativity i.e. evaluate from right to left

a += ( b = b * 3 ) //Deduce the short hand Expression

a += ( b = 5 * 3 ) //Substitute the given value of b

a += ( b = 15 ) //Reduce the equation to simplified form

a + = 15 //Apply Associativity i.e. evaluate from right to left

a = a + 15 // Deduce the short hand Expression

a = 3 + 15 //Substitute the given value of a

a =18 // Final Result

3. Evaluate the expression

100 / 20 <= 10 – 5 + 100 % 10 – 20 == 5 >= 1 != 20

→ 100 / 20 <= 10 – 5 + 100 % 10 – 20 == 5 >= 1 != 20

→ 5 <= 10 – 5 + 100 % 10 – 20 == 5 >= 1 != 20

→ 5 <= 10 – 5 + 0 – 20 == 5 >= 1 != 20

→ 5 <= 5 + 0 – 20 == 5 >= 1 != 20

→ 5 <= 5 – 20 == 5 >= 1 != 20

→ 5 <= -15 == 5 >= 1 != 20 // Simplify the relational operators

→ 0 == 5 >= 1 != 20 //True is given by 1 and false is given by 0

→ 0 == 1 != 20

→ 0 != 20

→1
MODULE-2
PROGRAMMING CONSTRUCTS
Writing C expressions for Mathematical Expressions
Basic Conversions
𝑥
→ x/y
𝑦

√𝑣 → sqrt(v)
| h | → abs(h)
gt → pow(g,t)
ex → exp(x)
sin x → sin (x)
sin 45o → sin ( ( 45 * 3.142 ) / 180) /*converting degrees to radians*/

Write the C equivalent expressions for the following mathematical Expressions


5𝑥+3𝑦
1. A= → A= ((5*x)+(3*y))/(a+b)
𝑎+𝑏

2. 𝐶 = 𝑒 |𝑥+𝑦−10| → C = exp ( abs ( x + y – 10 ) )

𝑒 √𝑥 +𝑒 √𝑦
3. 𝑃 = → P = ( exp ( sqrt ( x ) ) + exp ( sqrt ( y ) ) ) / ( x * sin ( sqrt ( y ) )
𝑥𝑠𝑖𝑛√𝑦

−𝑏+√𝑏 2 −4𝑎𝑐
4. 𝑋 = → X= ( ( -b ) + sqrt ( b * b – 4 * a * c ) ) / ( 2 * a )
2𝑎

Managing Input and Output Statements in C


In programming input mean reading data from the input device or a file and Output means
displaying the results on the screen. C provides a number of input and output functions. These
functions are predefined in the respective header files. The input and output functions are used in
the program whose functionality are predefined in the header file “#include<stdio.h>”

Input and output functions are broadly classified into as


MODULE-2
PROGRAMMING CONSTRUCTS

Formatted Input and Output statements


scanf( ): scanf() function reads all type of data value from input device or from a file. the address
operator “&” is used to indicate the memory location of the variable. This memory location is
used to store the data which is read through the keyboard.
Syntax:
scanf(“format specifier”,addresslist);
where:
format specifier indicates the type of data to be stored in the variable.
address list indicates the location of the variable where the value of the data is to be stored.
the address list is usually prefixed with an ”&”(ampersand) operator for each variable.

Example: if we want to store the values 50 and 31from the keyboard in variables num1 and num2
then the input function is read as
scanf(“%d%d”,&num1,&num2);
the value 50 will be assigned to num1 and value 31 will be assigned to num2
MODULE-2
PROGRAMMING CONSTRUCTS
printf( ): In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen. The features of printf() can be
effectively exploited to control the alignment and spacing of printouts on terminals.

Syntax:

printf(“Text Message”);
OR
printf(“format specifier”,variablelist);
where:
format specifier indicates the type of data to be displayed
variable list indicates the value present in the variable.
the number of format specifier must match the number of variables in the variablelist.

Example: if we want to display the values stored in variables num1 and num2 then the printf
statement can be written as
printf(“The Value of num1 = %d and The value of num2 = %d\n”,num1,num2);
This statement will display the values stored in the respective variables. The output will be of the
form:
The Value of num1 = 50 and The value of num2 = 31

Example: /* C program to demonstrate Formatted Input and Output Statements */

#include<stdio.h>
void main()
{
int a,b,sum;
printf(“Enter two numbers\n”);
scanf(“%d%d”,&a,&b);
sum=a+b;
printf(“ Addition of two Numbers=%d\n”,sum);
}
MODULE-2
PROGRAMMING CONSTRUCTS
Unformatted Input and Output statements

getch(): is used to read a character from the keyboard, the character entered is not displayed or
echoed on the screen the functions don’t need a return key pressed to terminate the reading of a
character. A character entered will itself terminates reading

Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getch();
printf(“The entered character is %c\n”,ch);
}

getche(): is used to read a character from the keyboard, the character entered is echoed or displayed
on the screen. the functions don’t need a return key pressed to terminate the reading of a character.
A character entered will itself terminates reading.
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getche();
printf(“The entered character is %c\n”,ch);
}

getchar(): will reads a character from the keyboard and copy it into memory area which is
identified by the variable ch. No arguments are required for this macro. Once the character is
entered from the keyboard, the user has to press Enter key.
Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getchar();
printf(“The entered character is %c\n”,ch);
}
MODULE-2
PROGRAMMING CONSTRUCTS
putch() and putchar(): This function outputs a character stored in the memory, on the standard
output device.. The variable should be passed as parameter to the functions

Example:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getchar();
printf(“The entered character is \n”);
putchar(ch);
}

CONDITIONAL BRANCHING AND LOOPING


C program is a set of statements which are normally executed sequentially in the order which
they appear. If there occours a situation where we have to change the order of execution of the
statements we make use of conditional statements.
C provides 5 types of conditional branching statements.
(i) Simple if statement
(ii) if – else statement
(iii) Nested if statement
(iv) Cascaded if statement or else-if ladder
(v) Switch Statement

(i) simple if: This is a one way selection statement which helps the programmer to execute or skip
certain block of statements based on the particular condition.

Syntax:

if(conditional_expression)
{
True block statements;
}

Flowchart:
MODULE-2
PROGRAMMING CONSTRUCTS

Example: /* C programto check the voting eligibility of the person*/

#include<stdio.h>
void main()
{
int age;
printf(“ Enter the age of the person\n”);
scanf(“%d”,&age);
if(age>=18)
{
printf(“The person is eligible to vote\n”);
}
if(age<18)
{
printf(“The person is not eligible to vote\n”);
}
}

(ii) if-else statement: This is a two way selection statement which executes true block or false
block of statements based on the given condition. The keyword “else” is used to shift the control
when the condition is evaluated to false.
Syntax:
if(conditional_expression)
{
True block statements;
}
else
{
False block statements;
}
MODULE-2
PROGRAMMING CONSTRUCTS
Flow chart:

Example: /* C program to check the entered num is even or odd*/

#include<stdio.h>
void main()
{
int num;
printf(“Enter a number\n”);
scanf(“%d”,&num);
if(num%2==0)
{
printf(“%d is a even number\n”,num);
}
else
{
printf(“%d is a odd number\n”,num);
}
}

(iii) Nested if Statement: An if statement within another if statement is called as a nested if


statement. This helps the programmer to select one among many alternatives based on a given
condition.
Syntax:
if(conditional_expression1)
{
if(conditional_expression2)
{
statement1;
}
else
{
statement2;
MODULE-2
PROGRAMMING CONSTRUCTS
}
}
else
{
statement 3;
}
statement X;

Flow chart:

Example: /* C program to find smallest of three numbers*/


#include<stdio.h>
void main()
{
int a,b,c,small;
printf(“Enter three numbers\n”);
scanf(“%d%d%d”,&a,&b,&c);
if(a<b)
{
if(a<c)
small=a;
else
small=c;
}
else
{
if(b<c)
small=b;
else
small=c;
}
printf(“Smallest among three numbers=%d”,small);
}
MODULE-2
PROGRAMMING CONSTRUCTS

(iv) Cascaded if-else or else if ladder: This is another way of putting all if’s togather when
multipath decision are involved The multipath decision is a chain of if statement in which the
statement associated with each else is a if statement. Here the conditions are evaluated from top to
bottom. As soon as the true condition is found the statement associated with it is executed and the
control is transferred to statement X, skipping rest of the ladder.

Syntax:

if(condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
----------------------
----------------------
----------------------
else if(condition n)
statement n;
else
default statement;
statement X;

Flowchart:
MODULE-2
PROGRAMMING CONSTRUCTS

Example: /* C program to display the grade of the student based on the average marks
obtained */
#include<stdio.h>
void main()
{
float avg;
printf(“Enter the Average marks\n”);
scanf(“%f”,&avg);
if(avg>=80)
printf(“Distinction\n”);
else if(avg>=60)
printf(“First Division\n”);
else if(avg>=50)
printf(“Second Division\n”);
else if(avg>=40)
printf(“Third Division\n”);
else
printf(“Fail\n”);
}

(v)Switch Statement: A switch statement tests the value of a variable and compares it with
multiple cases. Once the case match is found, a block of statements associated with that particular
case is executed. Each case in a block of a switch has a different name/number which is referred
to as an identifier. The value provided by the user is compared with all the cases inside the switch
MODULE-2
PROGRAMMING CONSTRUCTS
block until the match is found. If a case match is not found, then the default statement is executed,
and the control goes out of the switch block. The break statement is used at the end of each case
to come out of the switch block.

Syntax:
switch( expression )
{
case value-1: Statement-1;
break;
case value-2: Statement-2;
break;
case value-3: Statement-3;
break;
----------------------
----------------------
----------------------
case value-n: Statement-n;
break;
default: default Statement
break;
}
Statement-x;

Flowchart:
MODULE-2
PROGRAMMING CONSTRUCTS

Example: /* C program to find Area of various geometric figures*/


#include<stdio.h>
void main()
{
float a,b,area;
int choice;
printf(“\n MENU\n”)
printf(“1. Square\t 2. Circle\t 3. Rectangle\t 4. Triangle\n”);
printf(“Enter your Choice as 1 OR 2 OR 3 OR 4\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nSQUARE\n”);
printf(“Enter the Side\n”);
scanf(“%d”,&a);
area=a*a;
break;
MODULE-2
PROGRAMMING CONSTRUCTS
case 2: printf(“\nCIRCLE\n”);
printf(“Enter the Radius\n”);
scanf(“%d”,&a);
area=3.142*a*a;
break;
case 3: printf(“\nRECTANGLE\n”);
printf(“Enter the length and breadth\n”);
scanf(“%d%d”,&a,&b);
area=a*b;
break;
case 4: printf(“\nTRIANGLE\n”);
printf(“Enter the base and height\n”);
scanf(“%d%d”,&a,&b);
area=0.5*a*b;
break;
default: printf(“you have entered a wrong choice\n”);
exit(0);
}
Printf(“Area=%f\n”,area);
}

Introduction to Conditional looping statements.


A set of statements have to be repeatedly executed for a specified number of times until a condition
is satisfied. The statements that help us to execute the set of statements repeatedly are called as
looping constructs or loop control statements.
The various looping constructs in C are:
(i) while Loop (ii) do-while Loop (iii) for Loop
(i)while Loop: It is an entry-controlled loop. In while loop, a condition is evaluated before
processing a body of the loop. If a condition is true then and only then the body of a loop is
executed. After the body of a loop is executed then control again goes back at the beginning, and
the condition is checked if it is true, the same process is executed until the condition becomes false.
Once the condition becomes false, the control goes out of the loop. After exiting the loop, the
control goes to the statements which are immediately after the loop.

Syntax:
initialization;
while(test condition)
{
MODULE-2
PROGRAMMING CONSTRUCTS
set of statements to be executed
including increment/decrement opetator
}

Flow chart:

Example: /* C program to print Numbers from 1 to 5 using while loop*/


#include<stdio.h>
void main()
{
int i;
i=1;
while(i<=5)
{
printf(“%d\t “,i);
i++;
}
}

(ii) do-while loop : A do-while loop is similar to the while loop except that the condition is always
executed after the body of a loop. It is also called an exit-controlled loop. The body is executed if
and only if the condition is true. In some cases, we have to execute a body of the loop at least once
even if the condition is false. This type of operation can be achieved by using a do-while loop. In
the do-while loop, the body of a loop is always executed at least once. After the body is executed,
then it checks the condition. If the condition is true, then it will again execute the body of a loop
otherwise control is transferred out of the loop. Similar to the while loop, once the control goes
out of the loop the statements which are immediately after the loop is executed.
MODULE-2
PROGRAMMING CONSTRUCTS
Syntax:
initialization;
do
{
set of statements to be executed
including increment/decrement opetator
}while(test condition);

Flowchart:

Example: /* C program to print Numbers from 1 to 5 using do- while loop*/


#include<stdio.h>
void main()
{
int i;
i=1;
do
{
printf(“%d\t “,i);
i++;
} while(i<=5);
}
MODULE-2
PROGRAMMING CONSTRUCTS
Difference between while loop and do-while loop
While loop Do while loop
Syntax Syntax:
initialization; initialization;
while(test condition) do
{ {
set of statements to be executed set of statements to be executed
including increment/decrement including increment/decrement opetator
opetator }while(test condition);
}

Condition is checked first. Condition is checked later.


Since condition is checked first, statements Since condition is checked later, the body
may or may not get executed. statements will execute at least once.
The main feature of the while loop is,its an The main feature of the do while loops is it is an
entry controlled loop. exit controlled loop
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
i=1; i=1;
while(i<=5) do
{ {
printf(“%d\t “,i); printf(“%d\t “,i);
i++; i++;
} } while(i<=5);
} }

While loop Flowchart Do while loop Flowchart

(iii) for loop : A for loop is a more efficient loop structure in 'C' programming which is used when
the loop has to be traversed for a fixed number of times. The for loop basically works on three
major aspects (i) The initial value of the for loop is performed only once. (ii) The condition is a
MODULE-2
PROGRAMMING CONSTRUCTS
Boolean expression that tests and compares the counter to a fixed value after each iteration,
stopping the for loop when false is returned. (iii) The incrementation /decrementation increases (or
decreases) the counter by a set value.

Syntax:
for (initial value; condition; incrementation or decrementation )
{
statements;
}

Flowchart:

Example: /* C program to print Numbers from 1 to 5 using for loop*/


#include<stdio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
MODULE-2
PROGRAMMING CONSTRUCTS
printf("%d\t",i);
}
}

Nested for loop : Nested loop means a loop statement inside another loop statement. That is why
nested loops are also called as “loop inside loop“.In nested for loop one or more statements can be
included in the body of the loop. In nested for loop, The number of iterations will be equal to the
number of iterations in the outer loop multiplies by the number of iterations in the inner loop.
When the control moves from outer loop to inner loop the control remains in the inner loop until
the inner loop condition fails, once the condition fails the control continues with the outer loop
condition Again when the control comes to inner loop the inner loop is reset to the initial value.
The Nested for loop stops execution when the outer for loop condition fails.

Syntax:
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
statement of inner loop
}
statement of outer loop
}
Flowchart:
MODULE-2
PROGRAMMING CONSTRUCTS

Example: C program to print the following pattern


*
* *
* * *
* * * *

#include <stdio.h>
void main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf(“ * ”);
}
printf("\n");
}
}
MODULE-2
PROGRAMMING CONSTRUCTS
Example: C program to print the following pattern
1
2 3
4 5 6
7 8 9 10

#include <stdio.h>
void main()
{
int i, j, n=1;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d\t",n);
n++;
}
printf("\n");
}
}

Programming examples on Looping constructs:

1. Write a C program to find factorial of a given number using while loop.


#include<stdio.h>
void main()
{
int n,i,fact=1;
printf(“Enter a Number\n”);
scanf(“%d”,&n);
i=1;
while(i<=n)
{
fact=fact*i;
i=i+1;
}
printf(“Factorial of a given number = %d\n”,fact);
}

2. Write a C program to print even numbers in the range of 1 to10 using while loop.
MODULE-2
PROGRAMMING CONSTRUCTS
#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
if(i%2==0)
printf(“%d\t”,i);
i=i+1;
}
}

3. Write a C program to print sum of first n natural numbers using do-while loop
#include<stdio.h>
void main()
{
int n,i sum;
printf(“Enter the number of elements\n”);
scanf(“%d”,&n);
sum=0;
do
{
sum=sum+i;
i++;
}while(i<=n);
printf(“Sum of natural numbers=%d\n”,sum);
}

4. Write a C program to print multiplication table of a given number using do-while loop
#include<stdio.h>
void main()
{
int n,i,p;
printf(“Enter a number\n”);
scanf(“%d”,&n);
i=1;
do
{
p=n*i;
printf(“%d X %d = %d\n”,n,i,p);
i=i+1;
}while(i<=10);
}
MODULE-2
PROGRAMMING CONSTRUCTS
5. Write a C program to print sum of first n natural numbers using for loop
#include<stdio.h>
void main()
{
int n,i sum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum of natural numbers=%d\n”,sum);
}

6. Write a C program to print sum of all odd numbers and even numbers up to a given
range n using for loop
#include<stdio.h>
void main()
{
int n,i,osum=0,esum=0;
printf(“Enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
if(i%2==0)
esum=esum+i;
else
osum=osum+i;
}
printf(“The sum of even numbers=%d\n”,esum);
printf(“The sum of odd numbers=%d\n”,osum);
}

7. Write a C program to print fibonacci series up to n numbers using for loop


#include<stdio.h>
void main()
{
int n,i,fib1,fib2,fib3=0;
printf("Enter the number of series to to be genetared:");
scanf("%d",&n);
fib1=0;
fib2=1;
if(n==1)
MODULE-2
PROGRAMMING CONSTRUCTS
printf("%d\n",fib1);
else if(n==2)
printf("%d\n%d\n",fib1,fib2);
else
printf("%d\n%d\n",fib1,fib2);
for(i=3;i<=n;i++)
{
fib3=fib1+fib2;
printf("%d\n",fib3);
fib1=fib2;
fib2=fib3;
}
}

7. Write a C program to print the following pattern


1
1 2
1 2 3
1 2 3 4

#include <stdio.h>
void main()
{
int i,j;
for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf(“ %d ”,j);
}
printf("\n");
}
}

Unconditional Looping Statements


An unconditional statements are the statements which transfer the control or flow of execution
unconditionally to another block of statements. They are also called jump statements.
There are four types of unconditional control transfer statements.
(i) break (ii)continue (iii) goto (iv)return
MODULE-2
PROGRAMMING CONSTRUCTS
(i) break Statement: A break statement terminates the execution of the loop and the control is
transferred to the statement immediately following the loop. i.e., the break statement is used to
terminate loops or to exit from a switch.

Syntax :
Jump-statement;
break;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
i++;
if(i==3)
break;
printf(“%d\t”,i);
}
}
OUTPUT:
1 2
(ii) continue statement: The continue statement is used to bypass the remainder of the current
pass through a loop. The loop does not terminate when a continue statement is encountered.
Instead, the remaining loop statements are skipped and the computation proceeds directly to the
next pass through the loop. It is simply written as “continue”. The continue statement tells the
compiler “Skip the following Statements and continue with the next Iteration”.

Syntax :
Jump-statement;
Continue;
Example:
#include<stdio.h>
void main()
{
int i=0;
while(i<=5)
{
MODULE-2
PROGRAMMING CONSTRUCTS
i++;
if(i==3)
continue;
printf(“%d\t”,i);
}
}
OUTPUT:
1 2 4 5

(iii)goto statement : C supports the “goto” statement to branch unconditionally from one point to
another in the program. Although it may not be essential to use the “goto” statement in a highly
structured language like “C”, there may be occasions when the use of goto is necessary. The goto
requires a label in order to identify the place where the branch is to be made. A label is any valid
variable name and must be followed by a colon (: ). The label is placed immediately before the
statement where the control is to be transferred. The label can be anywhere in the program either
before or after the goto label statement.

Syntax : Forward jump Backward jump


goto label; goto label; label:
............. ............. statement;
............. ............. .............
............. ............. .............
label: label: .............
statement; statement; goto label;

If the label statement is below the goto statement then it is called forward jump. if the label
statement is above the goto statement then it is called backward jump

Example:
Program without using goto Program using goto
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
printf(“MITE \t”); printf(“MITE \t”);
printf(“is \t in\t”); goto label1;
printf(“Moodbidri\n”); printf(“is \t in\t”);
} label1: printf(“Moodbidri\n”);
OUTPUT }
MITE is in Moodbidri OUTPUT
MITE Moodbidri
MODULE-2
PROGRAMMING CONSTRUCTS

Write a C Program to check if the entered number is positive Negative or Zero using goto
statement.

#include<stdio.h>
#include<stdlib.h>
void main()
{
int num;
printf(“Enter the number\n”);
scanf(“%d”,&num);
if(num==0)
goto zero;
else if(num>0)
goto pos;
else
goto neg;
zero: printf(“The entered number is Zero\n”);
exit(0);
pos: printf(“The entered number is Positive\n”);
exit(0);
neg: printf(“The entered number is Negative\n”);
exit(0);
}

return statement: The return statement terminates the execution of a function and returns control
to the calling function. Execution resumes in the calling function at the point immediately
following the call. A return statement can also return a value to the calling function.

Syntax :
Jump-statement:
return expression;

Finding Roots of a Quadratic Equation:


A quadratic equation, or a quadratic in short, is an equation in the form of ax 2 + bx + c = 0,
where a is not equal to zero. The “roots” of the quadratic are the numbers that satisfy the
quadratic equation. There are always two roots for any quadratic equation, although sometimes
they may coincide.
MODULE-2
PROGRAMMING CONSTRUCTS
The possible roots of the quadratic equation are:

(i) Roots are Real and Equal

(ii) Roots are real and distinct

(iii) Roots are imaginary

How to decide on calculation of roots?

Given the equation ax2 + bx + c = 0, substitute the values of the coefficients a,b,c in the
discriminant b2-4ac

Outcome1: if the value of b 2-4ac is equal to zero then we say the “Roots are Real and Equal”
−𝑏
The formula to calculate the real and equal root is 𝑥 =
2𝑎

Outcome2: if the value of b 2-4ac is grater than zero i.e if the discriminant value is positive we
say the “Roots are real and distinct” the formula to calculate real and distinct roots are 𝑥 =
−𝑏±√𝑏2 −4𝑎𝑐
2𝑎

Outcome3: if the value of b 2-4ac is lesser than zero i.e if the discriminant value is negative
we say that the “ Roots are imaginary ” the formula to calculate imaginary roots are 𝑥 =
−𝑏±𝑖√𝑏2 −4𝑎𝑐
2𝑎

Develop a program to compute the roots of a quadratic equation by accepting the


coefficients. Print appropriate messages

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
float a,b,c,x1,x2,disc;
printf("Enter the values of a,b,c\n");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
MODULE-2
PROGRAMMING CONSTRUCTS
printf("Invalid Input\n");
exit(0);
}
disc=b*b-4*a*c;
if(disc>0)
{
printf("Roots are Real and Distinct\n");
x1=((-b)+sqrt(disc))/(2*a);
x2=((-b)-sqrt(disc))/(2*a);
printf("Root1= %f\n Root2= %f\n",x1,x2);
}
else if(disc==0)
{
printf("Roots are Real and Equal\n ");
x1=(-b)/(2*a);
printf("Root1=Root2=%f\n",x1);
}
else
{
printf("Roots are Imaginary\n");
x1=(-b)/(2*a);
x2=(sqrt(fabs(disc)))/(2*a);
printf("Root1= %f +i %f\n",x1,x2);
printf("Root2= %f -i %f\n",x1,x2);
}
}

You might also like