-->

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;

        num=num/10;

    }

    if(n==sum)

    printf(" %d is Palindrome number",n);

    else

    printf("%d is not palindrome",n);

    return 0;

}


Program 28 Write a program to convert from decimal number system into binary number system.

#include <stdio.h>

int main()

{

    int num,r,i=1,sum=0;

    printf("Enter decimal number ");

    scanf("%d",&num);

    while(num!=0)

    {

        r=num%2;

        sum=sum+r*i;

        num=num/2;

        i=i*10;

    }

    printf(" Binary Equivalent is %d ",sum);

    return 0;

}


Program 29 Write a program to convert the given binary number into equivalent decimal number.

#include <stdio.h>

#include<math.h>

int main()

{

    int num,r,i=0,sum=0;

    printf("Enter Binary number ");

    scanf("%d",&num);

    while(num!=0)

    {

        r=num%10;

        sum=sum+pow(2,i)*r;

        num=num/10;

        i++;

    }

    printf(" Decimal Equivalent is %d",sum);

    return 0;

}

Program 30 Write a program to check whether the given number is prime or composite. [Prime numbers are those whole numbers which have only two factors i.e. one and itself. Example: 19 is prime number because it has only two factors 1 & 19]

#include <stdio.h>

int main()

{

    int num,i,count=0;

    printf("Enter any number ");

    scanf("%d",&num);

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

    {

        if(num%i==0)

        count++;

    }

    if(count==2)

    printf("%d is prime number",num);

    else

    printf("%d is composite number",num);

    return 0;

}

Program 31 Write a program to display all prime numbers from 1 to 100.

#include <stdio.h>

int main()

{

    int num,i,count;

    for(num=1;num<=100;num++)

    {

        count=0;

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

    {

        if(num%i==0)

        count++;

    }

    if(count==2)

    printf(" %d ",num);

    }

    return 0;

}

Exercise 4(E)

  1. What do you mean by control structure? Discuss about its application in programming.

  2. Explain different types of control structure with syntax and flowchart.

  3. Discuss nested loop, infinite loop and loop interruption statement with example.

  4. Differentiate between for loop and while loop.

  5. Differentiate between while loop and do while loop.

  6. Differentiate between break and continue statement.

THE END

Past NEB Board Examination Questions from Array

  1. Define array. Write a program to input any 10 numbers in an array and display it. Find the biggest number among the input numbers. [2+4+4] 2076

  2. Write a program to enter 10 integer numbers in an array and display in ascending order. [10] 2075 GIE

  3. Write a program to input 10 integer numbers into an array and display the sum of the numbers. [10] 2075 Set A

  4. Write a program to enter 5 integer numbers into an array and display. [5] 2075 Set B

  5. Write a program to input any 10 integer numbers in an array and find the total. [10] 2074 Supp.

  6. Write a program to find addition of any two matrix of size 2*2 using array. [10] 2074 Set A

  7. Describe the syntax of array. Write a program to sort ten integer numbers in ascending order. [2+8] 2074 Set B

  8. Write a program to enter elements into 4*4 matrix and find the sum of the elements of the matrix. [5+5] 2073 Supp.

  9. Write a program to read five positive numbers using an array and find out the smallest among them. [10] 2073 Set C

  10. What is array? Write a program to sort twenty integer numbers in ascending order. [2+8] 2073 Set D

  11. Write a program which asks nth terms of numbers and sort them in ascending order. [10] 2072 Set C

  12. What is array? Write a program to find addition of two matrices. (3x3) [2+8] 2072 Set D

  13. What is an array? Write a program to enter 20 integer numbers into an array and display the greatest entered. [3+7] 2072 Set E

  14. Write a program which asks the user to input ‘n’ terms of number and find out the greatest and smallest among those numbers. [10] 2070 Supp.


4.6 Array and Strings

Definition of Array

It may be convenient to store a collection of similar data elements in different separate variables. For example, if the age of 100 persons were to be stored in variables with unique names, it certainly would be difficult, that means 100 variables needed for assigning the individual values. So an array certainly solves this problem because basically the variable name is the same. We differentiate among the values in an array by its unique subscripts with defined size.


POINTS TO REMEMBER 

An array is a collection of similar types of data items treated as a single unit. It acts to store related data under the same name with an index, also known as a subscript which helps to access individual array elements. Array data type may be int, float, char etc, depending upon the nature of problems.

Characteristics of Array 

  • All the array elements share the common name. 

  • The elements of the array are stored in contiguous memory locations. 

  • By declaring or using an array, the program becomes short and simple which handles a large volume of similar kinds of data items. 

  • We put the array size of fixed length as required that means once the size is declared then the size will be fixed at the execution time of the program, so called static type. 

  • We can randomly access to every element using numeric index, index starts from 0 and ends at size-1.


