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

UNIT II Www.anuupdates.org

This document provides an introduction to the C programming language, covering its structure, features, advantages, and disadvantages. It details the basic components of a C program, including data types, keywords, identifiers, and the process of compiling and executing C programs. Additionally, it discusses the use of comments and the types of files used in C programming.

Uploaded by

fayaz mohammed
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)
15 views

UNIT II Www.anuupdates.org

This document provides an introduction to the C programming language, covering its structure, features, advantages, and disadvantages. It details the basic components of a C program, including data types, keywords, identifiers, and the process of compiling and executing C programs. Additionally, it discusses the use of comments and the types of files used in C programming.

Uploaded by

fayaz mohammed
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
You are on page 1/ 37

UNIT II Introduction to C:

Introduction – Structure of C Program – Writing the first C Program – File used in C Program – Compiling
and Executing C Programs – Using Comments –Keywords – Identifiers – Basic Data Types in C – Variables –
Constants – I/O Statements in C- Operators in C- Programming Examples.
……………………………………………………………………………………………………………………………..
C Language Introduction
C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and
1973. It was mainly developed as a system programming language to write operating system.

Some Facts about C Programming Language

 In 1988, the American National Standards Institute (ANSI) had formalized the C language.
 C was invented to write UNIX operating system.
 C is a successor of 'Basic Combined Programming Language' (BCPL) called B language.
 Linux OS, PHP, and MySQL are written in C.
 C has been written in assembly language.

Uses of C Programming Language

In the beginning, C was used for developing system applications, e.g. :

 Database Systems
 Language Interpreters
 Compilers and Assemblers
 Operating Systems
 Network Drivers
 Word Processors

C Has Become Very Popular for Various Reasons


 One of the early programming languages.

 Still, the best programming language to learn quickly.

 C language is reliable, simple and easy to use.

 C language is a structured language.

 Modern programming concepts are based on C.

 It can be compiled on a variety of computer platforms.

 Universities preferred to add C programming in their courseware.

Features of C Programming Language


 C is a robust language with a rich set of built-in functions and operators.

 Programs written in C are efficient and fast.

 C is highly portable; programs once written in C can be run on other machines with minor or no
modification.

 C is a collection of C library functions; we can also create our function and add it to the C library.

 C is easily extensible.

20 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Advantages of C
 C is the building block for many other programming languages.

 Programs written in C are highly portable.

 Several standard functions are there (like in-built) that can be used to develop programs.

 C programs are collections of C library functions, and it's also easy to add own functions to the C
library.

 The modular structure makes code debugging, maintenance and testing easier.

Disadvantages of C
 C does not provide Object Oriented Programming (OOP) concepts.

 There are no concepts of Namespace in C.

 C does not provide binding or wrapping up of data in a single unit.

 C does not provide Constructor and Destructor.

The limitations of C programming languages are as follows:


 Difficult to debug.

 C allows a lot of freedom in writing code, and that is why you can put an empty line or white space
anywhere in the program. And because there is no fixed place to start or end the line, so it is difficult
to read and understand the program.

 C compilers can only identify errors and are incapable of handling exceptions (run-time errors).

 C provides no data protection.

 It also doesn't feature reusability of source code extensively.

 It does not provide strict data type checking (for example an integer value can be passed for floating
data type)

21 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Structure of C Program
A c program is collection of different modules / Functions. Each module performs their own individual task.
The output of all modules are put together to generate final output. The basic structure of C program ANSI
C follow is given below

Documentation section:-

 This is the section where the programmer gives the details of the program.

 Comments are used to provide details.

 Generally it includes the name of the program, the author of the program and other details like date
when the program wrote.

 C supports two type of comments 1. Single line comments 2. Documents line comments.

Example:

1. Single line comments:

// this program calculates the sum of two matrices

22 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
2. Document / multiple line comments
/**
* File Name: first.c
* Author: anuupdates
* Date: 09/08/2020
* Description: a program to display sum of tow matrix
* give proper input.
*/
Link section
 The link section provides instructions to the compiler to link functions from system library.
 This can be done by including header files like #include<stdio.h>

