-->

C programming

 4.1 Introduction 

Overview, History, Features, Advantages and Disadvantages of C language 


Overview of C Language

The C language is one of the most powerful languages. In the beginning due to the different architectures available, the programmer had to learn different languages to create different types of applications. The problem with low level languages is that they are very difficult for humans to understand and develop. On the other hand, High Level Languages are easy for humans to understand. 


The C language is a highly efficient programming language and easy to understand. It has both the properties of high level language and low level language, so it is also termed as Middle Level Language or intermediate language between high level language and low level language. It is a very powerful programming language because it is used to prepare system software as well as application software. It is a kind of general purpose, structured programming language. It has large numbers of vocabularies and simple syntax to write a program.


History of C Language 

C is a general purpose programming language. C language was designed and developed by Dennis Ritchie at Bell Laboratories in 1972. It is an offspring of the "Basic combined programming language" called BCPL developed in the year 1967 at Massachusetts Institute of Technology. This language is associated with the UNIX operating system. The source code for the UNIX operating system is coded in C. It runs under a number of operating systems including MS DOS. C programs are efficient, fast and highly portable programming language. The C language is named as C because its precedence was called B which was derived from BCPL by Ken Thompson in 1970 in Bell Labs. The development of UNIX in the C language made it uniquely portable and improvable. 

POINTS TO REMEMBER


C is a general purpose, portable, compact, simple and flexible programming language. 

Features of C Language 

C Language is a very popular language because it has large numbers of features for programmers to write medium types of programs. Some basic features of C language are given below. 

  • It is highly portable Language

  • It is a structured programming language because the program is divided into a number of functions.

  • It is a general purpose high level programming language. 

  • It is an internationally standardized programming language. 

  • It has both the features of high level languages as well as low level languages. 


Advantages of C Language

  • It is easy for debugging, testing and maintaining. 

  • It is a portable programming language. This means a program written for one computer may run successfully on another computer.

  • It is fast for executing. This means that the executable program obtained after compiling and linking runs very fast. 

  • It is a compact programming language. The statements in C language are generally short but very powerful.

  • It has only 32 Keywords so that's easy to remember. 

  • Its compiler is easily available. 

  • It has the ability to extend itself. Users can add their own functions to the C library.


Disadvantages of C Language 

C programming language has no strong disadvantages. But it has some negligible disadvantages that are given below.

  • There is no runtime checking. 

  • There is no strict type checking (for example we can pass an integer value for the floating data type). 

  • As the program extends it is very difficult to fix the bugs. 

  • It may compile time overhead due to the misplacing and excessive use of pointers.

  • It does not support modern programming approaches like object oriented programming. 

  1. List out features of C programming language. 

  2. List out advantages and disadvantages of C programming language. 


Structure of C Program 

Every C program contains a number of several building blocks known as functions. Each function performs tasks independently. The structure of C program is given below.

Header Files 

C program depends upon some header files for function definition that are used in the program. Each header file by default is extended with h. The file should be included using #include pre-processor directive. Example is given below. 

#include<stdio.h> 


Global Declaration

It declares some variables that are used in more than one function. These variables are known as global variables. 


void main() 

Every program of C language must contain the main () function. The main () is the starting point of every C program. 


Declaration Part 

It declares the variables that are used inside this particular function. The initialization of variables are also done in this section. 




Executable Part 

This part contains the statement blocks that may be input statement, process statement and output statement. 


User defined functions 

The functions defined by the user are called user defined functions. These functions are defined before or after the main() function. 


Comments 

It is not necessary in the program. However, to understand the flow of programs the programmer can include comments in a program.


Function header 

It defines the heading or prototypes of the functions.


Example 





Compiling Process 

Step 1 Use a text editor like notepad to write your source code and save the file with extension dot c. For example: abc.c


Step 2 Compile the program using a compiler. If the compiler doesn't find any errors in the program, it produces an object file with .obj extension and the same name as the source code file (for example, test.c compiles to test.obj). If the compiler finds errors, it reports them. We must return to step 1 to make corrections in your source code.


Step 3 Link the program using a linker. If no errors occur, the linker produces an executable program located in a disk file with .exe extension and the same name as the object file (for example, test.obj is linked to create test.exe) 

 

Step 4 Execute the program. We should test to determine whether it functions properly. If not, start again with step 1 and make modifications and additions to your source code. 







Your First C Program 

This demonstration uses a program named hello.c, which displays the words ‘Hello, World!’ on-screen. The source.code for hello.c is given below. 


Example: Simple program showing ‘Hello World’. 

1:  #include <stdio.h> 

2:  void main() 

3:   {

5: printf("Hello, World\n"); 

5:   }