Advantages of Array 

  • It is easier for handling similar types of data in a program. 

  • It is efficient for solving problems like sorting, searching, indexing etc. 

  • It is very close to matrix, therefore it is easy for solving matrix related problems. 

  • Graphic is an array of pixels, so graphics manipulation can be easily done using an array.




Disadvantages of Array 

  • It is not possible to hold a dissimilar type of data in an array. 

  • It is difficult to visualize the multi-dimensional array. 

  • It is static in nature so it is difficult to define the size of array during running time. 

Types of Array 

There are two types of array which are as follows. 

  1. One Dimensional Array: An array which has only one subscript is named as one dimensional array, a subscript is a number of large brackets in which we put the size of the array. 

  2. Multi Dimensional Array: An array which has more than one subscript is named as a multi dimensional array, subscripts define each dimension of the array. 

Declaration of One Dimensional Array: Like any other variable, we have to declare array before they are used. The general form of one dimensional array declaration is,

Syntax: 

Data_type array_name[array_size];

As in above syntax, the data_type refers to the type of array elements, array the name of the array variable and the array size indicates number of elements that can be stored inside the array, Hence if the size of array is n, for example: a[n], a[0] is the first element and a[n-1] is the last element of the array.


Example 1 

int a[5]: 

In this example, the variable a is an array of integer with size five elements.


Example 2 

float weight[100]; 

In this example, the variable weight is an array of floating point numbers having size 100.


Example 3 

char temp[10]; 

In this example, temp variable is an array of characters with size 10 and it is also known as string.


Initialization 

We can initialize arrays at the time of declarations. The initial value must appear which will be assigned to the individual array elements, enclosed within the brace and separated by commas.

Syntax 

data_type array name [size] = {val1, val2, val3,..valn}; 


Here val1 is the value for the first array element, val2 is the value for the second array element, val3 is the value for the three array element and valn is the value for the last array element. 


Example: 

int marks[5]={50, 60, 65, 70, 55}; 

Here the number of subscripts determines the dimension of array ; that is one dimensional array means here is only one subscript. The value in the bracket is the size of the array. marks[0] is the first element of the array where 0 is the starting index of array. 


marks[0]

marks[1]

marks[2]

marks[3]

marks[4]

50

60

65

70

55

index 0

index 1

index 2

index 3

index 4

The values to the array elements can be assigned as follows:

marks[0]=50;

marks[1]=60;

marks[2]=65;

marks[3]=70;

marks[4]=55;


Other Examples:

int a[]={6,7,8,9,10}; //default size is 5

float x[5]={70.5,45.75,85.97,78.87,66.33};

char name[10]={‘n’,‘e’,‘p’,‘a’, ‘l’};


Assignment 19

  1. Define the array with syntax and example.

  2. Write down advantages of array.


Program 32 Write a program to input 5 numbers in an array and display them. [NEB 2075 Set B]

#include <stdio.h>

int main()

{

    int i,num[5];

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

    {

        printf("Enter %d number = ", i+1);

        scanf("%d",&num[i]);

    }

    printf("Array elements are: ");

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

    {

        printf(" %d ",num[i]);

    }

    return 0;

}

Program 33 Write a program to input 5 numbers with constant values initialization in array and display their sum.

#include <stdio.h>

int main()

{

    int i,sum=0;

    int num[5]={100,30,55,60,75};

    printf(" The five numbers of array are: ");

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

    {

        printf(" %d ", num[i]);

        sum=sum+num[i];

    }

    printf("\n Sum of five numbers is : %d ", sum);

    return 0;

}




NEB OLD Questions Answers
QN. 1) Write a program to input 10 integer numbers into an array and display the sum of the numbers. [10] 2075 Set A     OR

Write a program to input any 10 integer numbers in an array and find the total. [10] 

2074 Supp.

Answers:

#include <stdio.h>

int main()

{

    int num[10],i,sum=0;

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

    {

        printf("Enter %d number ",i+1);

        scanf("%d", &num[i]);

    }

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

{

    sum=sum+num[i];

}

printf(" \n The sum is %d ", sum);

    return 0;

}

Program 34 Write a program to input the age of 20 students and count the number of students having age in between 20 to 25.

#include <stdio.h>

int main()

{

    int age[20],i,count=0;

    for(i=0;i<20;i++)

    {

        printf("Student No. %d age ",i+1);

        scanf("%d", &age[i]);

    }

for(i=0;i<20;i++)

{

    if(age[i]>=20 && age[i]<=25)

        count++;

}

printf(" \n The number of students having age in between 20 to 25 is %d ", count);

    return 0;

}

