0% found this document useful (0 votes)
4 views

C - Programming Material - II

The document provides an overview of tokens and control statements in C programming, detailing the types of tokens, operators, and control structures such as conditional and unconditional statements. It includes examples of C syntax and programming concepts like variables, constants, and operators, along with frequently asked questions related to these topics. The content is structured as a syllabus for a module on programming for problem-solving using C, aimed at enhancing understanding of fundamental programming constructs.

Uploaded by

Lakshman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C - Programming Material - II

The document provides an overview of tokens and control statements in C programming, detailing the types of tokens, operators, and control structures such as conditional and unconditional statements. It includes examples of C syntax and programming concepts like variables, constants, and operators, along with frequently asked questions related to these topics. The content is structured as a syllabus for a module on programming for problem-solving using C, aimed at enhancing understanding of fundamental programming constructs.

Uploaded by

Lakshman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Programming for Problem Solving using C

TOKENS AND CONTROL STATEMENTS


Module II

Syllabus

Tokens: All tokens, operators and expressions, type conversions in C. Input and Output:

Introduction, non-formatted input and output, formatted input and output. Control

Statements: Introduction, conditional execution (if, if-else, nested if), and selection (switch),

unconditional types (break, continue, goto).

Tokens are the basic building blocks in programming, which are constructed together

to write programming. Identifiers and Keywords are the basics in a C program.

Control statements used to specify the flow of program control; ie, the order in

which the instructions in a program must be executed.

Frequently Asked Questions in Module –II


(FAQ)

1. What is an operator? Explain the arithmetic, relational, logical, and assignment operators
in C language.

2. Explain the importance of a switch case statement. In which situations is a switch case
desirable? Also give its limitations.

3. What are different formatting specifications of printf.

4. Write a program in C to find the area and perimeter of a circle.

5. Explain the two way selection (if, if-else, nested if-else, else-if ladder) in C language with
syntax

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 1


Programming for Problem Solving using C

6. Explain the differences between break and continue statement with example.

7. What is type- casting? Explain with an example

8. Write a C program to read a floating point number. Display the rightmost digit of the
integral part of the number.

9. Explain the syntax and usage of various I/O functions.

10. Write a C program to swap the values of two variables, say x and y, using temporary
variable and without using temporary variable.

C – TOKENS

Tokens: Tokens are the basic buildings blocks in C language which are constructed together

to write a C program. Each and every smallest individual units in a C program are known as C

tokens.

Various C tokens are as follows,

1. Keywords

2. Identifiers

3. Constants

4. Strings

5. Special symbols

6. Operators

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 2


Programming for Problem Solving using C

Example:
main()
{
int x, y, total;
x = 10, y = 20;
Total = x + y;
Printf (“Total = %d \n”, total);
}
Where, main – identifier, {,}, (,) – delimiter int – keyword
X, y, total – identifier
Main, {, }, (, ), int, x, y, total – tokens

Identifiers in c language:
Each program elements in a C program are given a name called identifiers. Names
given to identify Variables, functions and arrays are examples for identifiers.
Eg. Int X;
Float f;
Char c;
double d;
here X, f, c, d are the names given to integer, float, char and double variables.

Rules for constructing identifier name in c:


1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.

Keywords in c language:
Keywords are pre-defined words in a C compiler. Each keyword is meant to perform a
specific function in a C program. Since keywords are referred names for compiler, they can’t
be used as variable name.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 3


Programming for Problem Solving using C

Ex:

AUTO DOUBLE INT STRUCT

BREAK ELSE LONG SWITCH

CASE ENUM REGISTER TYPEDEF

CHAR EXTERN RETURN UNION

CONST FLOAT SHORT UNSIGNED

CONTINUE FOR SIGNED VOID

DEFAULT GOTO SIZEOF VOLATILE

DO IF STATIC WHILE