Defination section

Here one can define all symbolic constants used in C program using define keyword, like

#define PI 3.148

Main function section

The main() is the starting point of nay C program.

The main is an independent module which performs some operations on data to accomplish a task with in a
C program. The main section contains two parts.

1. Declaration part: It is the place where all variable declarations are done.

2. Execution part:

 It contain instructions to the computer that cause it do some operations on data. Every C program
executable statement is terminated with semicolon.
 The execution part begins with the curly brackets and ends with the curly close bracket. Both the
declaration and execution part are inside the curly braces.

int main (void)


{
int a=10;
printf (" %d", a);
return 0;
}

Sub-Program Section

All user define functions are defined here.

23 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Writing the first C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.

To write the first c program, open the C console and write the following code:

1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello C Language");
5. return 0;
6. }

Line-1: #include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h .

Line-2: int main() The main() function is the entry point of every program in c language.

Line-4: printf() The printf() function is used to print data on the console.

Line-5: return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for successful
execution and 1 for unsuccessful execution.

Line-3&6: In C language, a pair of curly brackets define a scope and mainly used in functions and control
statements like if, else, loops. All functions must start and end with curly brackets.

Q) Compiling and Executing C Programs

What is a compilation?

The compilation is a process of converting the source code into object code. It is done with the help of the
compiler. The compiler checks the source code for the syntactical or structural errors, and if the source code
is error-free, then it generates the object code.

The following are the phases through which our program passes before being transformed into an executable
form:

 Pre-processor
 Compiler
 Assembler
 Linker

24 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
1. Pre-processor:

The source code is the code


which is written in a text editor
and the source code file is given
an extension ".c". This source
code is first passed to the
preprocessor, and then the
preprocessor expands this code.
After expanding the code, the
expanded code is passed to the
compiler.

2. Compiler

The code which is expanded by the


preprocessor is passed to the
compiler. The compiler converts this
code into assembly code. Or we can
say that the C compiler converts the
pre-processed code into assembly
code.

3. Assembler

The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is '.obj,' If
the name of the source file is 'hello.c', then the name of the object file would be 'hello.obj'.

4. Linker

Mainly, all the programs written in C use library functions. These library functions are pre-compiled, and the
object code of these library files is stored with '.lib' (or '.a') extension. The main working of the linker is to
combine the object code of library files with the object code of our program.

Q) Files used in C program


A C program uses four types of files as follows:

25 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Source Code File

 This file includes the source code of the program.

 The extension for these kind of files is '.c'. It defines the main and many more functions written in C.

 main() is the starting point of the program. It may also contain other source code files.

Header Files

They have an extension '.h'. They contain the C function declarations and macro definitions that are shared
between various source files. C provides us with some standard header files which are available easily.

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more than one
function of the same file.

Object files

 They are the files that are generated by the compiler as the source code file is processed.

 These files generally contain the binary code of the function definitions.

 The object file is used by the linker for producing an executable file for combining the object files
together. It has a '.o' extension.

Executable file

 This file is generated by the linker.

 Various object files are linked by the linker for producing a binary file which will be executed directly.

 They have an '.exe' extension.

26 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Using Comments in C
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in the C language.

1. Single Line Comments

2. Multi-Line Comments

Single Line Comments

Single line comments are represented by double slash \\. Let's see an example of a single line comment in C.

#include<stdio.h>
int main(){
//printing information
printf("Hello C");
return 0;
}
Even you can place the comment after the statement. For example:

Ex: printf("Hello C");//printing information

Multi Line Comments

Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code, but it can't
be nested.

Syntax:

/*

code

to be commented

*/

Let's see an example of a multi-Line comment in C.

#include<stdio.h>

int main(){

/*printing information

Multi-Line Comment*/

printf("Hello C");

return 0;

27 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32
reserved words (keywords) in the C language. A list of 32 keywords in the c language is given below:

Q) C Identifiers