[HSEB 2062-10 Mark] Write an algorithm and C Program to read salaries of 200 employees and count the number of employees getting salaries between 5,000-10,000.

Algorithm:

Step 1: Start

Step 2: Set I =0 and count=0

Step 3: Check is I<200

3.1: If Yes, Input Salary and go to step 4

3.2: If No, goto step 5

Step 4: Calculate I=I+1 and go to step 3

Step 5: Set I =0

Step 6: Check is I<200

6.1: If Yes, Check is salary between 5000 to 10000. If yes increase the value of count by 1, If no, goto step 7

6.2: If No, goto step 5

Step 7: Calculate I=I+1 and go to step 6

Step 8: Display the count

Step 9: Stop

C Program:

#include <stdio.h>

int main()

{

    int salary[200],i,count=0;

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

    {

        printf("Employee no . %d Salary = ", i+1);

        scanf("%d",&salary[i]);

    }

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

    {

        if(salary[i]>=5000 && salary[i]<=10000)

        count++;

    }

    printf("Number of employee getting salary between 5000 to 10000 is %d ", count);

    return 0;

}


[HSEB 2063-10 Mark] Write a C program to read the age of 40 students and count the number of students of the age between 15 to 22.

Answer:
#include <stdio.h>

int main()

{

    int age[40],i,count=0;

    for(i=0;i<40;i++)

    {

        printf("Student No. %d age ",i+1);

        scanf("%d", &age[i]);

    }

for(i=0;i<40;i++)

{

    if(age[i]>=15 && age[i]<=22)

        count++;

}

printf(" \n The number of students having age in between 15 to 22 is %d ", count);

    return 0;

}


[HSEB 2068-10 Mark] Write a C Program to read salaries of 300 employees and count the number of employees getting salaries between 10,000 to 15,000.

Answer:

#include <stdio.h>

int main()

{

    int salary[300],i,count=0;

    for(i=0;i<300;i++)

    {

        printf("Employee No. %d salary ",i+1);

        scanf("%d", &salary[i]);

    }

for(i=0;i<300;i++)

{

    if(salary[i]>=10000 && salary[i]<=15000)

        count++;

}

printf(" \n The number of Employee getting salary between 10000 to 15000 is %d ", count);

    return 0;

}


[HSEB 2070-10 Mark] Write a C Program to read salaries of 25 employees and count the number of employees getting salaries between 30,000 to 40,000.

Answer:

#include <stdio.h>

int main()

{

    int salary[25],i,count=0;

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

    {

        printf("Employee No. %d salary ",i+1);

        scanf("%d", &salary[i]);

    }

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

{

    if(salary[i]>=30000 && salary[i]<=40000)

        count++;

}

printf(" \n The number of Employee getting salary between 30000 to 40000 is %d ", count);

    return 0;

}

[NEB 2076- 2+4+4]  Define array. Write a program to input any 10 numbers in an array and display it. Find the biggest number among the input numbers. 

Answer:

C program to display 10 numbers using array

#include <stdio.h>

int main()

{

    int num[10],i;

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

    {

        printf(" Enter %d number ", i+1);

        scanf("%d", &num[i]);

    }

    printf("Entered ten numbers are : \n ");

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

    {

        printf(" %d ",num[i]);

    }


    return 0;

}


Also,biggest number among ten numbers

#include <stdio.h>

int main()

{

    int num[10],i,big;

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

    {

        printf(" Enter %d number ", i+1);

        scanf("%d", &num[i]);

    }

        big=num[0];

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

    {

        if(num[i]>big)

        big=num[i];

    }

    printf("Biggest number is %d ",big);

    return 0;

}


[NEB 2073- 10 Marks] Write a C program to read five positive numbers using an array and find out the smallest among them.

Answer:

#include <stdio.h>

int main()

{

    int num[5],i,smallest;

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

    {

        printf("Enter %d number ", i+1);

        scanf("%d", &num[i]);

    }

    smallest=num[0];

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

    {

        if(num[i]<smallest)

        smallest=num[i];

    }

    printf("smallest number is %d ", smallest);

    return 0;

}



Program 35 Write a program to find the largest number among ‘n’ numbers.

#include <stdio.h>

int main()

{

    int num[100],i,n,largest;

    printf("Enter the size of array not more than 100 ");

    scanf("%d",&n);

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

    {

        printf(" Enter %d number ", i+1);

        scanf("%d", &num[i]);

    }

        largest=num[0];

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

    {

        if(num[i]>largest)

       largest=num[i];

    }

    printf("Largest number is %d ",largest);

    return 0;

}





Program 36 Write a program to input ‘n’ numbers and search whether it is in the list or not.