(Don't use the line number and colon sign on the program.) 


  1. List out the major components of the C program? 

  2. Draw a figure of the compilation process in C programming. 


Header Files and C Preprocessor 

Header Files are standard files of C-programming language. It contains the function definition of library functions. They are written at the top of the program. Some header files are given below. 

POINTS TO REMEMBER


Header files are compulsory in language. That contains the function definition of library functions.



  • #include<stdio.h>: It is a standard input output header file. It contains the function definition of input output functions such as scanf(), printf() etc.


  • #include<conio.h>: It is a header file which is included in the program. This is used for  clrscr(), getch(), etc. We do not need to include this file in the C program. It is necessary for C++ programs. conio stands for CONsole Input Output header file. The clrscr() helps to clear the screen.


  • #include<math.h>: This header file is used for mathematical functions such as pow(), sqrt(), sin(), tan() , cos() etc.


  • #include<string.h> :It is string header file. It contains the function definition of string processing functions such as strlen(), strcat(), strcpy() etc. 

C Preprocessor

Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives. Preprocessor directives are placed in the source program before the main line, before the source code passes through the compiler. It is examined by the preprocessor for any preprocessor directives. If any appropriate actions are taken then the source program is handed over to the compiler.

POINTS TO REMEMBER 

Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives.

Preprocessor directives follow the special syntax rules and begin with the symbol # and do not require any semicolon at the end. A set of commonly used preprocessor directives are: 


Directive

Function

#define

Defines a macro substitution and symbolic constant

#include

Specifies a file to be included in the program 


Keywords

  • C language: C language has been designed and developed by Dennis Ritchie at Bell Laboratories in 1972. 

  • Features of C language: C language is portable, procedural, general purpose, structured, standardized and compact programming Language. 

  • Disadvantages of C language: Some disadvantages of C language are no runtime checking, no strict type checking. It may be compile time overhead due to the misplacing and excessive use of pointers. 

  • Components of C: The main components of C are Comments, header files, function header, global declaration, main(), Declaration part, Executable part and user defined functions 

  • Header files: Header files are standard files that are compulsory in C program and contains the function definition of library functions 

  • Preprocessor: Preprocessor is a program that processes the code before it passes through the compiler. It operates under the control of preprocessor command lines and directives.




  1. Why C is most popular language? Explain with suitable reasons. 

  2. Explain compilation process with appropriate block diagram. 

  3. Why are header files needed in every C program? Explain. 

  4. Write down the importance of the header file and explain briefly about any three header files  of C language.

  5. What is a pre-processor? List any two preprocessors. 

THE END

4.2 Fundamentals of C 

The characters are used to form words, numbers and expressions depending upon the computer on which the program runs. The character set in C language can be grouped into the following categories.


POINTS TO REMEMBER


C consists of character sets. They are letters, digits and special characters that form words, numbers and expressions.


Character Set

  • Letters: uppercase A to Z and lower case a to z 

  • Digits: 0 to 9

  • Special Characters: listed in the table

Special Characters 


,

Comma


&

Ampersand

.

Period


^

Caret

;

Semicolon


*

Asterisk

:

Colon


-

Minus

?

Question Mark


+

Plus

Apostrophe


<

OpeOpening Angle (Smaller than)

Quotation Mark


>

Closing Angle(Greater than)

!

Exclamation Mark


(

Left Parenthesis

|

Vertical Bar


)

Right Parenthesis

/

Slash


[

Left Bracket

\

Back slash


]

Right Bracket

~

Tilde


{

Left Brace

_

Underscore


}

Right Brace

$

Dollar Sign


#

Hash

%

Percentage Sign



White space






Use of Comments

Comments are very useful components of a program and they have no effect on the program. They help programmers for description of the program codes. Having good comments throughout our code will make it much easier to remember what specific parts of your code do. Comments can be written in two forms:


  • // Single Line Comments 

  • /* Multi-Line …………………………………………………………….………

…………………………comments */ 


Identifiers, Keywords and Tokens 

The smallest part of C programming language is called C tokens. C programs are written using these tokens. There are six types of C tokens that are given below. 


POINTS TO REMEMBER


Tokens are fundamental parts of the C program from which other parts are formed.


  • Keywords 

  • Operators 

  • Identifiers 

  • Constants 

  • Strings 

  • Special symbols 


Keywords 

There are certain words which are reserved by the C compiler. These words are known as keywords. They cannot be used as identifiers in the program. Mainly there are 32 keywords used in standard C language. 

POINTS TO REMEMBER


Keywords are reserved words that are per-defined in C programming language. 


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


Assignment - 3

  1. List out the character sets of C Language. 

  2. List out any ten keywords


Identifiers

Identifiers are the names given to program units such as variable, structure, function etc. They are not defined in the programming language but are used to define by the programmer. Some basic rules to define identifiers are given below.

  • First character must be an alphabet or (underscore)

  • It must consist of only letters, digits and underscore.

  • Any standard C language keyword cannot be used as an identifier name.

  • It should not contain a white space. 

  • It allows both upper case and lower case characters. 


POINTS TO REMEMBER


Identifiers are the names of program units. The rules of identifiers are used to define program units such as variable, constant, function, structure ete .


Valid Identifiers 

A1 B34 FIRST _NAME         x_1

 

Invalid Identifiers 

1A 34AB int void FIRST-NAME x.1


Data Types in C 

C language provides us the way to hold any type of data in it. It is called data type. In C language data types classified into two categories:- 

  • Primary data types

  • Secondary data types

















POINTS TO REMEMBER


Data types of C language are primary and secondary. They are mainly used to define the type and nature of data such that the compiler detects and proceeds.


Primary Data Types 

The fundamental data types are called primary data types. They are also used to build other data types. The fundamental data types are given in the following table. 


Variable Type

Keyword

Storage 

Size

Range

Character

char

1 byte

-128 to 127

Unsigned character

unsigned char

1 byte

0 to 255

Integer

int

2 byte

-32768 to 32767

Short integer

short int

2 byte 

-32768 to 32767

Long integer

long int

4 byte

-2,147,483,648 to 2,147,483,647

Unsigned integer

unsigned int

2 byte

0 to 65535

Unsigned short integer

unsigned short int

2 byte

0 to 65535

Unsigned Long integer

unsigned long int

4 byte

0 to 4,294,967,925

Float

float

4 byte

1.2 E-38 to 3.4E+38

Double

double

8 byte

2.2E-308 to 1.7 E+308

Long double

long double

10 byte

3.4 E-4932 to 1.1 E+308



signed/unsigned and long/short prefix are used before primary data types. A Signed data type defines both positive and negative values. For example: 

signed int x; //it holds both positive and negative numbers 

unsigned int x; // it holds positive numbers 


The long data type helps us to maximize the range of values and the short data type minimizes the range of values for basic data types. 

short int x; //it minimizes the range of values than ordinary integer value 

long int x; // it maximizes the range of values than ordinary integer value 

You will study later in chapter about secondary data types.

Assignment - 4

  1. What is an identifier? Determine followings are valid or invalid identifiers.
    1234, ER12, float, double_int, BIMALA, space, void 

  2. What are data types? List out primary data types. 

  3. Differentiate between signed and unsigned integer.


Variables and Constants 

Variable

A variable is a value that can change any time. It is a memory location used to store a data value. A variable name should be carefully chosen by the programmer so that its use is reflected in a useful way in the entire program. Any variable declared in a program should confirm to the following:

  • They must always begin with a letter, although some systems permit underscore as the first character. 

  • White space is not allowed. 

  • A variable name should not be a keyword. 

  • It should not contain any special characters.


Examples of invalid variable names are 

123  (area) 6th             % abc

Examples of valid variable names are 

Sun number Salary Emp_name averagel 


Types of Variable 

  • Numeric variable: The variable that stores numeric data only is called numeric variables. The numeric data may be whole numbers or fractional numbers. Examples of numeric variables are: integer, floating point and double. 

  • String variable: The variable that stores character data only is called string variable. The string data may be single character or string. Examples of string variables are: character, array of character (string), table of strings.


POINTS TO REMEMBER


Variables are simply names that can change the value while executing a program. It allocates memory space inside the memory of the computer. 

What is the purpose of variable declaration? 

The purpose of variable declaration is to allocate memory space inside a memory of the computer. Declaration does two things: 

  • It tells the compiler what the variable name is. 

  • It specifies what type of data the variable will hold. 

Syntax of variable declaration 

data_type v1, v2, v3, . vn; 

Where v1, v2, v3, .. vn are the names of valid variables. 

Examples 

int a,b;

float c;

char d;


This diagram describes that when the variables are declared, the spaces in memory are allocated according to size. In this example, a and b are integer, allocates 2 byte memory each, c is floating, allocates 4 byte memory, d is character, allocates 1 byte memory.


Constant 

A constant value is the one which does not change during the execution of a program. C supports several types of constants. These constants are given below: 

  • Integer Constants

  • Floating Constants 

  • Character constants 

  • String Constants 

  • Symbolic Constants 

  • Escape Sequence Constants 


POINTS TO REMEMBER


Constant value is a value that is never changed during the execution of a program.


Integer Constant 

An integer constant is a sequence of digits. There are 3 types of integers namely decimal integers, octal integers and hexadecimal integers. These constants are given below.

Decimal Integers: 123 -31 0 +78

Octal Integers: O26 O O347 O676

Hexadecimal integer: 0X2 OX8C OXbcd Ox


Character Constant 

A character constant stores only a single character. It is enclosed by a single quotation mark. Examples of character constants are:

 ‘A’ ‘B’ ‘h’ ‘2’ ‘6’


String Constant 

A string constant is a set of characters enclosed in double quotation marks. The characters in a string constant sequence may be an alphabet, number, special character and blank space. Example of string constants are 

“ALEX” “1234” “God Bless” “!.......?”


Symbolic Constant 

A symbolic constant is a type of constant that substitutes the value or expression to constant name. It is defined by using the pre-processor  #define. 

Syntax:

#define constant_name constant_value 

Example 

#define PI 3.14 

#define teachername     “PLK Computer SIR" 

#define area  100 


Escape Sequence Constant 

The non printing characters started with backslash(\) are called escape sequence constant. They are special characters used in output functions. Although they contain two characters they represent only one character. Given below is the table of sequence and their meanings.

POINTS TO REMEMBER


Escape sequence always starts  with \ and used in the output function.


Escape Sequence

Meaning

\a

Audible Alert(Bell)

\b

Backspace

\n

New Line

\r

Carriage Return

\t

Horizontal Tab

\v

Vertical Tab






Difference between Variables and constants 

Variables

Constants

(i) It is a name whose value can be changed during the execution of a program

(i) It is a name whose value cannot be changed during the execution of a program

(ii) The purpose of variable declaration is to allocate memory space inside a memory of a computer. 

(ii) The purpose of constant declaration is to allocate memory space inside a memory computer and assign value in it. 

(iii) Syntax: 

       data_type variable name;

(iii) Syntax:

       Data_type constant name=value;

(iv) e.g.

       int a;

       float b;

(iv) eg.

          int a=5;

          float b=10.9 ;


Assignment - 5

  1. List out types of variables with some valid and invalid examples. 

  2. List any five escape sequence constants. 

Type of Specifier

It is also known as a format specifier. Type of specifier controls the type and format of the value to be printed or entered. Each conversion specification begins with % sign and ends with a conversion character. The conversion character defines the data type of the corresponding argument. 

Specifier character

Meaning

c

Single character

d

Decimal integer

e

floating point value in exponent form

f

floating point value without exponent form

g

floating point value either e-type or f-type depending on value 

i

signed decimal integer 

o

octal integer without leading zero

s

String

u

unsigned decimal integer 

x

hexadecimal integer, without leading zero

ld

Long integer 

Statements: Simple and Compound Statements 

Statement: Statement causes the computer to carry out some action. It is terminated by semicolon. The types of statements of C language are given below. 

  • Simple statement 

  • Compound statement 

Simple statement: A simple statement consists of an expression followed by a semicolon. The execution of a simple statement causes the expression to be evaluated. Examples

b=5;

c=d+e; 

printf("Enter a number");


Compound statement: A compound statement consists of several individual Statements enclosed in a pair of braces { } . It provides capability for embedding Statements within other statements.

Example:

{

r=5;

area=3.14*r*r;

}

It shows a compound statement to calculate the area of the circle.

Keywords

  • Character sets: C character sets are letters, digits, and special characters and expressions.

  • Comments: Comments in code can be useful for a variety of purposes. They provide the easiest way to set off specific parts of code as well as providing a visual “split” between various parts of your code.

  • Keywords: Keywords are special words that are per-defined in C programming language.

  • Data types: Data types are mainly used to define the type and nature of data such that the compiler detects and proceeds. 

  • Variable: A variable is a value that can change any time. It is a memory location used to store a data value. The types of variables are numeric variable and string variable. 

  • Constant: A constant value is the one which does not change during the execution of a program.

  • Escape sequence constant: Escape sequence constants are non printing characters, always starts with \ and used in output function 

  • Statement: Statement causes the computer to carry out some action. It is terminated by semicolon. The types of statements are expression and compound control statements. 



Exercise 4(B)

  1. What are different character sets used in C? 

  2. Differentiate between keywords and identifiers.

  3. Write about primary data types used in C. 

  4. Write down the importance of variable declaration in the C program. 

  5. Define the statement and also mention its types.

THE END


4.3 Operators and Expressions 

Operators: Precedence and Associativity 

An operator is a symbol which helps to do certain mathematical calculations or logical manipulations. Operators are used in C language to operate on data and variables. C has a rich set of operators which can be classified as: 


POINTS TO REMEMBER 

C consists of operators that are used for mathematical and logical operations such as +, *, < , >  etc 

  • Arithmetic operators (Binary operators) 

  • Relational Operators (Comparison operators) 

  • Logical Operators (Boolean operators) 

  • Assignment Operator 

  • Unary Operators (Increment/decrement operators) 

  • Conditional Operators (Ternary operators) 

  • Comma Operator 

  • Size of Operator 

Arithmetic Operators 

All the basic arithmetic operations can be carried out in C. It can perform simple arithmetic calculations such as addition, subtraction, multiplication etc. It uses two operands so that it is called a binary operator. The types of arithmetic operators are given below. 


Operator 

Meaning

Examples

  • (Plus)

Addition

a+b

  • (Minus)

Subtraction

a-b

* (Asterisk)

Multiplication 

a*b

/ (Slash)

Division

a/b

% (Percentage)

Modulus(Remainder)

a%b


Relational Operators

It is required to compare the relationship between operands and bring out a decision accordingly. It is also called a comparison operator because it is used to compare any two expressions. C supports the following relational operators.



Operator 

Meaning

Examples

<

is less than

a<b

<=

is less than or equal to

a<=b

>

is greater than

a>b

>=

is greater than or equal to

a>=b

= =

is Equal to

a==b

!=

is not Equal to

a!=b


Logical Operators 

Logical operators are used to give logical value either true or false. C has the following logical operators; they compare or evaluate logical and relational expressions.


Operator 

Meaning

Examples

&&

Logical AND

(a>b) && (a>c)

||

Logical OR

(a>b) || (a>c)

!

Logical NOT

!(a==b)


Assignment 6 

  1. List out types of operators of C language. 

  2. Write examples of arithmetic, relational and logical operators.

Assignment Operator 

The assignment operator is used to assign the value of expression into a variable. It is written in the form: 

variable = expression 

Example 

x = a + b 

Where x is a variable and a+b is an expression. Here the value of a + b is evaluated and substituted to the variable x. 


There are other forms of assignment operators which are listed in table

Operator 

Statement with operator

Equivalent to

+=

a+=1

a=a+1

-=

a-=1

a=a-1

*=

a*=1

a=a*1

/=

a/=2

a=a/2

%=

a%=b

a=a%b


Unary Operators 

The increment and decrement operators are very useful operators in C language. They are extensively used in loops. The syntax of the operators is given below: 

  1. ++  variable name (increment prefix) 

  2.  variable name ++ (increment postfix) 

  3. -- variable name (decrement prefix) 

  4. variable name -- (decrement postfix) 


The increment operator ++ adds the value 1 to the current value of operand and the decrement operator - - subtracts the value 1 from the current value of operand. ++ variable name and variable name ++ mean the same thing when they form statements independently, they behave differently when they are used in expression on the right hand side of an assignment statement. 


Consider the following

m=5;

y = ++m; //prefix operation (first increment then assignment) 

In this case the value of y and m would be 6. 

Suppose if we rewrite the above statement as, 

m=5;

y = m++; //postfix operation (first assignment then increment) 

Then the value of y will be 5 and that of m will be 6. 

  • A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. 

  • On the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand. 


Assignment 7 

  1. List out assignment and unary operator. 

  2. Compare prefix and postfix operation. 


Ternary Operator (?:operator) 

Ternary operator is also known as a conditional operator as it checks the condition to make decisions. It uses two symbols: the question mark (?) and the colon (:) but not together as In >= ,<= etc. This is the only operator used in C that takes three operands so it is named as ternary operator. 

Syntax: 

(condition)?statement1:statement2     

In this operator, the first condition is checked and if it is found true then statement1 will be executed otherwise statement2 will be executed which is similar to the working style of if-else statement.  

Example

a=10;

b=15;

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

Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x. 


The Comma Operator

The comma operator can be used to link related expressions together. Comma-linked lists of expressions are evaluated left to right and value of right most expression is the value of the combined expression. 

Example 

value = (x = 10, y = 5, x + y); 

First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators the parenthesis is necessary.

The Size of Operator

The operator Size of gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier. 

Example 

m = sizeof (int): // value of m will be 2. 

n= sizeof (long int); value of n will be 4. 

The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program.


Precedence and Associativity 

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. Associativity refers to the direction of processing of an expression. 


For example x= 7+3*2, where 13 is assigned to x, not 20 because operator * has

higher precedence than + so it first gets multiplied with 3*2 and then adds into 7. 

Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first. 


Category

Operator

Associativity

Postfix

() [] 

Left to right

Unary

++ --

Right to Left

Multiplicative

* / %

Left to right

Additive

+ -

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

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




Assignment 8 

  1. Write the function of comma operator and sizeof operator. 

  2. List the precedence of operators.

Expressions 

An expression is a combination of variables, constants and operators written according to the syntax of C language. In C, every expression evaluates to a value that is, every expression results in some value of a certain type that can be assigned to a variable. Some examples of C expressions are shown in the table given below. 


POINTS TO REMEMBER


An expression is a combination of variables, constants and operators written according to the syntax of C language. In C every expression evaluates to a value .



Algebraic Expression 

C Expression

a x b - c

a*b-c

(m+n) (x+y)

(m+n)*(x+y)

(ab/c)

a*b/c

3x2+2x+1

3*x*x+2*x+1

(x/y)+c

x/y+c


Type Casting and Conversions 


Implicit Type Conversion 

C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without losing any significance. This automatic type conversion is known as implicit type conversion 


POINTS TO REMEMBER


The process of converting one type of data into another type is called type conversion.


Example 

float x;

int x1=5;

int x2=2;

x=x1/x2; 

printf( “Output is %f ”, x); 


Output is 2.000000 


Explicit type Conversion 

Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion. The process of such a local conversion is known as explicit conversion or casting a value. 

The general form is 

(type_name) expression 

Example 

float x; 

int x1=5; 

int x2=2; 

x=(float)x1/x2; 

printf( “Output is %f ”, x); 


Output is 2.500000 


Introduction to Library Functions

The functions that are pre-defined in programming language are called library functions. Some library functions are used for input/output operations, some are string processing operations, some are for mathematical operations and so on. Each library function can perform specific tasks and return specific values. Some library functions are given below in tabular form. Library functions are stored in respe header files. 






POINTS TO REMEMBER


The special functions that are well defined in C programming languages are called library functions such as printf(), scanf(), strlen(), sqrt() ete.



Library Functions

Meanings

sqrt(d)

Return the square root of d

exp(d)

Raise e to the power d

abs(d)

Return the absolute value of d

log(d)

Return the logarithm of d

pow(d1,d2)

Return d1 raised to the d2 power

printf(...)

Displays data from standard output device

scanf(...)

Enter data items from the standard input device

getchar()

Enter a character from the standard input device

putchar()

Display a character to a the standard output device

sin(d)

Returns the sine angle of d

cos(d)

Returns the cos angle of d

tan(d)

Returns the tangent of d

toascii()

Convert into ASCII code

tolower()

Convert letter to lowercase

toupper()

Convert letter to uppercase



Assignment 9 

  1. List out any five library functions. 

  2. Compare implicit type casting and explicit type casting. 

Keywords 

  • Operators: Operators are symbols that can be used for mathematical and logical operations such as +, *, <, + etc. 

  • Arithmetic operators: All the basic arithmetic operations can be carried out in C. It can perform simple arithmetic calculations such as addition, subtraction, multiplication etc. 

  • Relational operator: Relational operator is required to compare the relationship between operands and bring out a decision accordingly. 

  • Logical operators: Logical operators are used to give logical value either true or false. 

  • Assignment operator: Assignment operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression. 

  • Conditional operator: Conditional operator can be used to check condition and returns a value either true or false. 

  • Data conversion: The process of converting one type of data into another type is called data conversion. 

  • Library functions: The special functions that are well defined in C programming languages are called library functions such as printf(), scanf(), strlen(), sqrt() ete.


Exercise 4(C)

  1. What is an operator? List its types. 

  2. Differentiate between binary and ternary operator. 

  3. Differentiate between assignment and conditional operator 

  4. What are special operators of the C language? 

  5. Write down the precedence and associativity of operaČ›ors. 

  6. Write down the type casting process. 

  7. Write down the importance of library function.

THE END


4.4 Input/ Output Functions

Introduction 

Like other languages, C does not have any built-in input/output statements as part of its syntax. All input/output operations are carried out through printf() and scanf() function. There exist several functions that have more or less become standard for input and output operations in C. These functions are collectively known as the Standard I/O library because it can take or accept any type of data.

Each program that uses a standard input/output function must contain a statement #include<stdio.h> at the beginning. The instruction #include<stdio.h> tells the compiler to search for a file named stdio.h and place its contents at this point in the program. The contents of the header file become part of the source code when it is compiled.

C language consists of some I/O functions like getchar(), putchar(), scanf() gets(), puts(), getch(), putch(), getche() etc.

 

Input/Output Functions

The printf() and scanf() functions are known as formatted I/O functions because they can take any type of format of data from the I/O devices. 


printf() can be used to display some conversion characters along with some unchanged characters. Such conversion characters may include format specifiers or escape sequences.


Syntax: 

printf( "control string", arg1, arg2, ......); 

Here control string may consist of any simple characters or format conversion specifiers or escape sequences and arg1, arg2,.... are arguments (variables) that represent the individual data item.


Example 1

printf(“Hello”);

Here, the statement consists of simple characters without arguments and will display output ‘Hello’.



Example 2

int a=5;

printf(“%d”,a);

Here, printf() statement contains a format conversion specifier “%d”  and an argument ‘a’ which will display output 5.


Example 3

float a=0.5;

float b=987.8145;

printf(“ \n here are two values %f and %.3f ”, a, b);

Here, printf() statement contains characters "here are …….” , format  conversion specifiers “ %f ”, “ %.3f ”, escape sequence ‘\n’ and arguments ‘a’, ‘b’ which will display Output: 

here are two values 0.500000 and 987.814”.


scanf() can be used to get inputs from the user.

Syntax:

scanf (" control string " , argl, arg2,....)

Here control string may consist of any format conversion specifiers and arg1, arg2,.... are arguments specifying the address of locations where the data is stored. Control string and arguments are separated by commas. For example, if ‘k’ is a variable or argument then '&k' is its address. So, it must be written as &k with scanf function.


Examples:

int a;

float b;

char c;

scanf(“%d%f%c”,&a,&b,&c);

If input is 4,0.8 and m then values of a, b and c are respectively 4,0.800000 and m.


Differentiate between printf() and scanf() statements 


printf()

scanf()

1. It is used to display contents(text/number).

1. It is used to get inputs from the user.

2. It contains any simple characters, format conversion specifiers or escape sequence and arg1, arg2,... arguments(variables)

2. It does not contain simple characters, it contains format conversion specifier and arg1,arg2,..... arguments(variables).

3. Syntax:

printf(“control string”, arg1,arg2,....);

Here, control string may consist of simple string or format conversion specifiers and arg1,arg2,.... are arguments.

3. Syntax:

scanf(“control string”,arg1,arg2);

Here, control strings may consist of format conversion specifiers and arg1,arg2,... are arguments.

4. Example:

int main()

{

  float a=9861.492492;

 printf(“\n %.3f”,a);

}

4. Example:

int main()

{

     int a;

     printf(“Enter a number”);

     scanf(“%d”,&a);


Program 1   Write a program to find the sum of two input numbers.

#include<stdio.h>

int main()

{

int a,b,c;

printf(“\n Enter first number”);

scanf(“%d”,&a);

printf(“\n Enter second number”);

scanf(“%d”,&b);

c=a+b;

printf(“Sum is %d” ,c);

return 0;
}




Program 2   Write a program to find the square of a number.

#include<stdio.h>

int main()

{

int a,b;

printf(“\n Enter a number”);

scanf(“%d”,&a);

b=a*a;

printf(“Square = %d” ,b);

return 0;
}

Assignment 10 

  1. Enter two numbers and print sum, product, difference and division of both numbers using C program. 

  2. Input three numbers and print sum and average using C program.

  3. Write a C program to calculate and print simple interest (SI) and net amount (A), given that Sl=PTR/100 and A = SI+P.

Other Input/Output Functions

  1. getchar () and putchar():

The getchar() function is used to read (or accept) a single character. It can not take more than one character. 

Syntax: 

variable_name = getchar(); 

Here variable_name is a valid C name that has been declared as char type. 


The putchar() function is used to display the character contained in the variable name at the output screen / terminal. 

Syntax: 

putchar(variable_name); 

Where variable_name is a type char containing a character. 

Example 

#include<stdio.h>

int main()

{ char a; 

printf("Enter a character"); 

a=getchar(); 

putchar(a);

return 0;

}

In the above example, getchar() function accepts a character which stores in a variable 'a' and putchar() used to display stored character. 


  1. gets and puts():

The gets() function is used for a completely different purpose. It reads a string (group of characters) from the standard input and stores it in the given variable.

It reads a whole line of input until a newline. 

Syntax: 

gets (variable); 

Example: 

char name[25]; 

gets(name); // it will ask the user for a name and save the name into name

The puts() function is used to display text in the monitor which is stored in the variable. But the variable is always string data type. 

Syntax: 

puts (variable); 

or puts("string");

Example:

char name[25]={“Alex”};

puts(name);

This example will display name “Alex”


Program 3   Write a program to enter full name and print it on screen.

#include<stdio.h>

int main()

{

char name[100];

puts(“Enter your full name”);

gets(name);

puts(“Your Name is:”);

puts(name);

return 0;
}





Program 4   Write a program to input name,age and salary and print them on monitor.

#include<stdio.h>

int main()

{

char name[50];

int age;

float salary;

printf(“Enter name”);

gets(name);

printf(“Enter age”);

scanf(“%d”,&age);

printf(“Enter salary”);

scanf(“%f”,&salary);

printf(“Name=%s”,name);

puts(name);

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

printf(“\n Salary = %.2f” ,salary);

return 0;
}


Worked Out Examples:

Program 5   Write a program to input two numbers and print remainder and quotient.

#include<stdio.h>

int main()

{

int a,b,c,d;

printf(“ Enter two numbers”);

scanf(“%d%d”,&a,&b);

c=a/b;

d=a%b;

printf(“Quotient = %d” ,c);

printf(“Remainder =%d”,d);

return 0;
}

Program 6   Write a program to input seconds and convert it into hours,minutes and seconds.

#include<stdio.h>

int main()

{

int s,h,r,d,m,a;

printf(“Enter seconds”);

scanf(“%d”,&S);

h=s/3600; // for hour

r=s%3600;

m=r/60; // for minutes

d=r%60; // for seconds

printf(“Hour =%d Minutes=%d Seconds=%d” ,h,m,d);

return 0;
}


Program 7   Write a program to calculate area of a circle.

#include<stdio.h>

int main()

{

float r,a;

printf(“Enter radius”);

scanf(“%f”,&r);

a=3.14*r*r;

printf(“Area = %.2f” ,a);// upto two digits

return 0;
}

Keywords 

  • printf() statement: It can be used to display some conversion characters along with some unchanged characters. 

  • scanf() statement: It can be used to get inputs from the user. 

  • getchar(): The getchar() function is used to read (or accept) a single character. 

  • putchar(): The putchar() function is used to display the character contained in the variable name at the terminal. 

  • gets(): The gets() function is used to read a string from the standard input and store in the given variable. 

  • puts(): The puts() function is used to display text in the monitor which is stored in the variable.


Exercise 4 (D)

  1. What are input /output functions of c language? Explain with examples.

  2. Differentiate between getchar() and putchar () statements.

  3. What is gets() function? How it is different from puts () statements.

The End

Past NEB Board Examination Questions

  1. What is a ‘while’ loop statement? Write an algorithm and a C program to input a number and reverse it.[4+6] 2076

  2. Explain if -else control structure with example. [5] 2075 GIE

  3. What is a loop? Differentiate between while and do while loop. [2+3] 2075 Set A





4.5 Control Structures

Introduction

In most of the programs that we discussed till now, program statements were executed in the same order in which they were written. Each instruction was executed only once. This is not enough in programming. Sometimes we may have to execute program statements based on the given condition, sometimes we may have to execute program statements repeatedly, sometime we may have to choose an option and perform the task accordingly. To carry out all these tasks and other similar tasks, program statements must be executed in a controlled way and it can be done using control structure. 


Control Structures are those programming constructs which control the flow of program statements execution in a program. It also specifies the order of statements in the program. 


Mainly controls structures are classified into the following three categories: 

  • Branching (Selective Control Structure) 

  • Looping (Repetitive Control Structure) 

  • Jumping (Unconditional Control Structure) 

Besides these, if there is no looping/branching/jumping then the structure is called sequential structure. In sequential control structure, program statements are executed in a sequence that is one after another. 


POINTS TO REMEMBER 

Control Structures are those programming constructs which control the flow of program statements execution in a program. 


Decisions (Selective Control Structure) 

In selective control structure, selection is made on the basis of condition. We have options to go when the given condition is true or false. The flow of program statement execution is totally directed by the result obtained from the checking condition. Hence, program statements using selective control structures are also called conditional Statements. This type of control structure is mainly used for decision making. It can mainly be categorized into two types. 

  • Conditional Statement 

  • Switch-Case Statement 



Conditional Statement 

It is the most common decision making control structure which controls the flow of program statement execution based on the condition checked. It can be used in different forms as: 

  • if statement

  • if else statement 

  • if else if statement (Multipath Conditional Statement/ if-else ladder)

  • nested if else statement

if statement 

This is the simplest form of conditional statement in which statements are executed if the test expression (condition) is true. When the condition is false there is no option within this structure; in such a situation control must get out from the structure and statements outside this structure will be executed.


Syntax of if statement:

if(condition)

{

statements;

}

Braces are optional for only 

one statement as shown below:

if(condition)

statement; 


Flowchart of if statement:


Program 8   Write a program to demonstrate the use of if statement.

#include<stdio.h>

int main()

{

int n;

printf("\n Enter a number");

scanf("%d",&n);

if(n==2)

printf("\n Entered number is 2");

return 0;

}

Assignment 11 

  1. Write a C program to check whether the given number is positive. 

  2. Write a C program to check whether the given number is odd.

  3. Write a C program to check whether the given number is divisible by 5. 




if else statement

This is another form of selective control structure which can handle both expected as well as unexpected situations. In this control structure, statements written in the body part of if are executed if the condition is true otherwise statements written in the body part of else are executed. This is appropriate where we have to check only one condition.

Syntax of if else statement:

if(condition)

statement1;

else

    statement2;

In this case if the condition is true then statement1 is executed otherwise statement2 is executed. The else portion of the if-else statement is optional.




Flowchart of if else statement:

Program 9   Write a program to which reads any two numbers and displays the largest one.

#include <stdio.h>


int main()

{

    int num1,num2;

    printf("Input two numbers");

    scanf("%d%d",&num1,&num2);

    if(num1>num2)

    printf("%d is greater than %d",num1,num2);

    else

    printf("%d is greater than %d",num2,num1);

    return 0;

}


Assignment 12

  1. Write a program to check whether the given number is odd or even. 

  2. Write a program to check whether the given number is positive or negative.

  3. Write a program to check whether the given number is divisible by 5 and not divisible by 10. 

if-else if statement 

When we have two or more conditions to be checked in a series we can use if-else if Statement. It is also known as multiple conditional statement / multipath conditional statement / if-else ladder.

Syntax of if-else if statement:

if(condition1)

  statement1;

else if(condition2)

  statemen2;

........

else if(condition n-1)

   statement n-1;

else

statement n

In this statement, conditions are checked from the top of the ladder to downwards. As soon as the true condition is found, the statement associated with it are executed and the control is transferred to outside of the ladder skipping the remaining part of the ladder. When most of the conditions (condition-1 - condition n-1) are evaluated false then statements associated with the else part will be executed.

Flowchart of if-else-if statement:

Program 10 Write a program to find the largest among three numbers given by the user.

#include<stdio.h> 

int main()

{

    int a,b,c;

    printf("\n Enter any three numbers:"); 

    scanf("%d%d%d",&a,&b,&c);

    if(a>b && a>c)

    printf("\n%d is the largest number.",a); 

    else if(b>a && b>c)

    printf("\n%d is the largest number.",b);

    else 

    printf("\n%d is the largest number.",c); 

    return 0;

}


Assignment 13

  1. Write a program to find the largest number among four numbers given the user.

  2. Write a program to find the smallest number among five numbers given by the user.

  3. Write a program to check whether the given number is positive, negative or zero.


Nested if else statement

An entire if else statement written within the body of if part or else part of another if else statement is called nested if else statement. It is used when a condition is to be checked inside another condition at a time in the same program to make a decision. 


Syntax of if-else if statement:

if(condition1)

{

 if(condition2)

  statement1;


else 

   statement 2;

}

else

statement 3


Flowchart of if-else  ladder statement:

Program 11 Write a program that reads marks of five subjects and calculates total marks and percentage. Also awards the division on the basis of following criteria.

Percentage

Division

p>=75

Distinction

p>=60 and <75

First Division

p>=45 and <60

Second Division

p>=35 and <45

Third Division

Otherwise

Failed

[Hints: Pass marks and full marks for each subject are 35 and 100 respectively.]

#include<stdio.h>

int main()

{

int s1,s2,s3,s4,s5,total;

float p;

printf("Enter the marks of five subjects");

scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5);

total=s1+s2+s3+s4+s5;

p=(float)total/5;

printf("Total marks=%d  Percentage=%0.2f\n",total,p);

if(s1>=35 && s2>=35 && s3>=35 && s4>=35 && s5>=35)

    {

        if(p>=75)

            printf("Distinction");

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

            printf("First Division");

        else if(p>=45 && p<60)

            printf("Second Division");

        else

            printf("Third Division");

    }

    else

    {

        printf("Failed");

    }

    return 0;

}

Assignment 14

  1. Write a program to find the largest number among three positive numbers using nested if else statement.

  2. Write a program to find the given number is divisible by 5 and not by 10 using nested if else statement.


Switch Case Statement 

C switch case statement is a multipath decision making statement that allows selection and execution of a particular block of statements from several blocks of statement based upon the value of expression which is included within the switch statement and branches accordingly. The expression must be of an integral value (“integral” values are simply values that can be expressed as an integer, such as the value of a char).


The same task can be performed using an if-else ladder as well but as the number of alternatives increases, the selection process becomes more complex (more time consuming). The main difference between if else ladder and switch statement is - In if-else ladder selection of appropriate option is made in serial fashion whereas in switch-case statement it is done in parallel fashion. So switch statement is much faster than if-else ladder. The switch statement body consists of a series of case labels and an optional default label. The default label can appear only once and anywhere in the body of the switch statement.


Syntax

Syntax Description

switch(expression)

{

    case constant 1:

     statement 1;

      break;

   case constant 2:

     statement 2;

      break;

     --------------
  case constant n-1:

     statement n-1;

      break;

  default:

    statement n;

}

  • When the switch statement is executed, the value of expression is compared with the value of case constant (constant1 , constant2...)

  • Then the block of statements associated with the case whose value is matched with expression will be executed.

  • a break statement at the end of block indicates the end of the particular case and cause an exit from switch statement and control will be transferred to statements following with switch.

  • If none of the cases match with the value of the expression, then the block of statement under default is executed.

Program 12 Write a program which reads any two integer values from the user and calculates sum, difference and product using switch statement.

#include<stdio.h>

int main()

{

    int num1,num2,sum,diff,pro,choice;

    printf("Menu");

    printf("Press 1 for Sum\n");

    printf("Press 2 for Difference\n");

    printf("Press 3 for Product\n");

    printf("Enter two numbers");

    scanf("%d%d",&num1,&num2);

    printf("Enter your choice");

    scanf("%d",&choice);

switch(choice)

{

    case 1:

        sum=num1+num2;

        printf("%d + %d =%d ",num1,num2,sum);

    break;

    case 2:

        diff=num1-num2;

        printf("%d - %d =%d ",num1,num2,diff);

    break;

    case 3:

        pro=num1*num2;

        printf("%d * %d =%d ",num1,num2,pro);

    break;

    default:

      printf("Enter the numbers between 1 to 3");

}

    return 0;

}





Assignment 15

  1. Write a program to display the name of the day in a week, depending on the number entered through the keyboard using the switch statements.

Answer:

#include<stdio.h>

int main()

{

    int ch;

    printf("Enter choice between 1 to 7");

    scanf("%d",&ch);

    switch(ch)

    {

    case 1:

        printf("Sunday");

        break;

    case 2:

        printf("Monday");

        break;

     case 3:

        printf("Tuesday");

        break;

     case 4:

        printf("Wednesday");

        break;

     case 5:

        printf("Thursday");

        break;

     case 6:

        printf("Friday");

        break;

     case 7:

        printf("Saturday");

        break;

     default:

        printf("Wrong choice");

    }

    return 0;

}

Looping (while, do while and for) 

Looping is the process of executing the same program statement or block of program statements repeatedly for a specified number of times or till the given condition is satisfied. Loop structure is used to carry out looping. 


For example, if we want to display "C is the best" 10 times, one way to get the desired output is - we type printf("C is the best"); 10 times, which is time consuming hence not preferable. Another way to perform this is - use of loop structure. With loop structure we don't need to type the same program statement again and again. Loop structure is also known as repetitive control structure or iterative control structure

POINTS TO REMEMBER 

A control structure that executes the same program statement or block of program statements repeatedly for a specified number of times or till the given condition is satisfied is called Loop.


Mainly there are three types of loop: 

  1. while Loop

  2. do while Loop

  3. for Loop


while Loop

It executes the program statements repeatedly until the given condition is true. It checks the condition at first; if it is found true then it executes the statements written in its body part otherwise it just gets out of the loop structure. It is also known as entry control or pre-test loop.


Syntax of while Loop:

initialization;

while(condition)

{

  statements;

  increment/decrement;

}

Where initialization means starting point, control means stopping points and increment/decrement means counter.

Flowchart of while Loop:



Program 13 Write a program to display “C is the best” 10 times using a while loop.

#include<stdio.h>

int main()

{

    int i=0;

    while(i<10)

    {

    printf("C is the best\n");

        i++;

    }

    return 0;

}

Program 14 Write a program to display numbers from 1 to 10.

#include<stdio.h>

int main()

{

    int i=1;

    while(i<=10)

    {

    printf("%d\n",i);

        i++;

    }

    return 0;

}

Program 15 Write a program to calculate and display sum of the numbers from 1 to 10.

#include<stdio.h>

int main()

{

    int i=1,sum=0;

    while(i<=10)

    {

        sum=sum+i;

        i++;

    }

    printf("Sum of numbers between 1 to 10 is %d\n",sum);

    return 0;

}


Assignment 16

Write programs using while loop to:

  1. Display your name 10 times on screen

  2. Display the series: 10 9 8 ….. to 1.

  3. Calculate and display sum of odd natural numbers up to n.


do while Loop

It also executes program statements repeatedly until the given condition is true. It executes the program statements once at first then only condition is checked. If a condition is found true then it executes the program statements again, otherwise it gets out from the loop structure. As it checks the condition at last it is also known as the post-test loop or exit control loop.


Syntax of do while Loop:

initialization;

do

 {

  statements;

  increment/decrement;

 }while(condition);


Flowchart of  do while Loop:

Program 16 

Write a program to display the series: 1 6 11 16…. 101.

#include<stdio.h>

int main()

{

    int i=1;

    do

    {

    printf("%d\t",i);

    i=i+5;

    }while(i<=101);

    return 0;

}



Program 17 

Write a program to display the series: 5 9   13… up to 10th terms.

#include<stdio.h>

int main()

{

    int i=1,a=5;

    do

    {

    printf("%d\t",a);

    a=a+4;

    i++;

    }while(i<=10);

    return 0;

}


Program 18 

Write a program to display a multiplication table of 6.

#include<stdio.h>

int main()

{

    int i=1,ans;

    do

    {

        ans=6*i;

    printf("6*%d=%d\n",i,ans);

    i++;

    }while(i<=10);

    return 0;

}


Assignment 17

Write programs using do while loop to:

  1. Calculate and display the series 1    8   27 …. to 10th terms

  2. Display the series: 15 9 ……. up to 20th terms

  3. Display the multiplication table of any number given by the user.

Difference between while and do while loop

while loop

do while loop

In the while loop, condition is checked in the beginning.

In the do while loop, condition is checked at the end.

It is also known as a pre-test or entry control loop.

It is also known as post-test or exit control loop.

It is not terminated with a semicolon.

It is terminated with a semicolon.

In the while loop, statements are not executed if the condition is false.

In the do while loop, statements are executed once even the condition is false.

It uses the keyword ‘while’.

It uses two keywords ‘do’ and ‘while’.

The syntax of while loop is as follows:

initialization;

while(condition)

{

  statements;

  increment/decrement;

}

The syntax of do-while loop is as follows:

initialization;

do

 {

  statements;

  increment/decrement;

 }while(condition);

The operation of while loop can be represented using flowchart as follows:

The operation of do while loop can be represented using flowchart as follows:

Example:
#include<stdio.h>

int main()

{

    int i=1;

    while(i>=10)

    {

        printf("I love my country");

        i++;

    }

    return 0;

}

Output: This program displays nothing as output; as condition is evaluated false in the beginning.

Example:

#include<stdio.h>

int main()

{

    int i=1;

    do

    {

        printf("I love my country");

        i++;

    }while(i>=10);

    return 0;

}

Output: This program displays “I love my country as output at once.


for loop

It is the most common type of loop which is used to execute a program statement or block of program statements repeatedly for a specified number of times. It is a definite loop. Mainly it consists of three expressions: initialization, condition and increment / decrement. The initialization defines the loop starting point, condition defines the loop stopping points and counter helps to increment and decrement the value of counter variable.



Syntax of for Loop:

for(initialization;condition;increment/decrement )

{

      statements;


}

Flowchart of for Loop:



Program 19 Write a program to calculate and display the value of y raised to power x. (z=yx).

#include<stdio.h>

int main()

{

    int x,y,i,z=1;

    printf("Enter the value of x and y");

    scanf("%d%d",&x,&y);

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

    {

     z=z*y;

    }

    printf("%d raised to %d = %d",y,x,z);

    return 0;

}


Program 20 Write a program to calculate and display factorial of 5.

[The product of a given positive integer multiplied by all lesser positive integers: The quantity five factorial (5!) = 5x4 x 3 x 2 x 1 = 120.]

#include<stdio.h>

int main()

{

    int i,f=1;

    for(i=5;i>=1;i--)

    {

        f=f*i;

    }

    printf("Factorial of 5 = %d",f);

    return 0;

}




Program 21 Write a program to display 1 to 10 and respective factorials.

#include<stdio.h>

int main()

{

    int i,f=1;

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

    {

        f=f*i;

        printf("Factorial of %d = %d\n",i,f);

    }


    return 0;

}

Nested Loop

We can write an entire loop structure inside another loop structure. So a loop inside another loop is called a nested loop.

Syntax:

Nested for loop:

for(initialization; condition ; increment/decrement)

{

for(initialization; condition ; increment/decrement)

{

statements;

}

}

Program 22 Write a program to  display the following:

1

12

123

#include<stdio.h>

int main()

{

    int i,j;

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

    {

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

        {

                printf("%d",j);

        }

        printf("\n");

    }

    return 0;

}

Practice Programs for Nested Loop by PLK  SIR:


Algorithm to solve nested loop

Step 1: Write Outer Loop by making pattern of change value

Step 2: Write inner loop

Step 3: Print matter 

3.1 Horizontal change- Inner Loop

3.2 Horizontal not change- Outer Loop

3.3 Everywhere same (*)- Print the repeating item

Step 4: Print New Line  - after inner loop


Nested Program-1

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

Hint:

1-1

1-2

1-3

1-4

1-5

Answer:

#include <stdio.h>

int main()

{   int i,j;

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

      {

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

        {

       printf(" %d ",j);

        }

        printf("\n"); 

      } 

 return 0;

 }

Nested Program-2

1

2 2

3 3 3

4 4 4 4 

5 5 5 5 5

Hint:

1-1

1-2

1-3

1-4

1-5

Answer:

#include <stdio.h>

int main()

{  int i,j;

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

      {

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

        {

       printf(" %d ",i);

        }

        printf("\n"); 

      } 

 return 0;

 }


Nested Program-3

5

5 4

5 4 3

5 4 3 2

5 4 3 2 1

Hint:

5-5

5-4

5-3

5-2

5-1

Answer:

#include <stdio.h>

int main()

{   int i,j;

     for(i=5;i>=1;i--)

      {

     for( j=5;j>=i;j--) 

        {

       printf(" %d ",j);

        }

        printf("\n"); 

      } 

 return 0;

 }

Nested Program-4

5

4 4

3 3 3

2 2 2 2

1 1 1 1 1

Hint:

5-5

5-4

5-3

5-2

5-1

Answer:

#include <stdio.h>

int main()

{   int i,j;

     for(i=5;i>=1;i--)

      {

     for( j=5;j>=i;j--) 

        {

       printf(" %d ",i);

        }

        printf("\n"); 

      } 

 return 0;

 }

Nested Program-5

*

* *

* * * 

* * * * 

* * * * *

Hint:

1-1

1-2

1-3

1-4

1-5

Answer:

#include <stdio.h>

int main()

{   int i,j;

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

      {

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

        {

       printf(" * ");

        }

        printf("\n"); 

      } 

 return 0;

 }

Nested Program-6

1

2 3

4 5 6

7 8 9 10

11 12 13 14 15

Hint:

1-1

1-2

1-3

1-4

1-5

Answer:

#include <stdio.h>

int main()

{   int i,j,p=1;

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

      {

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

        {

       printf(" %3d ",p);

       p=p+1;

        }

        printf("\n"); 

      } 

 return 0;

 }

Nested Program-7

2

4 6

8 10 12

14 16 18 20

22 24 26 28 30

Hint:

1-1

1-2

1-3

1-4

1-5

Answer:

#include <stdio.h>

int main()

{   int i,j,p=2;

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

      {

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

        {

       printf(" %3d ",p);

       p=p+2;

        }

        printf("\n"); 

      } 

 return 0;

 }

Nested Program-8

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1


Hint:

1-5

1-4

1-3

1-2

1-1

Answer:

#include<stdio.h>

int main()

{

int i,j;

for(i=5;i>=1;i--)

{

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

    {

        printf("%d ",j);

    }

    printf("\n");

}

return 0;

}

Nested Program-9

5 5 5 5 5

4 4 4 4

3 3 3

2 2

1


Hint:

1-5

1-4

1-3

1-2

1-1


Answer:

#include<stdio.h>

int main()

{

int i,j;

for(i=5;i>=1;i--)

{

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

    {

        printf("%d ",i);

    }

    printf("\n");

}

return 0;

}

Nested Program-10

5 4 3 2 1

5 4 3 2

5 4 3

5 4

5


Hint:

5-1

5-2

5-3

5-4

5-5

Answer:

#include<stdio.h>

int main()

{

int i,j;

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

{

    for(j=5;j>=i;j--)

    {

        printf("%d ",j);

    }

    printf("\n");

}

return 0;

}

Nested Program-11

* * * * *

* * * *

* * *

* *

*


Hint:

1-5

1-4

1-3

1-2

1-1

Answer:

#include<stdio.h>

int main()

{

    int i,j;

    for(i=5;i>=1;i--)

    {

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

        {

            printf(" * ");

        }

            printf("\n");

    }

    return 0;

}

Nested Program-12

15 14 13 12 11

10 9  8  7

6  5  4

3  2

1

Hint:

1-5

1-4

1-3

1-2

1-1

Answer:

#include<stdio.h>

int main()

{

    int i,j,p=15;

    for(i=5;i>=1;i--)

    {

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

        {

            printf("%5d",p);

            p=p-1;

        }

            printf("\n");

    }

    return 0;

}



Nested Program-13

1 2 3

2 3 4

3 4 5

4 5 6

5 6 7

Hint:

1-3

2-4

3-5

4-6

5-7

Answer:

#include <stdio.h>

int main()

{   int i,j,p=0;


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

      {

     for(j=0;j<=2;j++)

        {

         printf(" %d ",i+j);

        }

        printf("\n");

      }

 return 0;

 }



Nested Program-14

1  2   3...N

2  4   6...2N

3  6   9 ….3N

-----

N 2N  3N…...NN

Hint:

1- N

2-2N

3-3N

----

N-NN

Answer:

#include <stdio.h>

int main()

{   

int i,j,n;

printf("Enter the value for n: ");

scanf("%d",&n);

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

      {

     for(j=1;j<=n;j++)

        {

       printf(" %3d ",i*j);

        }

        printf("\n");

      }

 return 0;

 }

Infinite Loop

A loop which never terminates is called infinite loop that is it executes the program statements repeatedly which doesn’t meet any ending point.


Example of infinite loop:

#include<stdio.h>

int main()

{

int i;

for(i=1;i>=0;i++)

{

printf("%d",i);

    }

return 0;

}



Jumping Statement

Jumping statements are particularly used to jump execution of program statements from one place to another place inside a program. These statements may execute the same program statement repeatedly or skip some program statements. Following are the jumping statements defined in C programming language.

  • break

  • continue

  • goto

break statement

As its name implies, it is used to break the normal flow of program statement execution in loop and switch case statement. It allows us to exit from the innermost enclosing loop or switch statement as soon as certain condition is satisfied. 

When ‘break’ is encountered in the program (loop body/switch statement), the remaining part of the loop/switch statement is skipped and control will be passed to the next statement after loop; terminating the loop/switch statement. For example, while searching a number in a set of 100 numbers; when the required number is found it is obvious to get terminated from the loop. In such cases a break statement is used to do so.


Example of break statement:

#include <stdio.h>

int main()

{

    int i;

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

    {

        if(i==4)

        break;

        printf(" %d\t ",i);

    }

    return 0;

}


When the value of i becomes 4 then break is encountered and control is passed to outside the loop structure. 

The output of this program is    1 2 3


continue statement

As its name implies, it is used to continue the normal flow of program statement execution in loop; skipping particular iteration in the loop as soon as certain condition is satisfied. When 'continue' is encountered in the program (loop body) then that particular iteration is skipped and the loop will be continued with the next iteration. 

Example of continue statement:

#include <stdio.h>

int main()

{

    int i;

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

    {

        if(i==4)

        continue;

        printf(" %d\t ",i);

    }

    return 0;

}


When the value of i becomes 4, 'continue' is encountered then that iteration for which i equals 4 is skipped and it continues with i equals 5. 

Hence, the output of this program is 1 2 3 5


Differences between break and continue statement break statement 


break statement

continue statement

(i) When a break statement is encountered the entire loop or switch statement is terminated

(i) When continue statement is encountered the entire loop is not terminated; only that particular iteration is skipped

(ii) It is used with loop and switch case statements.

(ii) It is used only with loop structure. 


(iii) It uses a keyword break.

(iii) It uses a keyword continue.

(iv) Example:

#include <stdio.h>

int main()

{

    int i;

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

    {

        if(i==4)

        break;

        printf(" %d\t ",i);

    }

    return 0;

}

Output:

1   2   3

(iv) Example:

#include <stdio.h>

int main()

{

    int i;

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

    {

        if(i==4)

        continue;

        printf(" %d\t ",i);

    }

    return 0;

}

Output:

1   2   3    5


goto statement 

When a goto statement is encountered in a program then it transfers the control of the program statements execution unconditionally to the location specified by the goto statement within a current function. 

Syntax 

goto label; 

where the label is an identifier that is used to label the target statement to which the control is transferred. Control may be transferred to anywhere within the current function. The target statement must be labeled, and a colon must follow the label. Thus the target statement will appear as 

label: statement; 

Each labeled statement within the function must have a unique label, that is, no two statements can have the same label. 

Program 24 Write a program to display numbers from 1 to 10 using goto statement.

#include <stdio.h>

int main()

{

    int i=1;

    label1:

    printf(" %d ",i);

    i++;

    if(i<=10)

        goto label1;

    return 0;

}

Assignment 18

  1. Explain break, continue and goto statement with appropriate examples.

  2. Write a program to display the following output:

3 3 3

2 2

1


Worked out Examples


Program 25 Write a program to display the following Fibonacci series:
1 1 2 3 5 ……. To nth terms 

[An integer in the infinite sequence 0,1, 1, 2, 3, 5, 8, 13, … of which the first two terms are 0 and 1 and each succeeding term is the sum of the two immediately preceding is called Fibonacci Series.]

#include<stdio.h>

int main()

{

    int a=1,b=1,c,n,i;

    printf("Enter the value of n");

    scanf("%d",&n);

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

    {

        printf("%d\t",a);

        c=a+b;

        a=b;

        b=c;

    }

    return 0;

}

Program 26 Write a program to calculate and display sum of digits present in the given number.[123=1+2+3=6]

#include<stdio.h>

int main()

{

    int num,sum=0,r;

    printf("Enter the value of num ");

    scanf("%d",&num);

    while(num!=0)

    {

        r=num%10;

        sum=sum+r;

        num=num/10;

    }

    printf("Sum of digits is %d",sum);

    return 0;

}

Program 27 Write a program to check if the given number is palindrome or not. [ If the reverse of the given number is the same as number , then it is said to be palindrome. Example: 121 is palindrome number]

#include<stdio.h>

int main()

{

    int num,sum=0,r,n;

    printf("Enter the value of num ");

    scanf("%d",&num);

    n=num;

    while(num!=0)

    {

        r=num%10;

        sum=sum*10+r;