C identifiers represent the name in the C program, for example, variables, functions, arrays, structures,
unions, labels, etc.

Rules for constructing C identifiers

 The first character of an identifier should be either an alphabet or an underscore, and then it can be
followed by any of the character, digit, or underscore.

 It should not begin with any numerical digit.

 In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers
are case sensitive.

 Commas or blank spaces cannot be specified within an identifier.

 Keywords cannot be represented as an identifier.

 The length of the identifiers should not be more than 31 characters.

 Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

total, sum, average, _m _, sum_1, etc.

Example of invalid identifiers

2sum (starts with a numerical digit)

int (reserved word)

char (reserved word)

m+n (special character, i.e., '+')

28 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Basic Data Types:

Each variable in C has an associated data type. Each data type requires different amounts of memory and has
some specific operations which can be performed over it.

A data type defines a set of values and the operations on that can be performed on them. Moreover a data
type tells to the compiler

1. What type of data the program can handle

2. How much memory is needed for that data?

3. What type of operations that can be performed on those data?

1. Basic Data Types

i) Void Data type

1. Designated by 'void' keyword.

2. Used in front of a function which does not return any value.

3. Used to create generic pointers.

ii) Integral Data type

The C language has three integral data types.

a) Boolean data type

 Used to represent two values 'true' or 'false'

 Designated by the keyword 'bool'

29 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
b) Character Data type

The characters are used to form words, numbers and expressions depending upon the computer on which
the program runs. There are two types of character types.

 Signed characters which occupies one byte in memory and range from -128 to 127

 Unsigned characters which occupies one byte in memory and range from 0 to 255

 The format specifier used is %c

c) Integer Data type:

An integer is a number without fractional part. C supports 4 different types of integer types.

Type Size in bytes Range Format specifier

Short int 1 -27 to 27-1 %hd

Int 2 -215 to 215-1 %d

Long int 4 -231 to 231-1 %ld

Long long 8 -261 to 261-1 %ud


int

d) Floating point type:

i) Real data type


real data type represents the real numbers; A number with decimal part.

ii) Imaginary data type


An imaginary number is used extensively in mathematics and engineering. An imaginary number is a real
number which is multiple of square root of -1

iii) Complex numbers type


A complex number is a combination of real and imaginary number.

2. Derived Data Types

Derived Data types are derived from the basic data types.

Examples: Arrays, functions, pointers

3. User Defined Data types:

C allows us to define our own data types such as structures and unions. These are called user defined data
types because the programmer or user creates them according to their needs.

30 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be
reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Declaring (or) Creating Variable

Each and every variable must be created before using in your c program. The basic syntax is

Syntax: type variable_list;

Example:

int a;

float b;

char c;

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

int a=10,b=20;//declaring 2 variable of integer type

float f=20.8;

char c='A';

The declaration tells to the compiler three things

The name of the variable

The type of the variable

The value of the variable.

Rules for defining variables

 A variable can have alphabets, digits, and underscore.

 A variable name can start with the alphabet, and underscore only. It can't start with a digit.

 No whitespace is allowed within the variable name.

 A variable name must not be any reserved word or keyword, e.g. int, floats, etc.

Assigning Value (OR) Initialization of variable

A variable must be initialized before it can be used in your C program. Initialization is nothing but storing
values in variable. A variable can be initialized in two ways:

i) Static initialization:

We can initialize the variable at the time same time of declaration using assignment operator (=).

int a=10,b=20;//declaring 2 variable of integer type

float f=20.8;

ii) Dynamic initialization:

In some programs the value of a variable is known when the program in execution or after execution. This
type of initialization is known as dynamic initialization.
31 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Ex: C=a+b;

Types of Variables in C

There are many types of variables in c:

a) Local variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

b) Global variable

A variable that is declared outside the function or block is called a global variable. Any function can
change the value of the global variable. It is available to all the functions.

It must be declared above the block.

c) Static variable

d) Automatic variable

e) External variable

Q) Constant in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c
programming" etc.

There are different types of constants in C programming.

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", etc.