#include <stdio.h>

int main()

{

    int n,num[100],i,searchnum;

    printf(" Enter the size of array not more than 100 ");

    scanf("%d",&n);

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

    {

        printf("Enter %d number ", i+1);

        scanf("%d", &num[i]);

    }

   printf("Enter a number to be searched ");

   scanf("%d",&searchnum);

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

    {

        if(searchnum==num[i])

       {

           printf("%d is in the list", searchnum);

           break;

       }

    }

    if(n==i)

    printf(" %d is not in the list", searchnum);

    return 0;

}




[NEB 2074 , 2077 - 10 Marks] Define array. Describe the syntax of array. Write a program to sort ten integer numbers in ascending order. 

Answer:

Syntax of Array:

Data_type Array_name [Array-size];


C Program

#include <stdio.h>

int main()

{

    int num[10],i,j,temp;

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

    {

        printf("Enter %d numebr ",i+1);

        scanf("%d", &num[i]);

    }

    for(i=0;i<9;i++)

    {

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

        {

            if(num[i]>num[j])

                {

                    temp=num[i];

                    num[i]=num[j];

                    num[j]=temp;

                }

        }

    }

    printf(" Array in Ascending Order \n");

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

    {

        printf(" %d ", num[i]);

    }

    return 0;

}










Ten integers in Descending order:

#include <stdio.h>

int main()

{

    int num[10],i,j,temp;

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

    {

    printf("Enter %d number ", i+1);

    scanf("%d",&num[i]);

    }

    for(i=0;i<9;i++)

    {

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

        {

            if(num[i]<num[j])

            {

                temp=num[i];

                num[i]=num[j];

                num[j]=temp;

            }

        }

    }

    printf("Ten integers in Descending order\n");

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

    {

        printf(" %d ",num[i]);

    }

    return 0;

}



Program 37 Write a program to input ‘n’ numbers and sort them in ascending order.

#include <stdio.h>

int main()

{

    int n,num[100],i,j,temp;

    printf("Enter the size of array not more than 100\n ");

    scanf("%d",&n);

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

    {

    printf("Enter %d number ", i+1);

    scanf("%d",&num[i]);

    }

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

    {

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

        {

            if(num[i]>num[j])

            {

                temp=num[i];

                num[i]=num[j];

                num[j]=temp;

            }

        }

    }

    printf("Numbers in Ascending order\n");

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

    {

        printf(" %d ",num[i]);

    }

    return 0;

}




Assignment 20

  1. Write a program to find the smallest number among 10 numbers.

  2. Write a program to input 10 numbers and sort them in descending order.

Multi Dimensional Array

Multi dimensional arrays are defined the same as one-dimensional arrays, except that it consists of more than one pair of square brackets that are subscripts. Thus a two dimensional array will require two square brackets, one for row size and other for column size. The  maximum capacity of elements of an array is the product of row size and column size. A three dimensional array will require three square brackets, and so on.


In general terms, a multidimensional array definition can be written as

data_type array_name [expression1] [expression2]..... [expression n]; 


In two dimensional array declaration we write,

data_type array_name [row_size] [column_size]; 


As in above syntax, the data_type refers to the type of array elements, array_name is the name of the array variable and row_size, column_size are the number of array elements associated with each subscript that can be stored inside the array.

For example, a[m][n] is a 2 dimensional array in which the starting element of array is a[0][0] and the last element of array is a[m-1][n-1]. Here, in a[m][n], m denotes the row size and n denotes the column size in array.


Initialization

If we have m*n array, it will have m*n elements and will require m*n element size bytes of storage. To allocate storage for an array you must reserve this amount of memory. The elements of a two dimensional array are stored row wise.

In two dimensional array (suppose 3x3 matrix), data items are stored in memory below: 


Column 0

[0][0]

Column 1

[0][1]

Column 2

[0][2]

Row 0

100

200

300


[1][0]

[1][1]

[1][2]

Row 1

200

150

50


[2][0]

[2][1]

[2][2]

Row 2

350

500

600

As in above example, two dimensional array consist of 3 rows and 3 columns, the starting array element is 100 that is stored in position matrix[0][0] and the last array element is 600 that is stored in position matrix[2][2]. 

This means, 

int matrix[3][3]={100, 200, 300, 200, 150, 50, 350, 500, 600}; 

matrix[0][0]= 100; 

matrix[0][1]= 200; 

matrix[0][2]= 300;

matrix[1][0]= 200;

matrix[1][1]= 150;

matrix[1][2]= 50;

matrix[2][0]= 350;

matrix[2][1]= 500;

matrix[2][2]= 600;