Constant:
C Constants are also like normal variables. But, only difference is, their values can not
be modified by the program once they are defined. Constants refer to fixed values. They are
also called as literals. Constants may be belonging to any of the data type.
Syntax:
Const data_type variable_name; (or) const data_type *variable_name;

Types of c constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 4


Programming for Problem Solving using C

Rules for constructing c constant:

1. Integer constants in c:
 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.
Example:
int (12, -762, -8 etc )
unsigned int (500u, 90U etc)

2. Real constants in c:
 A real constant must have at least one digit
 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.
Example:
float (0.456789)
double (123.123456789)

3. Character and string constants in c:


 A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.
Example:
char (Example: ‘A’, ‘B’, ‘C’)

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 5


Programming for Problem Solving using C

4. Backslash character constants in c:


 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of
them.
 Given below is the list of special characters and their purpose.

Backslash_character Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\” Double quote

\’ Single quote

\\ Backslash

\v Vertical tab

\a Alert or bell

\? Question mark

\N Octal constant (N is an octal constant)

\XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a c program?


 We can define constants in a C program in the following ways.
1. By “const” keyword
2. By “#define” preprocessor directive
 Please note that when you try to change constant values after defining in C program, it
will through error.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 6


Programming for Problem Solving using C

Example:
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
Variable:
 C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.

Rules for naming c variable:


1. Variable name must begin with letter or underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. Sum, height, _value are some examples for variable name

Declaring & initializing c variable:


 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
 Variable initialization means assigning a value to the variable.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 7


Programming for Problem Solving using C

S.No Type Syntax Example

Variable Data_type Int x, y, z; char


1 declaration variable_name; flat, ch;

Data_type Int x = 50, y =


Variable variable_name = 30; char flag =
2 initialization value; ‘x’, ch=’l’;

There are three types of variables in c program they are,

1. Local variable: These variables only exist inside the specific function that creates them.
They are unknown to other functions and to the main program. As such, they are normally
implemented using a stack. Local variables cease to exist once the function that created
them is completed. They are recreated each time a function is executed or called.

2. Global variable: These variables can be accessed (ie known) by any function comprising
the program. They are implemented by associating memory locations with variable names.
They do not get recreated if the function is recalled.

Example:

#include <stdio.h>
int add_numbers( void );
int value1, value2, value3; /* global variables*/

int add_numbers( void )


{
auto int result; /*local variable*/
result = value1 + value2 + value3;
return result;
}

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 8


Programming for Problem Solving using C

OPERATORS

 Operators are the symbols which operates on operands (value or a variable).


 C language has wide range of operators to perform various operations.
These are classified as:
1) Arithmetic
2) Relational
3) Logical
4) Assignment
5) Bitwise
6) Conditional
7) Increment and decrement.

1. Arithmetic operators: These are used to perform mathematical calculations .

For example, ’+’ is an operator to perform addition.

Operator Description

+ Addition or unary plus

- Subtraction or unary minus

/ division

* multiplication

% Remainder after division

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 9


Programming for Problem Solving using C

For example, a+b. Here a,b are operands and ‘+’ is an operator.

Program: (a+b)

#include<stdio.h>
main()
{
int a,b,c;
printf(“enter a&b values:”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“the sum of a&b is %d”,c);
c=a-b;
c=a*b
printf(“a*b=%d”,c);
c=a/b
printf(“a/b=%d”,c);
}
2. Relational operators: These operators checks relation b/w 2 operants .if the relation
is true it returns value 1 otherwise it returns o.
Ex:-a>b

Here ‘>’ is a relational operator.

 Relational operators are used in decision making and loops in c program.

Operator meaning Example

> Greater than 5>3(returns 1)

< Less than 5<3(returns 0)

== Equal to 5==3(returns 0)

!= Not equal to 5!=3(returns1)

>= Greater than equal to 5>=3(returns1)

<= Less than equal to 5<=3(returns0)

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 10


Programming for Problem Solving using C

3. logical operators: These are used to combine expressions containing relational