2 ways to define constant in C

There are two ways to define constant in C programming.

1. const keyword

2. #define preprocessor

32 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
1) C const keyword

The const keyword is used to define constant in C programming.

1. Ex: const float PI=3.14;

Now, the value of PI variable can't be changed.

Example:

#include<stdio.h>

int main(){

const float PI=3.14;

printf("The value of PI is: %f",PI);

return 0;

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive
later.

Syntax: #define token value

Example:

#include <stdio.h>

#define PI 3.14

main() {

printf("%f",PI);

Q) Operators in C
An operator is a symbol that tells the compiler to perform certain mathematical or logical operations.

C is a rich set of operators it include all high level language operators as well as low level language operators
such as bitwise operators.

There are following types of operators to perform different types of operations in C language.

1. Arithmetic Operators

2. Relational Operators

3. Logical Operators

4. Increment and decrement operators

5. Ternary or Conditional Operators

6. Bitwise Operators

7. Assignment Operator

33 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
8. Special Operator

1. Arithmetic Operators

C provides all the basic arithmetic operators. They are shown in below table. The operators +, -,* and /all
work the same way as they do in other languages. These can operate on any built- in data type allowed in
C.

Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus

i) Integer Arithmetic: when both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression and the operation is called integer arithmetic. Integer arithmetic
always yields an integer value.

In the below examples, if a and b are integers, then for a=14 and b= 4 we have the following results:

A-b =10

A+b= 14

A*b= 56

a/b= 3 (decimal part truncated

a%b = 2( remainder of division)

Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic; a real
operand may assume values either in decimal (or) exponential notation

If x, y and z are floats, then we will have:

X= 6.0/ 7.0 = 0.8572

Y= 1.0/3.0 = 0.333

Z = -2.0 /3.0 = -0.6667

The operator % cannot be used with real operands.

Mixed – Mode Arithmetic: when one of the operands is real and the other is integer, the expression is called
a mixed mode arithmetic expression.

If either operand is of the real type, then only the real operation is performed and the results are
always a real number. Thus 15/10.0 = 1.5 where as 15/10 = 1.

34 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
2. Relational Operators:

The operators which are used to distinguish two values depending on their relationships. This operator
provides the relationship between two expressions. If the relationship is true it returns 1 otherwise 0.

Operator Meaning Example

< Less than 3<5 gives 1

> Greater than 7>9 gives 0

>= Less than or equal to 100>=100 gives 1

<= Greater than equal to 50>= 100 gives 0

3. Logical operators

Logical operators are used to combine expressions containing relational operators. The logical operators are

i) Logical AND (&&): The logical and operator produces true value when both expressions are true.

A B A&&B

0 0 0

0 1 0

1 0 0

1 1 1

ii) Logical OR: The logical operator produces TRUE value when one the of expression is true otherwise zero.

A B A&&B

0 0 0

0 1 1

1 0 1

1 1 1

iii) Logical NOT: The logical not operator takes a single expression and produces opposite value.

A !A

0 1

1 0

4. Assignment Operator

Assignment operators are used to assign the result of an expression to a variable, the general format of
assignment statement is:

Variable = name expression;

a=10;

In addition ’C’ has a set of ‘shorthand’ assignment operators of the form.

35 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
V OP = exp;

Where V is a variable, exp is an expression and OP is a C binary arithmetic operator. The operator

OP = is known as the shorthand assignment operator.

Some of the commonly used shorthand assignment operators are shown below.

Statement with simple Statement with shorthand

Assignment operator Operator

a=a+1 a+=1

a=a-1 a-=1

a=a*(n+1) a*=n+1

a=a/(n+1) a/=n+1

a=a%b a%=b

The use of shorthand assignment operators has three advantages:

1. What appears on the left hand side need not be repeated and therefore it becomes easier to write.

2. The statement is more concise and easier to read.

3. The statement is more efficient.

5. Increment and decrement operators / Unary operators

C allows two very useful operators not generally found in other languages. These are the increment and
decrement operators:

++ and - -

The operator ++ adds 1 to the operand, While – subtracts 1. Both are unary operators and takes the
following form:

++m; or m++;

--m ; or m - -;

++m; is equivalent to m=m+1; (or m+=1;)

--m; is equivalent to m=m-1; (or m-=1;)

While ++m and m++ mean the same thing when they form statements independently, they behave
differently when they are used in expressions on the right hand side of an assignment statement. Consider
the following:

m = 5;

y = ++m;

In the case, the value of y and m would be 6. Suppose, if we rewrite the above statement as

m = 5;

y = m++;

36 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
then, the value of y would be 5 and m would be 6. A prefix operator first adds 1 to the operand and then
the result is assigned to the variable on left. On the hand, a postfix operator first assigns the value to the
variable on left and then increments the operand.

6. Conditional operator

A ternary operator pair “?:” is available in C to construct conditional expressions of the form.

Exp1? exp2: exp 3

Where exp1, exp2, and exp3 are expressions.

The operator (? : )works as follows:

exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated and becomes the
value of the expression.

If exp1 is false, exp 3 is evaluated and its value becomes the value of the expression.

Note that only one of the expressions (either exp2 or exp3) is evaluated.

For example, consider the following statements.

a = 10;

b = 15;

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

In this example, x will be assigned the value of b.

7. Bitwise operators

C has a distinction of supporting special operators known as bitwise operators for manipulation of data at bit
level. These operators are used for testing the bits, or Lists the bitwise operators and their meanings.

Operator Meaning

~ One’s complement 9 Bitwise AND)

>> Right shit

<< left shit

& Bitwise AND

! Bitwise OR

^ Bitwise XOR ( Exclusive OR)

8. Special Operators:

These are used for special purpose in C language these operators are used in pointers, structures and unions
etc. Some types special operators as

I ) unary operator

II) Comma operator

III) Size of operator

IV) Member selection operator

37 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
I) Unary Operator: Those that operators on a single operand. The unary operators are ++, - -,
(underscore), & (address operand),* (indirection operator), size of operator and so on.

II) Comma Operator: When a no. of statement occurred in a C program having a relationship between
expressions. Then we can write all expression are statements in a single expression using comma
(,) operator. The comma operator are also used in variable declaration statement.

III) Size Operator: It is to display no. of bytes covered by a variable or an expression.

Ex: int a, b ;

B=size of (a); b contains 2

Iv) Member selection Operator: These operators are used in structures, unions and pointers.

These are ‘.’ And ‘->’.

38 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) I/O Statements in C

Reading the data from the input devices and displaying the result on the screen are two major task of
program. To perform these operations user-friendly, C has a number of input-output functions.

Formatted I/O functions:

1. Printf(): The printf() function prints all type of data values on output console. The general form is

Syntax: printf("format string", argument_list);

2. Scanf(): The scanf() function is used for input. It reads the input data from the console.

Syntax: scanf("format string", argument_list);

#include<stdio.h>

int main(){

int number;

printf("enter a number:");

scanf("%d",&number);

printf("cube of number is:%d ",number*number*number);

return 0;

Unformatted I/O functions:

The unformatted I/O functions can be classified into three types: 1) String I/O 2) Character I/O 3) File I/O

1) String I/O: These functions are used to read and print strings.

a) gets(): This function is used to read a string from the input console.

b) puts(): This is used to print a string on the output console.

2) Character I/O: These functions are used to read and print characters.

a) getchar(): This function reads character type data from the standard input device. It reads one character at
a time.

b) putchar(): This function print one character at a time on the output console.

c) getch(). getche(): These functions read any alpha numeric characters from the standard input devices.

d) putchar(): This function prints any alpha numeric value on output console.

39 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Type conversion / Type casting
Type conversion or type casting of variables refers to converting a variable value of one data type to
another. Type conversion is done implicitly where as type casting is done explicitly by programmer.

Type conversion:

Type conversion is done when the expression has different data types. To evaluate the expression, the data
type is promoted from a lower type to a higher level. The hierarchy is shown below.