Program 38 Write a program to store 9 numbers with constant values in 2 dimensional array that is 3x3 matrix and print in matrix form.

#include <stdio.h>

int main()

{

    int matrix[3][3]={1,2,3,4,5,6,7,8,9},i,j;

    printf("The given matrix is \n");

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

    {

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

        {

            printf("%3d",matrix[i][j]);

        }

        printf("\n");

    }

    return 0;

}






Worked out Examples

Program 39 Write a program to input data in two dimensional array for example 3x3 matrix and display in matrix form.

#include <stdio.h>

int main()

{

    int matrix[3][3],i,j;

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

    {

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

        {

    printf("Enter [%d][%d] elements" , i+1,j+1);

            scanf("%d",&matrix[i][j]);

        }

    }

    printf("The given matrix is \n");

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

    {

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

        {

            printf("%3d",matrix[i][j]);

        }

        printf("\n");

    }

    return 0;

}

Program 40 Write a program to input a 2x3 matrix and display in transpose form that is 3x2 matrix.

#include <stdio.h>

int main()

{

    int matrix[2][3],i,j;

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

    {

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

        {

            printf("Enter [%d][%d] elements" , i+1,j+1);

            scanf("%d",&matrix[i][j]);

        }

    }

    printf("The transpose of given matrix is \n");

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

    {

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

        {

            printf("%3d",matrix[j][i]);

        }

        printf("\n");

    }

    return 0;

}


[NEB Question - 2074  ]Write a program to find addition of any two matrix of size 2*2 using array. [10]

#include <stdio.h>

int main()

{

    int m1[2][2],m2[2][2],m3[2][2],i,j;

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

    {

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

        {

            printf("Enter [%d][%d] elements of First Matrix " , i+1,j+1);

            scanf("%d",&m1[i][j]);

        }

    }

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

    {

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

        {

            printf("Enter [%d][%d] elements of Second Matrix " , i+1,j+1);

            scanf("%d",&m2[i][j]);

        }

    }

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

    {

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

        {

           m3[i][j]=m1[i][j]+m2[i][j];

        }

    }

    printf("Sum of given matrix is \n");

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

    {

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

        {

            printf("%d\t",m3[i][j]);

        }

        printf("\n");

    }

    return 0;

}


[NEB Question  2073 Supp ]Write a program to enter elements into 4*4 matrix and find the sum of the elements of the matrix. [5+5] 

#include <stdio.h>

int main()

{

    int m1[4][4],m2[4][4],m3[4][4],i,j;

    for(i=0;i<4;i++)

    {

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

        {

            printf("Enter [%d][%d] element of First matrix ",i+1,j+1);

            scanf("%d",&m1[i][j]);

        }

    }

      for(i=0;i<4;i++)

    {

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

        {

            printf("Enter [%d][%d] element of Second matrix ",i+1,j+1);

            scanf("%d",&m2[i][j]);

        }

    }


  for(i=0;i<4;i++)

    {

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

        {

           m3[i][j]=m1[i][j]+m2[i][j];

        }

    }

    printf("Sum of two 4*4 matrices is \n");

      for(i=0;i<4;i++)

    {

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

        {

                printf(" %3d ",m3[i][j]);

        }

        printf("\n");

    }

    return 0;

}





Program 41 Write a program to input two matrices. Add two matrices and display in proper format.

#include <stdio.h>

int main()

{

    int m1[5][5],m2[5][5],m3[5][5],i,j,r,c;

    printf("Enter the row and column size");

    scanf("%d%d",&r,&c);

    for(i=0;i<r;i++)

    {

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

        {

            printf("Enter [%d][%d] element of First matrix ",i+1,j+1);

            scanf("%d",&m1[i][j]);

        }

    }

      for(i=0;i<r;i++)

    {

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

        {

printf("Enter [%d][%d] element of Second matrix ",i+1,j+1);

            scanf("%d",&m2[i][j]);

        }

    }

  for(i=0;i<r;i++)

    {

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

        {

           m3[i][j]=m1[i][j]+m2[i][j];

        }

    }

  printf("Sum of two %d*%d matrices is \n",r,c);

      for(i=0;i<r;i++)

    {

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

        {

                printf(" %3d ",m3[i][j]);

        }

        printf("\n");

    }

    return 0;

}


Differentiate between one dimensional and two dimensional array:

One Dimensional Array

Two Dimensional Array

It consists of only one subscript.

It consists of two subscripts.

Maximum size will be the size of the array which we define in the program.

Maximum size will be the product of row and column size of array which we define in the program.

It stores data either row wise or column wise.

It stores data in matrix form that is row wise and column wise.

Syntax:

Data_type array_name[array_size];

Syntax:

Data_type array_name[row_size][column_size];