operators .
In ‘c’ there are 3 logical operators.

Operator meaning Example

&& Logical AND If c=5 and d=2


then,((c==5&&(d>5))

Returns false.

|| Logical OR If c=5 and d=2


then,((c==5||(d>5))

Returns true.

! Logical NOT If c=5 then (c!=5)

Returns false.

3. Assignment operator:

Most common assignment operator is ‘equal to’(=).this operator assigns the value in right side
to left side.

For example, a=5; /* here 5 is a value assigned to ‘a’*/

5=a; /*error occurs*/

Operator Example Same as

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 11


Programming for Problem Solving using C

4. Bitwise operators: These are used to perform bit level operations on each bit of data.

Operator meaning

& Bitwise AND

| Bitwise OR

^ Exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Example:

P q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

Program:

#include<stdio.h>
main()
{
int a,b,c;
printf(“enter a and b values:”);
scanf(“%d%d”,&a,&b);

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 12


Programming for Problem Solving using C

c=a&b;
printf(“bitwise AND of a&b is %d”,c);
c=a|b;
printf(“bitwise OR of a&b is %d”,c);
c=a^b;
printf(“bitwise exclusive OR of a&b is %d”,c);
}

6. Conditional operators:
 These are used for decision making in c programming .it takes 3 operands and consists
of 2 symbols (? And : ).
 It executes different statements according to test condition whether it is either true or
false.
 Syntax: conditional expression? expression 1:expression 2;
If the test condition is true, expression 1 is returned and if false, expression 2 is
returned.
Example:

C=(a>b)?a:b;

C=(c>0)?10:10;

Comma operator:

A set of expression separated by comma is a valid constant in the C language. For example i
and j are declared by the statements
int i , j;
i=(j=10, j+20);
In the above declaration, right hand side consists of two expressions separated by comma. The
first expression is j=10 and second is j+20. These expressions are evaluated from left to right.
ie first the value 10 is assigned to j and then expression j+20 is evaluated so the final value of
i will be 30.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 13


Programming for Problem Solving using C

Size of operator:

It is a unary operator which is used in finding the size of data types, constants, arrays,
structures, etc

Program:

#include<stdio.h>
main()
{
int a;
float b;
double c;
char ch;
printf(“sizeof int=%d bytes \n”,sizeof(a));
printf(“sizeof float=%d bytes \n”,sizeof(b));
printf(“sizeof double=%d bytes \n”,sizeof(c));
printf(“sizeof char=%d bytes \n”,sizeof(d));
}

7.Increment and decrement operators:

In ‘c’, “++” is called as an increment operator and “- - “ is called as an decrement operator .

They are classified into 2 types.

1. Pre-increment and post-increment.

2. Pre-decrement and post-decrement

Pre-increment:

In this first, the variable is incremented by 1 and only after that, any operation is performed on
variable.

Syntax: ++variable;

Example: ++i or ++a;

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 14


Programming for Problem Solving using C

int a,i=2;

a=++i;

In the above example, first ‘i’ is incremented to 1, i.e, ‘i’ becomes 3 and after that ‘i’ will be
assigned to a.

Post-increment:

In this first, the operator is performed on variable and only after that, variable is incremented
by 1.

Syntax: variable++;

Example: i ++or a++;

int a,i=2;

a=i++;

in the above example ,first ‘i’ is assigned to a and after that ‘i’ will be incremented by 1.

Pre-decrement:

In this first, the variable is decremented by 1 and only after that, any operation is performed
on variable.

Syntax: - -variable;

Example:

- -i or - -a;

int a,i=2;

a=- -i;

In the above example, first ‘i’ is decremented to 1 and only after that ‘i’ will be assigned to a.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 15


Programming for Problem Solving using C

Post-decrement:

In this first, the operator is performed on variable and only after that, variable is decremented
by 1.

Syntax: variable- -;

Example: i - -or a- -;

int a,i=2;

a=i- -;

In the above example, first ‘i’ is assigned to a and only after that ‘i’ will be decremented by 1.

EXPRESSIONS

An expression is a combination of variable, constants and operators.

Ex: SI=P*T*R/100

(a+b) c/d;

a*b+c (d+x);

5*a+b+b*c;

(a+b)*(x+y);

Evaluation of expressions:

An expression can be evaluated based on presidency of operators, after the evaluation of


expression, the value of the expression is assigned to the variable.

Ex: SI=P*T*R/100

Precedence of operators:

Operator precedence determines which operator will be performed first in a group of operators
with different precedence. For instance 5 + 3 * 2 is calculated as 5 + (3 * 2), giving 11, and
not as (5 + 3) * 2, giving 16.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 16


Programming for Problem Solving using C

Operator Name Associativity Operators


Primary scope resolution left to right ::
Primary left to right () [ ] . -> dynamic_cast typeid
Unary right to left ++ -- + - ! ~ & * (type_name) sizeof new
delete
C++ Pointer to Member left to right .*->*
Multiplicative left to right * / %
Additive left to right + -
Bitwise Shift left to right << >>
Relational left to right < > <= >=
Equality left to right == !=
Bitwise AND left to right &
Bitwise Exclusive OR left to right ^
Bitwise Inclusive OR left to right |
Logical AND left to right &&
Logical OR left to right ||
Conditional right to left ?:
Assignment right to left = += -= *= /= <<= >>= %= &= ^= |=
Comma left to right ,

 The order of priority in which the operations can perform in an expression is called
presidency.
 An arithmetic expression without parenthesis will be executed from left to right
using the rules of presidency of operators.

Highest Presidency :(,),*, /, %


Lowest Presidency: +, -

 The basic evaluation procedure includes two passes from left to right through the
expression.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 17


Programming for Problem Solving using C

 During the first pass the highest priority operator (if any) are applied as they are
encountered.
 Whenever parenthesis are used in the expressions, within parenthesis assumes
highest priority.
 If two or more sets of parenthesis appear one after the another as 9-12/(3+3)*(2-1).
The expression contained in the left most set is evaluated first and the right most set
in the last.
Ex: 9-12/ (3+3)*(2-1)
9-12/6*1
9-2*1
9-2
7
 If the parenthesis is nested and in such cases evaluation of the expression will
process outwards from the inner most set of the parenthesis.

Ex: A) 9-(12/ ((3+3)*2)-1


9-(12/6*2)-1
9-(2*2)-1
9-4-1
5-1
4

B) 9-((12/3) +3*2)-1
9-(4+3*2)-1
9-(4+6)-1
9-10-1
-1-1
-2

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 18


Programming for Problem Solving using C

Program 1:-

#include<stdio.h>
#include<conio.h>
main()
{
int a=20;
int b=10;
int c=15;
int d=5;
int e;
e=(a+b)*c/d;
printf("\n Value of (a+b)*c/d is : %d\n",e);
e=((a+b)*c)/d;
printf("\n Value of ((a+b)*c/d) is : %d\n",e);
e=(a+b)*(c/d);
printf("\n Value of (a+b)*(c/d) is : %d\n",e);
e=a+(b*c)/d;
printf("\n Value of a+(b*c)/d is : %d\n",e);
getch();
}

TYPE CONVERSIONS:

Generally the data type conversions or the type casting can be possible in the following
three ways.

1. Automatic Conversion using assignment operator


2. Conversion to higher type in expressions (implicit)
3. Using cast operator (Explicit)

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 19


Programming for Problem Solving using C

1. AUTOMATIC CONVERSION USING ASSIGNMENT OPERATOR:

If we are using the assignment operator the right side value can be automatically
converted into left side.
Ex -1: int x=5; Ex-2: int x;
float y; float y=3.5;
y=x; x=y;

2. CONVERSION TO HIGHER TYPE IN EXPRESSIONS (IMPLICIT):


If we are using an arithmetic expression that contains different types of data then the
resultant value type is equal to the higher type data of the expression. Automatically converts
lower type to higher type before the operation performed by the compiler and ultimately the
result in the form of higher type is known as implicit conversion.
Ex: int a;
float b;
double c, x;

x=a*b+c;
3. USING CAST OPERATOR (EXPLICIT):
We can also perform type conversion explicitly by using a cast operator in the following
way.
Syntax: (Type name) expression;
OR
(Type name) variable;
Where, type name is any of c data types and expression may be a constant, variables or any
arithmetic expressions.
Ex-1: a= (int) 8.65; Ex-2: x= (float) 7;
It returns a=8 It returns x=7.000000

Ex-3: y= (int) 6.5/ (int) 2.3;


y=int (6/2);
It returns y=3

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 20


Programming for Problem Solving using C

Program 1:-

#include<stdio.h>
main()
{
int cum=17,count=5;
double mean;
mean=(double)sum/count;
printf(“\n Value of mean is : %f\n”,mean);
}
Program 2:-

#include<stdio.h>
main()
{
int i=17;
char c=’c’;
int sum;
sum=i+c;
printf(“\n The value of sum is : %d\n”,sum);
}
INPUT AND OUTPUT
Non formatted Input Output function :
These are console Input Output Library function which deal with one character at a
time and string function for Array of characters ( String ).Unformatted I/O functions works
only with character datatype (char). The unformatted Input functions used in C are getch(),
getche(), getchar(), gets().

Syntax for getch () in C :


char c=getch();
getch() accepts only single character from keyboard. The character entered through getch() is
not displayed in the screen (monitor).

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 21


Programming for Problem Solving using C

Syntax for getche() in C :


C=getche();
Like getch(), getche() also accepts only single character, but unlike getch(), getche() displays
the entered character in the screen.

Syntax for getchar() in C :


C=getchar();
getchar() accepts one character type data from the keyboard.

Syntax for gets() in C :


gets(s)
gets() accepts any line of string including spaces from the standard Input device (keyboard).
gets() stops reading character from keyboard only when the enter key is pressed.
The unformatted output statements in C are putch, putchar and puts.

Syntax for putch in C :


putch(c );

putch displays any alphanumeric characters to the standard output device. It displays only one
character at a time.

Syntax for putchar in C :


putchar(c);

putchar displays one character at a time to the Monitor.

Syntax for puts in C :


puts(s);
puts displays a single / paragraph of text to the standard output device.

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char a[20];

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 22


Programming for Problem Solving using C

gets(a);
puts(a);

getch();
}