Type conversion:

Type conversion is automatically done in expressions. This is known as promotion.

Example: int x=3;

float y=7.35;

double z=x+y;

In the above expression the ‘x’ is converted to float then addition is will take place.

Type casting:

Type casting is also known as forced conversion. It can be done by using cast operator.

Syntax: (Cast-type) expression;

Example:

40 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Without Type Casting:

int f= 9/4;

printf("f : %d\n", f );//Output: 2

With Type Casting:

float f=(float) 9/4;

printf("f : %f\n", f );//Output: 2.250000

41 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Chapter-II

Decision Control and Looping Statements

Introduction to Decision Control Statements– Conditional Branching Statements – Iterative Statements –


Nested Loops – Break and Continue Statement – Goto Statement

……………………………………………………………………………………………………………………………..

Q) Conditional Branching Statements

The conditional branching statements help to jump from one part of the program to another depending on
weather a particular condition is true or false. C provides three types of conditional branching statements.

1. If statement

2. Switch statement

3. Conditional operator.

1) If statements: The if statement many be implemented on different forms depending upon the complexity
of condition tested.

a) Simple if statement

b) If-else statement

c) Nested-if statement

d) else-if ladder statement.

a) Simple if statement: If Statement in C language is a programming conditional statement that executes a


code segment over a condition, provided if it is true and valid. Below is the syntax and flowchart for if
condition.

Syntax:

If(test condition)

Statement block;

Statement-x

The statement block is executed only if the condition is true and them followed by rest of the program
(statement-x) will be executed.

If the condition is false, the statement block is skipped and rest of the program is executed.

Example: Write a C program to check whether the given number is even or not.
42 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
#include<stdio.h>

int main()

int number=0;

printf("Enter a number:");

scanf("%d",&number);

if(number%2==0){

printf("your number is %d and it is an even number", number);

return 0;

b) If-else statement

The If-else statement is an extension of simple if statement. The general form is

Syntax:

If(test-condition)

True block statements;

else

else block statements;

Statement-x

The if-else statement works as follow

 If test condition is true both true block statements and statement-x are executed.

 If test condition is false both the else block statements and statement-x are executed.

 In any case both true block and else block are not executed at a time.

Example: Write a C program to find biggest of two numbers using if-else statement.

#include<stdio.h>

void main()

int a, b, c;

printf(“ enter a,b, c values”);

43 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
scanf(“%d %d”, &a, &b);

if(a>b)

printf(“a is big”);

else

printf(“ b is big”);

getch();

c) Nested-if statement:

C language supports if-else-if statement to test additional conditions a part from the initial condition. The
general form is

if(test condition-1)
{
if(test condition-2)
{
statement-2
}
else
{
statement-3
}
}
else
{
statement-1
}
statement-x

The if-else-if works as follows

 Statement-1 is executed when condition is


false.

 Statement-2 is executed when both


conditions are true.

 Statement-3 is executed when condition-1 is true and condition-2 is false.

 At a time one statement block will be executed followed by statement-x

44 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Example: write a c program to find biggest of three numbers using nested-if statement.

#include<stdio.h>
void main()
{
int a,b,c;
printf (“ enter a, b, c values”);
scanf(“ %d %d %d”, &a, &b, &c);
if(a>b)
{
if(a>c)
{
printf(“ a is big”);
}
else
{
printf(“ c is big”);
}
}
else
{
if(c>b)
{
printf(“ c is big”);
}
else
{
printf(“ b is big”);
}
}
getch();
}

d) else-if ladder:

There is another way of putting ifs together when multipath decisions are involved. A multipath decision is
chain of ifs in which the statement associated with each else is an if. It takes the following general form:

45 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
if(condition-1)
Statement-1;
else if(Statement-2)
Statement-2;
else if(condition-3)
Statement-3;
……………..
else if(condition-n)
Statement-n;
else
default statement;
Statement-x

 This construct is known as the else if ladder.


 The conditions are evaluated from the top (of the ladder), downwards.
 As soon as a true condition is found, the statement associated with it is executed and the control is