Example: 

int num[5];

Example: 

int matrix[2][2];

Program:

#include <stdio.h>

int main()

{

    int num[4]={1,2,3,4},i;

    for(i=0;i<4;i++)

    {

            printf("%3d",num[i]);

    }

        return 0;

}


Program:

#include <stdio.h>

int main()

{

    int matrix[2][2]={1,2,3,4},i,j;

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

    {

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

        {

            printf("%3d",matrix[i][j]);

        }

        printf("\n");

    }

        return 0;

}



Assignment 21

  1. Compare one dimensional array and two dimensional array.

  2. Write a program to transpose a given matrix with size 2x2.

  3. Write a program to subtract two 2x2 matrices.


String (Important Question)

NEB PAST QUESTIONS

  1. Explain the function with an example. Write a program to demonstrate any two string function using C. [2+5.5] 2077 Mangsir 10

  2. Explain any two string functions with examples.[5] 2076

  3. What is function? Explain any four string functions with example.[2+8] 2075 “A”

Answer:
A self contained block of code that performs a specific task is called function. In C programming, there are two types of function.

(i) User Defined Function

(ii) Library Function

Components of function:

  • Function Prototype or Declaration

  • Function Definition

  • Function Call

  1. What is string? Explain any four string function with an example. [2+8] 2074

  2. Describe the string manipulation function in C. Explain strcpy and strcmp with example. [2+3] 2073

  3. Describe any five “string handling functions “ with examples. [10] 2070

*********

Definition of String: 

String is the set of characters,digits and symbols. We can also define string as the array of characters. The end of the string is marked with a special character , the ‘\0’ that means Null character. The size in a character string represents the maximum number of characters that the string can hold.


POINTS TO REMEMBER 

A string is an array of characters. It contains characters, symbols, numbers etc.


Syntax:

char string_name[string_size];


As in above syntax, char refers to the character data type that will be stored in the array, string_name is the name of the string variable and string_size indicates the number of characters that can be stored inside the array.


Example 

char name[10];

char address[10];

This declares the name as a character array (string) variable that can hold a maximum of 10 characters. 

String is simply a sequence of characters, so to declare a string, we have to put data type char with string name with square brackets. 

Initialization of Strings 

Let us take a string: 

char name[10]={‘c’, ‘  ’, ‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘\0’}; 

or second method 

char name[10]= “c program” ;

Each character is treated as an element of the array name and is stored in the memory as follows: 

name[0]

name[1]

name[2]

name[3]

name[4]

name[5]

name[6]

name[7]

name[8]

name[9]

‘c’

‘ ’

‘p’

‘r’

‘o’

‘g’

‘r’

‘a’

‘m’

‘\0’

Index 0

Index 1

Index 2

Index 3

Index 4

Index 5

Index 6

Index 7

Index 8

Index 9

When the compiler sees a character string, it terminates it with an additional null character means empty. Thus, the element name[9] holds the null character ‘\0’ at the end. When declaring a character array, we must always allow one extra element space for the null terminator.


Program 42 Write a program to input character wise in array and display them.

#include <stdio.h>

int main()

{

char name[10]={'c','','p','r','o','g','r','a','m','\0'};

    printf("The given string is : %s",name);

    return 0;

}


Program 43 Write a program to input string in array and display them.

#include <stdio.h>

int main()

{

    char name[10]="c program";

    printf("The given string is : %s",name);


    return 0;

}


Assignment 22

  1. What do you mean by the term string? Explain it with syntax and example.

  2. Differentiate between array and string with suitable examples.



Array of String 

A two dimensional array of characters is called an array of strings. It is also known as a table of strings. It is very useful for solving string sorting problems. In other words, an array of strings can be declared and handled like a two dimensional array. 

Syntax:

char string_name[MAX][SIZE]: 

As in above syntax, char refers to character data type, string_name is the name of the string variable and in two dimensional array, [MAX] indicates the number of strings and [SIZE] indicates the maximum number characters associated with string.

Example 

char name[5][10];

In this example, here is a two dimensional character array. The array is initialized with five character strings with maximum size ten.


Program to demonstrate table of strings 

#include <stdio.h>

int main()

{

    int i;

    char name[5][30]={"Dipendra","Manisha","Suyog","Ram","Laxman"};

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

    {

    printf("%s\n",name[i]);

    }

    return 0;

}


 

String Handling Functions 

The C library supports a large number of string handling functions that can be used to carry out many of the string manipulation. The header file #include<string.h> is used for string manipulation functions. Some of the common string manipulation functions are:

 

  1. strlen() function 

The strlen() function returns the length of a string which takes the string name as an argument.

Syntax:

l=strlen(str); 

