CTP Module2
CTP Module2
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.
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:
{
printf(“Welcome to C Programming for Problem solving”);
}
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.
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
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
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.
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.
(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 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
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
= 36 //Final Result
→ 5 <= 10 – 5 + 0 – 20 == 5 >= 1 != 20
→ 5 <= 5 + 0 – 20 == 5 >= 1 != 20
→ 5 <= 5 – 20 == 5 >= 1 != 20
→ 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*/
𝑒 √𝑥 +𝑒 √𝑦
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𝑎
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
#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);
}
(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
#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:
#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);
}
}
Flow chart:
(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
Syntax:
initialization;
while(test condition)
{
MODULE-2
PROGRAMMING CONSTRUCTS
set of statements to be executed
including increment/decrement opetator
}
Flow chart:
(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:
(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:
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
#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");
}
}
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);
}
#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");
}
}
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.
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;
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𝑎
#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);
}
}