Formatted Input and Output:


The function printf() outputs to the standard output, the function fprintf() outputs to
the stream given as the first parameter. sprintf() composes a zero-terminated string passed by
reference as the first parameter. You must allocate enough space in it in advance. The function
snprintf() outputs at most size characters to the string. The return value of these functions is
the number of characters actually output (not including the trailing '\0' used to end output to
strings).
The format string may consists both of characters and literals, and determines how the
arguments arg_1 - arg_n will be formatted. Each of those arguments requires a format
specifier, that begins with the character % and has the following syntax:

%[-][+][0][x[.y]]conv

Here the terms put in brackets are optional. The meaning of these terms is as follows:

term meaning
- left justify the argument
+ print a number with its sign, + or -
0 pads a number with leading zeros
x minimum field width
.y number of decimal places
The conv is a character from the following list:

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 23


Programming for Problem Solving using C

conv meaning
b boolean (true/false)
d integer
e exponential notation
f floating point number
lf double precision f.p. number
o unsigned octal
s string of characters
x unsigned lower-case hexadecimal
X unsigned upper-case hexadecimal
The format string, or strings to be output, can contain special control sequences (escape
sequences):

ECS sequence meaning


\' single quote
\" double quote
\\ backslash
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 24


Programming for Problem Solving using C