where, str is the name of string and l is the length of the string, returned by function. 



Program 44 Write a program to find the length of a string. 

#include <stdio.h>

#include <string.h>

int main()

{

    char str[100];

    int l;

    printf("Enter any string = ");

    scanf("%s",str);

    l=strlen(str);

    printf("Length of string is %d ", l);

    return 0;

}


  1. strrev() function 

The strrev() function is used to reverse the given string. 


Syntax: 

strrev(str); 

where str is string to be reversed. 


Program 45 Write a program to reverse the given string.

#include <stdio.h>

#include<string.h>

int main()

{

    char str[100];

    printf("Enter any string = ");

    scanf("%s",str);

    strrev(str);

    printf("Reverse of string is %s ",str);

    return 0;

}




  1. strcpy() function 

The strcpy() function is used to copy one string into another string. 

Syntax: 

strcpy(destination,source)    or 

strcpy(strl,str2); 

where strl,str2 are two strings. 

The content of string str2 is copied on string strl.



Program 46 Write a program to copy one string into another string.

#include <stdio.h>

#include<string.h>

int main()

{

    char str1[100],str2[100];

    printf("Enter any string = ");

    scanf("%s",str1);

    strcpy(str2,str1);

    printf("After copying the string is %s ", str2);

    return 0;

}

  1. strcat() function 

The strcat() function is used to join or concatenate one string into another string. 


Syntax:

strcat(strl,str2); 

where str1,str2 are two strings. The content of string str2 is concatenated with string str1. 


Program 47 Write a program to concatenate two strings into one string.

#include <stdio.h>

#include<string.h>

int main()

{

    char str1[100],str2[100];

    printf("Enter two strings = ");

    scanf("%s%s",str1,str2);

    strcat(str1,str2);

    printf("After copying the string is %s ", str1);

    return 0;

}

  1. strcmp( ) function 

The strcmp() function is used to compare two strings, character by character and stops comparison when there is a difference in the ASCII value or the end of any one string and returns ASCII difference of the character that is  integer. 


Syntax: 

v=strcmp(strl,str2); 

Where, str1 and str2 are two strings to be compared and v is a value returned by the function which is either zero(equal), positive value(descending)  or negative value(ascending).


Program 48 Write a program to compare two strings 

#include <stdio.h>

#include<string.h>

int main()

{

    char str1[50],str2[50];

    printf("Enter two strings : ");

    scanf("%s%s",str1,str2);

    int v=strcmp(str1,str2);

    if(v==0)

        printf("Both strings are same and have same ASCII value");

    else if(v>0)

        printf("%s comes after  %s or %s has more ASCII value than %s",str1,str2,str1,str2);

    else

    printf("%s comes before %s or %s has more ASCII value than %s",str2,str1,str2,str1);

    return 0;

}


  1. strlwr() function 

The strlwr() function is used to convert upper case characters of string into lower case characters.

Syntax:

strlwr (str); 

where str is string to be converted into lower case characters. 


Program 49 Write a program to convert the given string into lower case.

#include <stdio.h>

#include<string.h>

int main()

{

    char str[50];

    printf("Enter a string : ");

    scanf("%s",str);

    strlwr(str);

    printf("Given string in lower case is %s ",str);

    return 0;

}


  1. strupr() function

The strupr() function is used to convert lower case characters of string into upper case characters. 

Syntax: 

strupr (str); 

where str is string to be converted into upper case characters.



Program 50 Write a program to input string in array and display them.

#include <stdio.h>

#include<string.h>

int main()

{

    char str[50];

    printf("Enter a string : ");

    scanf("%s",str);

    strupr(str);

    printf("Given string in upper case is %s ",str);

    return 0;

}


Assignment 23 

  1. Define array of strings. 

  2. List five string handling functions with respective syntax. 


Worked Out Examples 

Program 51 Write a program to find the length of the given string without using built in function. 

#include <stdio.h>

#include<string.h>

int main()

{

    char str[50];

    int i,length=0;

    printf("Enter a string : ");

    scanf("%s",str);

 for(i=0;str[i]!='\0';i++)// no body so use semicolon

{

    length++;

}

    printf("Length of string is %d",length);

    return 0;

}


Program 52 Write a program to input strings and sort them. 

#include<stdio.h>

#include<string.h>

int main()

{

    char string[100][100],temp[100];

    int i,j,n;

    printf("enter n as total strings\n");

    scanf("%d",&n);

    printf("enter strings\n");

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

    {

        printf(" string for location %d = ",i);

        scanf("%s",string[i]);

    }

    

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

    {

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

        {

            if(strcmp(string[i],string[j])>0)

            {

                strcpy(temp,string[i]);

                strcpy(string[i],string[j]);

                strcpy(string[j],temp);

            }

        }

    }

   printf("sorted strings are\n");

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

    {

        printf("name =%s \n",string[i]);

    }

     return 0;

}