transferred to the statement-x (skipping the rest of the ladder).
 When all the n conditions become false, then the final else contain the default-statement will be
executed.

46 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Example: program on to display the examination result.

#include <stdio.h>

#include<conio.h>

void main ()

int marks;

printf(“%/n Enter the marks obtained: “);

scanf (“%d” , &marks);

if (marks>=75)

printf( “/n DISTINCTION”);

else if (marks>=60 && marks <75)

printf(“/n FIRST DIVISION”)

else if (marks >=50 && marks >60)

printf(“/n SECOND DIVISION”);

else if (marks >=40 && marks >50)

printf((“/n THIRD DIVISION);

else

printf (“/n FAIL”);

getch();

47 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
2. Switch Statement

C has a built in multi way decision statement known as a switch. The switch statement tests the value of a
given variable (or expression) against a list of case values and when a match is found, a block of statements
associated with that case is executed.

The general of the switch statement is as shown below

switch (variable)
{
case value1:
Statement block 1;
Break;
case Value 2:
Statement block2;
Break;
…………………..
case value N :
Statement block N;
Break;
Default:
}
Statement X ;

In the syntax of the switch case statement, the break statement must be used at the end of each case because
if it were not used, then all the cases from the one met will be executed.

To summarize the switch case construct, let us go through the following rules:

 The control expression that follows the keyword switch must be of integral type ( i.e., either
be an integer or any value that can be converted to an integer).

 Each case label should be followed with a constant or a constant expression.

 Case labels must end with a colon.

 The default label is optional and is executed only when the value of the expression does not
match with any labeled constant expression.

48 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Example : program on to determine whether an entered character is vowel or not.

#include<stdio.h>
#include<conio.h>
void man ( )
{
char ch;
printf(“/n Enter any character:”);
Scanf (“%c”, &ch);
switch (ch)
{
case ‘ a ‘
printf (“/n %%c is a VOWEL”, ch);
break;
case ‘e’
printf(“/n %c is a VOWEL”, ch);
break;
case ‘ I ‘:
Printf (“/n % c is a VOWEL “,ch);
case ‘o’
printf( “/n %c is a VOWEL”, ch);
break;
case ‘ u ‘
printf (“/n%c is a VOWEL”,ch);
break;
default : printf (“%c is not a VOWEL”, ch);
}
getch( );
}
3. Conditional operator

The operator pair (?, :) is called ternary operator and it takes the following form

Expression1 is evaluated first if it is true expression2 is evaluated and becomes the value of the value.
Otherwise expression3 is evaluated and becomes the value of the expression.

#include<stdio.h>
void main()
{
int a,b,results;
printf(“ enter a, b values”);
scanf(“ %d %d”. &a, &b);
results=a>b?a:b;
printf(“ results=%d”, results);
getch();
}

49 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Looping / Iterative statements in C
. When a single statement or a group of statements will be executed again and again in a program then such
type processing is called Loop (or iteration). The C programming language contains 3 different programming
statements for program looping.

1. for Loop

2. While Loop

3. Do while Loop

1. for Loop

The for loop in C language is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like the array and linked list.

Syntax:

for(intitilization;condition;update statements)

body of the loop

 The initialization statement is executed only once


at the beginning of the for loop.

 Then the condition is checked by the program. If


the condition is false, for loop is terminated.

 But if condition is true then the code/s inside body


of for loop is executed and then update
expression is updated. This process repeats until
test expression is false

Example:

#include<stdio.h>
void main ()
{
int i;
for(i=0;i<10;i++)
{
int i = 20;
printf("%d ",i);
}
}
The braces {} are used to define the scope of the loop. However, if the loop contains only one statement,
then we don't need to use braces. A loop without a body is possible. The braces work as a block separator,
i.e., the value variable declared inside for loop is valid only for that block and not outside.

50 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Infinitive for loop in C

To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to
provide two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.

#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome to infinite loop");
}
}