CONTROL STATEMENTS

C provides two styles of flow control:


 Branching
 Looping

Branching is deciding what actions to take and looping is deciding how many times to
take a certain action.
if statement:
This is the simplest form of the branching statements. It takes an expression in
parenthesis and a statement or block of statements. if the expression is true then the statement
or block of statements gets executed otherwise these statements are skipped.

Flowchart:

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 25


Programming for Problem Solving using C

Syntax:

if (expression)
statement;

or

if (expression)
{
Block of statements;
}

or

if (expression)
{
Block of statements;
}
else
{
Block of statements;
}

or

if (expression)
{
Block of statements;
}
else if(expression)
{

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 26


Programming for Problem Solving using C

Block of statements;
}
else
{
Block of statements;
}

Example 1:
#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");


}

Example 2:
#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 27


Programming for Problem Solving using C

if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
}
Nested if….else statement:

The if...else statement executes two different codes depending upon whether the test
expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.

Flowchart:

Syntax of nested if...else statement:

if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 28


Programming for Problem Solving using C

// statements to be executed if testExpression1 and testExpression2 is false and


testExpression3 is true
}
.
.
else
{
// statements to be executed if all test expressions are false
}

Example:
#include <stdio.h>
main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}}

Switch statement
The switch statement is much like a nested if .. else statement. Its mostly a matter of
preference which you use, switch statement can be slightly more efficient and easier to read.
Syntax:

switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 29


Programming for Problem Solving using C

[default : statements4;]
}
Example:
#include <stdio.h>
main()
{
int Grade = 'A';

switch( Grade )
{
case 'A' : printf( "Excellent\n" );
case 'B' : printf( "Good\n" );
case 'C' : printf( "OK\n" );
case 'D' : printf( "Mmmmm....\n" );
case 'F' : printf( "You must do better than this\n" );
default : printf( "What is your grade anyway?\n" );
}
}
Using break keyword

If a condition is met in switch case then execution continues on into the next case
clause also if it is not explicitly specified that the execution should exit the switch statement.
This is achieved by using break keyword.

break Statement

The break statement terminates the loop immediately when it is encountered. The
break statement is used with decision making statement such as if...else.

Syntax: break;

Example:
# include <stdio.h>
main()
{
int i;
double number, sum = 0.0;

for(i=1; i <= 10; ++i)


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 30


Programming for Problem Solving using C

{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
}

Continue Statement

The continue statement skips some statements inside the loop. The continue statement
is used with decision making statement such as if...else.

Syntax of continue Statement

continue;

Example:
# include <stdio.h>
main()
{
int i;
double number, sum = 0.0;
for(i=1; i <= 10; ++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
if(number < 0.0)
{
continue;
}
sum += number; // sum = sum + number;
}
printf("Sum = %.2lf",sum);
}

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 31


Programming for Problem Solving using C

Goto Statement
The goto statement branches unconditionally from one point to another in the block. In
other words the goto statement transfers execution to another label within the statement block.

The goto requires a label to identify the place where the branch is to be made to. A label is
any valid identifier and must be followed by a colon. The label is placed immediately before
the statement where the control is to be transferred. The goto statement can transfer the
control to any place in a program.

Syntax :

goto label;

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

The label is an identifier. When goto statement is encountered, control of the program jumps
to label: and starts executing the code.

Forward and backward jump:

As shown in the above syntax, if the label is after the goto statement, then it is known as
forward jump and if the label is before the goto statement, it is known as backward jump.

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 32


Programming for Problem Solving using C

Example:

void fun(int x)
{
back:
if( condition1)
{
x++;
goto next;
}
else if( condition 2)
{x=x+2;
goto back;
}
x=x+3;
next:
printf(“%d”,x);
if (!done)
goto back;
}

Dr Prakash Bethapudi, Professor, HoD, IT, VIGNAN’S (VIEW) Page 33

You might also like