Exercise 4(F)

  1. Define the term array. 

  2. Differentiate between one dimensional and two dimensional array. 

  3. Write down the importance of an array. 

  4. What is string? Explain any four string handling function with an example. 

  5. What do you mean by string manipulation? Explain about “strcpy()” and “strcat()”.

The End

4.7 Functions 

Definition: A self –contained block of code that performs a particular task is called Function.

 Advantages of functions:

1.   It facilitates top down modular programming.

2.   The length of a source program can be reduced by using functions at appropriate places.

3.  It is easy to locate and isolate a faulty function for further investigations.

4.  A function may be used by many other programs.

 A function has 3 elements.

1. Function Declaration (Function Prototype)

2. Function Call

3. Function Definition

 1. Function Declaration (Function Prototype)

A function declaration also known as Function Prototype consists of four parts:

  • Function type(return type)

  • Function name

  • Parameter list

  • Terminating Semicolon

Syntax:

Function_type Function_name(Formal Parameter list);

Example:

int sum(int a, int b);

or

int sum(int, int);

Points to note:

1.       The parameter list must be separated by commas.

2.       The parameter names do not need to be the same in the prototype declaration and the function definition.

3.      The types must match the types of parameters in the function definition, in number and order.

4.      Use of parameter names in the declaration is optional.

 

Function Parameter:

The parameters used in function declaration and function definition are called formal parameter and those used in function call is called actual  parameter.

The formal and actual parameters must match exactly in type, order and number. Their names, however, do not need to match.

 

Examples: sum=add (a, b, c); // here a, b, c are called actual parameter.

         int add(int x , int y, int z); // here x, y, z are formal parameter.

 

Function Return: Function can be organized into 2 types.

a) Function that has not a return value i.e. void function.

b) Function that has a returned value i.e. int function.

 

2. Function Call

A function can be called by simply using the function name followed by a list of actual parameters, if any, enclosed in parenthesis.

Static variables are created and initialized once, on the first call to the function. Subsequent calls to the function do not recreate or re-initialize the static variable.

Example:

c=sum (a,b);

3. Function Definition

The function definition is an independent program module that is specially written to implement the requirement of the function.


A function definition, also known as function implementation shall include the following elements.

a)     Function type

b)     Function Name

c)      List of parameters

d)     Local variable declarations

e)     Function statements

f)       A return statement

 

All the six elements are grouped into two parts, namely,

·         Function Header(First three elements)

·         Function Body ( Second three elements)

Syntax:

Function_type Function_Name(Formal Parameter list)

{

Local variable declaration;

Executable statement 1;

Executable statement 2;

………………….

………………….

return statement;

}

Note that a semicolon is not used at the end of the Function Header of Function definition.

Difference between Local Variable and Global variable [HSEB2068]

 

Local Variable

Global Variable

1. Any variable declare within the specific function is called Local Variable.

1. Any variable which is declared outside all the function is called Global Variable.

2. Visibility: Visible inside the corresponding function only.

2. Visibility: Visible throughout program.

3. Accessible: Accessible to instruction of corresponding function.

3. Accessible: Accessible to all the instruction to specified program.

4. Life span: Created when control is transferred from calling to called function and destroyed when control returned to calling function.

4. Life span: Life of program or until the program run.

5. Duplicate is allowed.

5. Global variable name should be unique.

Difference between Library and User-defined Function [HSEB 2067]                                        

 

Library Function

User –defined Function

1. It is already defined functions.

1. It is defined by the programmers as their need.

2. It needs header file to use the functions.

2. It requires the function declaration to use the functions.

3. We can’t modify the library functions.

3.  We can modify the user –defined functions.

4.  It is called at run time.

4. It is called at compile time.

5.  Example:

   printf( );

   scanf ( ); etc.

5. Example:

sum( );

  max( );   etc.

 

1.      WAP to find the sum of two numbers using function?[HSEB 2072-E,2073-D]

#include<stdio.h>

#include<conio.h>

int sum (int x, int y);

void main( )

{

int a,b,c;

printf("Enter any two numbers=");

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

c=sum (a,b);

printf("The sum of two numbers=%d",c);

getch( );

}

 

int sum (int x, int y)

{

int p;

p=x+y;

return p;

}


4.8 Structures and Unions

4.8.1

4.9 Pointers

jhdsbfjhdsbf

4.10 Working with Files

dkldfjgefjgk


source/references: computer science-II,buddha publication

No comments:

Post a Comment