2. While loop:

While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be
executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if
statement. The while loop is mostly used in the case where the number of iterations is not known in
advance.

Syntax:

while(test expression)
{
body of the loop
}

 The test condition is evaluated and if the condition is true, then


body of the loop is executed.
 After execution of and if the condition of the body, the test
condition is once again evaluated and if it is true, the body is
executed once again.
 This process continues until the test-condition finally becomes
false the control is transferred out of the loop and the body of the loop may have one or more
statements.
 If the test condition evaluate to false at the first time the statements are never executed

Example:

#include<stdio.h>
int main(){
int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
return 0;

51 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
3. do-while

The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several
parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at
least once. The do-while loop is mostly used in menu-driven programs where the termination condition
depends upon the end user.

Syntax:

do
{
body of the loop
}while(test condition);

 In this first body of the loop is executed and then the


condition is checked.

 If condition is true then body of the loop is executed when


condition becomes false then it will exit from the loop.

 Note that semicolon must be at the end of the while.

Example:

#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
}

What are the differences between while and do-while loops?

A) There are many differences between while loop and do-while loop. Some important and basic differences
between them is as follows:

While loop:

1. In while loop the condition is tested first and then the statement are executed, if the condition turns
out to be true.
2. It is entry-controlled loop
3. Never execute loop if condition is false
4. There is no semicolon at the end of while statement
5. Syntax:
while(condition)
{
i. Statements;
}

Do-While loop:
1. In do while the statements are executed for the first time and then the conditions are tested. If the
condition turns out to be true then the statements are executed again.
2. It is exit-controlled loop.

52 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
3. A do while is used for a block of code that must be executed at least once.
4. There is semicolon at the end od while statement.
5. Syntax:
do
{
Statements;
} while (condition);

Q) Nested loops

A loop within another loop is called nested loop. Consider a loop where the outer loop runs ‘n’ time and
consists of another loop inside it. The inner loop runs ‘m’ times. Then the total number of times the inner
loop runs during program execution is m*n times.

Example: Write a C program to print the following pattern.

*
**
***
****
*****

#include<stdio.h>
void main()
{
int I, j;
for(i=0;i<=5;i++)
{
printf(“\n”);

for(j=1;j<=I;j++)
{
printf(“*”);
}
}
getch();
}

53 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) Break and continue
In various scenarios, you need to either exit the loop or skip an iteration of loop when certain condition is
met. So, in those scenarios are known as jumping out of the loop. There are two ways in which you can
achieve the same.

break statement

When break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.

In case of nested loop, if the break statement is encountered in the inner loop then inner loop is exited.

#include <stdio.h>
int main()
{
int counter;
for (counter=1; counter<=10; counter++)
{
if(counter==5)
{
break;
}
printf("%dn", counter);
}
return 0;
}

Output: 1 2 3 4

54 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Continue statement

Continue Statement sends the control directly to the test-condition and then continue the loop process.

On encountering continue keyword, execution flow leaves the current iteration of loop, and starts with the
next iteration.

#include <stdio.h>
int main()
{
int counter;
for (counter =1; counter<=10; counter++)
{
if(counter%2==1)
{
continue;
}
printf("%dn", counter);
}
return 0;
}

Output:

2 4 6 8 10

55 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d
Q) goto statement
A goto statement has two uses

1. A goto statement can transfer the control to any place in a program; it is useful to provide branching
within the loop.

2. A goto statement is used to exit from deeply nested loops when a error occurs.

 The goto statement is used to jump from one line to another line in the program.

 Using goto statement we can jump from top to bottom or bottom to top.

 To jump from one line to another line, the goto statement requires a label.

 Label is a name given to the instruction or line in the program.

 When we use a goto statement in the program, the execution control directly jumps to the line with
the specified label.

#include<stdio.h>
#include<conio.h>
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}

56 | © w w w . a n u u p d a t e s . o r g / D . V e n k a t a R e d d y U G C N E T , A P S E T Q u a l i f i e d

You might also like