1. programming in ‘c’

161
1. Programming in ‘C PROGRAM DEVELOPMENT TOOLS 1.1 Algorithm Algorithm is a method of representing the step-by-step logical procedure for solving a problem. According to D.E. Knuth, a pioneer in the computer science discipline, an algorithm must possess the following properties (i) Fitness: An algorithm must terminate in a finite number of steps (ii) Definiteness: Each step of the algorithm must be precisely and unambiguously stated. (iii) Effectiveness: Each step must be effective, in the same that it should be primitive (easily converted into program statement) and can be performed exactly in a finite amount of time. (iv) Generality: The algorithm must be complete in itself so that it can be used to solve all problems of a specific type for any input data. (v) Input / Output: Each algorithm must take zero, one or more quantities an input data and produce one or more output values. An algorithm can be written in English like sentences or in any standard representation. Sometimes, algorithm written in English like language is called Pseudo Code. MILLENNIUM SOFTWARE SOLUTIONSVisakhapatnam

Upload: kalpana-nagle

Post on 18-Nov-2014

3.139 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: 1. Programming in ‘C’

1. Programming in ‘C’

PROGRAM DEVELOPMENT TOOLS

1.1 Algorithm

Algorithm is a method of representing the step-by-step logical procedure for

solving a problem. According to D.E. Knuth, a pioneer in the computer science

discipline, an algorithm must possess the following properties

(i) Fitness: An algorithm must terminate in a finite number of steps

(ii) Definiteness: Each step of the algorithm must be precisely and

unambiguously stated.

(iii) Effectiveness: Each step must be effective, in the same that it should be primitive (easily converted into program statement) and can be performed exactly in a finite amount of time.

(iv) Generality: The algorithm must be complete in itself so that it can be used to solve all problems of a specific type for any input data.

(v) Input / Output: Each algorithm must take zero, one or more quantities an input data and produce one or more output values.

An algorithm can be written in English like sentences or in any standard

representation. Sometimes, algorithm written in English like language is called Pseudo

Code.

Example: Suppose we want to find the average of three numbers

Step 1. Read the numbers a, b, c

Step 2. Compute the sum of a, b and c

Step 3. Divide the sum by 3

Step 4. Store the result in variable d

Step 5. Print the value of d

Step 6. End of the program

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 2: 1. Programming in ‘C’

Formally, an algorithm can be defined as an ordered sequence of well-defined

and effective operations that, when executed, will always produce a result and

eventually terminate in a finite amount of time.

1.2 Flowchart

Flowchart is diagrammatic representation of an algorithm. It is constructed

using different types of boxes and symbols. Arrows among themselves to indicate the

flow of information and processing connect all symbols.

Following are the Standard symbols used in drawing flowcharts.

Oval Terminal

Parallelogram Input/ output

Document Printout

Rectangle Process

Diamond Decision

Circle Connector

Arrow Flow

Double sidedRectangle

PredefinedProcess

Important Points in drawing flowcharts

1. Flowchart should be clear, neat and easy to follow

2. Flowchart should be logically correct

3. Flowchart should be verified for its validity with some test data

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 3: 1. Programming in ‘C’

Limitations of flowcharts

1. Flowcharts are difficult to modify. Re-drawing of flowchart may be necessary

2. Translation of flowchart into computer program is always not easy

Advantages of flowcharts

1. Logic of program is clearly represented

2. It is easy to follow logically the flow chart

Example: Find out the average of n numbers.

True

False

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Start

Read N

Count = 0Sum = 0Avg = 0

Sum = Sum + aCount = Count+1

Count<=n

?

Avg = sum / n

Print avg.

Stop

Page 4: 1. Programming in ‘C’

1.3 Introduction

C is a programming language developed at AT & T Bell Laboratories of USA in

1972. It was designed and written by “Dennis Ritchie”. C is a powerful general purpose

and most popular computer programming language. C is highly portable i.e., software

written for one computer can be run on another computer. C language is well suited for

structured programming. An important feature of ‘C’ is its ability to extend itself. A C

program is basically a collection of functions.

Historical Development of C

Year

Language Developed by Remarks

1960 ALGOL International Committee Too general, too abstract

1963 CPL Cambridge University Hard to learn, difficult to implement

1967 BCPLMartin Richards at Cambridge University

Could deal with only specific problems

1970 B Ken Thomson at AT & T Could deal with only specific problems

1972 C Dennis Ritchie at AT & T Lost generality of BCPL and B restored

ALGOL Algorithmic Language

CPL Combined Programming Language

BCPL Basic Combined Programming Language

1.4 Where C Stands

All programming languages can be divided into two categories:

(a) Problem oriented languages or High-level languages:

These languages have been designed to give a better programming efficiency, i.e.,

faster program development.

Ex: FORTRAN, BASIC, PASCAL, etc.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 5: 1. Programming in ‘C’

(b) Machine oriented languages or Low-level languages:

These languages have been designed to give a better machine efficiency, i.e., faster

program execution.

Ex: Assembly Language and Machine Language.

C stands in between these two categories. That’s why it is often called a “Middle Level

language”, since it was designed to have both: a relatively good programming efficiency

and relatively good machine efficiency.

1.5 C Tokens

A token is an atomic unit (smallest indivisible units) in a program.

The most basic elements in a C program recognized by the compiler are a single

character or a group of characters called C tokens.

The compiler cannot breakdown the token any further. For example, the words

main, ‘{‘ (brace), ‘(‘ (parenthesis) are all tokens of C program.

C language has 6 types of tokens.

1. Keywords

Examples: float, int, double, while, for

2. Identifiers

Examples: main, amount

3. Constants

Examples: 12.4, 7894

4. Strings

Examples: “CSM”, “Thursday”

5. Special Symbols

Examples: [,], {, }, (, )

6. Operators

Examples: +, *, /

Steps in learning C language are …

1. Character Set – Alphabets, Digits and Special Symbols

2. Datatypes, Constants, Variables and Keywords

3. Instructions

4. Functions, Program

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 6: 1. Programming in ‘C’

In C, the alphabet is a set of characters. The words correspond to constants,

variables, keywords, etc. These are classified into different datatypes. Further, these are

combined with operators to form expressions, of various types. These are in turn

combined to form instructions. Combining a group of instructions into functions makes a

program.

1.6 The C character set

The C character set includes the upper case letters A to Z, the lower case a to z,

the decimal digits 0 to 9 and certain special characters/symbols. The character set is

given below.

Alphabets A, B, C, …………Za, b, c, ……………z

Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special characters/Symbols ~ , . ; : ? ‘ “ ! ( ) [ ] { } / \ < > = + - $ # @ & * % ^

Character/Symbol Meaning Character/Symbol Meaning~.?“([{/<=-#&%_

TildePeriodQuestion MarkDouble QuoteLeft ParenthesisLeft BracketLeft BraceSlashLess thanEqual toMinusHashAmpersandPercentUnderscoreBlank Space

,;:‘)]}\>!+$*^|

CommaSemicolonColonApostrophe (single quote)Right ParenthesisRight BracketRight BraceBack SlashGreater thanExclamatory MarkPlusDolor SignAsterisk (or star)CaratVertical Bar

1.7 Identifiers

Identifiers are distinct names given to program elements such as constants, variables, etc.

An Identifier is a sequence of letters, digits, and the special character ‘_’ (underscore).

(i) It must start with either a letter or underscore. ‘_’

(ii) No commas or blanks are allowed within a variable name.

(iii) The upper case and lower case letters are treated as distinct, i.e.,

identifiers are case-sensitive.

(iv) An identifier can be of any length.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 7: 1. Programming in ‘C’

(v) No special symbol can be used in a variable name.

The following are valid identifiers.

i, income_tax, _pass, n10xy

The following are invalid identifiers.

2module, first program, -pass

1.8 Keywords

Keywords are predefined tokens in C. These are also called reserved words. Key

words have special meaning to the C compiler. These key words can be used only for

their intended action; they cannot be used for any other purpose. C has 32 keywords.

The standard keywords are

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed sizeof static struct

switch typedef union unsigned void

volatile while

Note that all these keywords are in lowercase.

1.9 Datatypes

A datatype defines a set of values and the operations that can be performed on

them. Every datatype item (constant, variable etc.) in a C program has a datatype

associated with it. C also has a special datatype called void, which, indicates that any data

type, i.e., no data type, does not describe the data items.

The following are the basic datatypes along with their size and range

Datatypes Description Size (No. of Bytes) Range

Char Single character 1 0 to 255Int An integer 2 -32768 to +32767Float Floating point number 4 -2,147,483,648 to

+2,147,483,647double Floating point number 8 Approximately 15 digits of

PrecisionVoid No datatype 0signed char Character 1 -128 to 127unsigned char Unsigned character 1 0 to 255short signed int Short signed integer 2 -32768 to +32767short unsigned int Short unsigned integer 3 0 to 65535Long singed int Long signed integer 4 -2,147,483,648 to

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 8: 1. Programming in ‘C’

+2,147,483,647

Generally, the following rule is true for any compiler to specify the size of data types:

sizeof(char) <= sizeof(short int) <= sizeof(int) <= sizeof(long int) <= sizeof(float) <= sizeof(double)

There are some other datatypes in C that can be derived from the basic datatypes.

The basic datatypes are often called Primary datatypes and the derived datatypes are

often called Secondary datatypes.

C Datatypes

Basic datatypes Derived datatypes

char integer float double void array structure union pointer

1.10 Constants and Variables

A constant is a literal, which remain unchanged during the execution of a

program. A variable is a name that is used to store data value and is allowed to vary the

value during the program execution.

Constants

A constant is a fixed value that cannot be altered during the execution of a

program. C constants can be classified into two categories.

(i) Primary Constants

(ii) Secondary Constants

Constants

Primary constants Secondary constants

Numeric Character Logical Array Structure Union Pointer

integer float Single char String

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 9: 1. Programming in ‘C’

C has five types of primary constants. They are integer, float, char, logical and

string. The numeric constants can be preceded by a minus sign if needed.

Rules for constructing Integer constants

(a) An integer constant must have at least one digit.

(b) It should not contain either a decimal point or exponent.

(c) If a constant is positive, it may or may not be preceded by a plus sign. If it is a negative, it must be preceded by a minus sign.

(d) Commas, blanks and non-digit characters are not allowed in integer constants.

(e) The value of integer constant cannot exceed specified limits. The valid range is –32768 to +32767.

Rules for constructing Real constants

Real values are often called floating-point constants. There are two ways to

represent a real constant decimal form and exponential form.

In exponential form of representation, the real constant is represented in two parts.

The part appearing before ‘e’ is called mantissa, whereas the part following ‘e’ is called

exponent.

(a) The mantissa part and the exponential part should be separated by a letter e.

(b) The mantissa part may have a positive or negative sign.

(c) Default sign of mantissa part is positive.

(d) The exponent must have at least one digit, which must be a positive or negative integer. Default sign is positive.

(e) Range of real constants expressed in exponential form is –3.4e38 to 3.4e38.

Rules for constructing Characters constants

(a) A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas. Both the inverted commas point to the left. For example, ‘A’ is valid character constant whereas A is not.

(b) The maximum length of a character constant can be 1 character.

Note: Every character has its ASCII (American Standard Code for Information Interchange)

value. That means every character is interchange with integer constant. For example,

‘A’ value is 65 and ‘a’ value is 97.

String constants

A string constant is a sequence of characters enclosed in double quotes. The

characters may be letters, numbers, blank space or special characters.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 10: 1. Programming in ‘C’

Note that “” is null string or empty string. And the single string constant “A” is

not equivalent to the single character constant ‘A’.

Each string constant must end with a special character ‘\0’. This character is

called null character and used to terminate the string. The compiler automatically places

a null ‘\0’ character at the end of every string constant.

Escape sequence

Some non-printing characters and some other characters such as double quote (“),

single quote (‘), question mark (?) and backslash (\), require an escape sequence. A list of

commonly used backslash character constants is given below.

Escape Sequence

Meaning ASCII valueEscape

SequenceMeaning ASCII value

\a

\b

\t

\n

\v

\f

Bell

Back Space

Tab

New line

Vertical tab

Form feed

7

8

9

10

11

12

\r

\”

\’

\?

\\

\0

Carriage return

Double Quote

Single Quote

Question Mark

Back Slash

Null

13

34

39

63

92

0

Variables

A variable can be considered as a name given to the location in memory. The

term variable is used to denote any value that is referred to a name instead of explicit

value. A variable is able to hold different values during execution of a program, where as

a constant is restricted to just one value.

For example, in the equation 2x + 3y = 10; since x and y can change, they are

variables, whereas 2,3 and 10 cannot change, hence they are constants. The total

equation is known as expression.

Rules for constructing variable names

(a) The name of a variable is composed of one to several characters, the first of which must be a letter

(b) No special characters other than letters, digits, and underscore can be used in variable name. Some compilers permit underscore as the first character.

(c) Commas or Blanks are not allowed with in a variable name.

(d) Upper case and Lower case letters are significant. That is the variable income is not same as INCOME.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 11: 1. Programming in ‘C’

(e) The variable name should not be a C key word. Also it should not have the same name as a function that is written either by user or already exist in the C library.

The following are valid variable names:Alphaincomexfyear_9899matrix

1.11 C Instructions

There are basically four types of instructions in C:

(a) Type Declaration Instruction

(b) Input/Output Instruction

(c) Arithmetic Instruction

(d) Control Instruction

The purpose of each these instructions is

(a) Type Declaration instruction - to declare the type of variables used in a C program

(b) Input/Output instruction - to perform the function of supplying input data to a program and obtaining the output results from it.

(c) Arithmetic instruction - to perform arithmetic operations between constants and variables.

(d) Control instruction - to control the sequence of execution of various statements in a C program.

Type Declaration Instruction

This instruction is used to declare the type of variables being used in the program.

Any variable used in the program must be declared before using it in any statement. The

type declaration statement is usually written ate the beginning of the C program.

Ex: int bas;float rs, grosssal;char name,code;

Arithmetic Instruction

A C arithmetic instruction consists of a variable name on the left hand side of =

and variable names & constants on the right hand side of the =. The variables and

constants appearing on the right hand side of = are connected by arithmetic operators like

+, -, *, and /.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 12: 1. Programming in ‘C’

Assigning Values

The values can be assigned to variables using assignment statements.

The general format of assignment statement is…

Variable-name = expression;

where expression may be as simple as a constant or as complex as an expression.

The operator = is called assignment operator. The left of assignment operator

must be a variable. It should not be a function or a constant.

1.12 Operators & Expressions

C is extremely rich in built-in operators. An operator is a symbol that tells the

computer to perform certain mathematical or logical manipulations. Operators are used

in program to manipulate data and variables. The data items that operators act upon are

called operands. Some operators require two operands, while others act upon only one

operand. The operators are classified into unary, binary and ternary depending on

whether they operate on one, two or three operands respectively.

C has four classes of operators

- Arithmetic Operators

- Relational Operators

- Logical Operators

- Bit-wise Operators

In addition, C has some special operators, which are unique to C, they are

- Increment & Decrement Operators

- Conditional Operators

- Assignment Operators, etc.

Arithmetic Operators

There are five arithmetic operators in C. The following table lists the arithmetic

operators allowed in C:

Operator Meaning+-*/

%

AdditionSubtraction; also for unary minusMultiplicationDivisionModulo division (remainder after integer division)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 13: 1. Programming in ‘C’

The modulo division operator % cannot be used on type float or double. It can

be used only on type int and char.

A C arithmetic statement could be of three types.

1. Integer Mode : In this mode, all operands in an arithmetic statement are

either integer constants or integer variables.

2. Real Mode : All operands in an arithmetic statement are either real constants

or real variables.

3. Mixed Mode : Some of the operands in an arithmetic statement are integer

and some of the operands are real.

Relational Operators

Relational Operators are symbols that are used to test the relationship between

two variables or between a variable and a constant. We often compare two quantities,

and depending on their relation takes certain decisions. These comparisons can be done

with the help of relational operators.

C has six relational operators as shown below.

Operator Meaning>

>=<

<== =!=

Greater thanGreater than or Equal toLess thanLess than or Equal toEqual toNot equal to

There should not be any space between two characters in an operator, i.e., <=

should not be written as < =.

Logical Operators

Logical Operators are symbols that are used to combine or negate expressions

containing relational operators.

C has three logical operators as defined below.

Operator Meaning&&||!

Logical ANDLogical OR

Logical NOT

The && and || operators are binary operators, whereas ! is a unary operator.

OR, is used when at least one of the two conditions must be true in order for the

compound condition to be true.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 14: 1. Programming in ‘C’

AND, is used to both conditions must be true in order for the compound condition

to be true.

NOT, is used to reverse the truth-value of its operand.An expression containing a logical operator is termed as a logical expression. Like the

simple relational expressions, a logical expression also yields a value of one or zero.

Bitwise operators

C supports a set of bitwise operations. The lowest logical element in the memory

is bit. C allows the programmer to interact directly with the hardware of a particular

system through bitwise operators and expression. These operators work only with int

and char datatypes and cannot be used with float and double type.

The following table shows the bitwise operators that are available in C.

Operator Meaning-|&^

>><<

One’s ComplementBitwise ORBitwise ANDBitwise Exclusive OR (XOR)Right ShiftLeft Shift

Increment & Decrement operators

C has two very useful operators for adding and subtracting a variable. These are

the increment and decrement operators, ++ and --

These two operators are unary operators. The increment operator ++ adds 1 to its

operand, and the decrement operator -- subtracts 1 from its operand. Therefore, the

following are equivalent operations.

++i; is equivalent to i = i + 1;

--i; is equivalent to i = i – 1;

These operators are very useful in loops.

Assignment operators

In addition to usual assignment operator =, C has a set of shorthand operators, that

simplifies the coding of a certain type of assignment statement. It is of the form

var op = exp

where var is a variable, op is a C binary arithmetic operator and exp is an

expression.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 15: 1. Programming in ‘C’

The operator += means add the expression on the right to the variable on the left

and the operator -= means subtract the expression on the right from the variable on the

left.

Statement Equivalent Statement

a + = b;a - = b;a * =b;

a * = b + c;a / = b;

a % = b;a * = a;

a = a + ba = a - b;a = a * b;

a = a * ( b+ c);a = a / b;

a = a % b;a = a * a;

Conditional Operator

C provides a peculiar operator ? : which is useful in reducing the code. It is

ternary operator requiring three operands.

The general format is

exp1 ? exp2 : exp3;

where exp1, exp2 and exp3 are expressions. In the above conditional expression,

exp1 is evaluated first. If the value of exp1 is non zero (true), then the value returned will

be exp2. if the value of exp1 is zero (false), then the value returned will be exp3.

Hierarchy (precedence) of operators

The priority or precedence in which the operations of an arithmetic statement are

performed is called the hierarchy of operators.

Each operator has a precedence associated with it. This precedence is used to

determine how an expression involving more than one operator is evaluated. The

operators of at the higher level of precedence are evaluated first. The operators of the

same precedence are evaluated either from left to right or from right to left, depending on

the level. This is known as the associativity property of an operator.

PRECEDENCE OF OPERATORS (Arithmetic operators only)

Operator Description Associativity Rank

*/

%+

MultiplicationDivisionModuloAddition

Left to right“““

3334

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 16: 1. Programming in ‘C’

- Subtraction “ 4

1.13 Structure of a ‘C’ program

C programs consist of one or more functions. Each function performs a specific

task. A function is a group or sequence of C statements that are executed together.

The following is a simple C program that prints a message on the screen.

/* A simple program for printing a message */

# include <stdio.h>

# include <conio.h>

void main( )

{ clrscr( );

printf(“Welcome to C”);

getch( );}

Description

The first line

/* A simple program for printing a message */

is a comment line. Comments in the c program are optional and may appear anywhere in

a C program. Comments are enclosed between /* and */.

The second line

# include <stdio.h>

tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one

of header files, contain the information about input and output functions. stdio.h means

Standard Input Output Header file. This file contains the information about printf()

function.

The third line

# include <conio.h>

tells the compiler to read the file conio.h and include its contents in this file. conio.h

means Consoled Input Output Header file. This file contains the information about

clrscr() and getch() functions.

The fourth line

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 17: 1. Programming in ‘C’

void main( )

is the stat of the main program. The word main is followed by a pair of ordinary

parenthesis ( ), which indicates that main is also a function.

The fifth line

{

the left brace represents the beginning of the program.

The sixth line

clrscr( );

tells the compiler to clear the screen and kept the cursor at left side corner.

The seventh line

printf( “Welcome to C”);

this function causes its arguments to be printed on the screen on the computer.

The eight line

getch( );

is reads the single character directly from the keyboard without printing on the screen.

The ninth line

}

the right brace represents the ending of the program.

The body of the function is enclosed within a pair of braces. This section contains

two parts.

(a) Declaration part.(b) Executable part.

The following are some of rules to write C programs.

1. All C statements must end with semicolon.

2. C is case-sensitive. That is, upper case and lower case characters are different. Generally the statements are typed in lower case.

3. A C statement can be written in one line or it can split into multiple lines.

4. Braces must always match upon pairs, i.e., every opening brace { must have a matching closing brace }.

5. Every C program starts with void main( ) function.

6. Comments cannot be nested. For example, /* Welcome to ‘C’ ,/* programming*/ */

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 18: 1. Programming in ‘C’

7. A comment can be split into more than one line.

1.14 Execution of C Program

Steps to be followed in writing and running a C program.

(a) Creation of Source Program

Create a C program file in various C compilers are available under MS-DOS,

Turbo C Editor etc.

(b) Compilation of the Program

Turbo C compiler is user friendly and provides integrated program development

environment. Thus, selecting key combination can do compilation. That means press

Alt + F9 for compilation.

(c) Program Execution

In Turbo C environment, the RUN option will do the compilation and execution

of a program. Press Ctrl + F9 for execution the program.

1.15 Different types of files in C

In C programming language every source file is saved with an extension of .c.

The compiler automatically converts this source file into machine code at compiling time

and creates an executable file. The machine code is saved with an extension of .obj, and

the executable file is saved with an extension of .exe.

For Example, the source file name is emp.c then the object and executable files

are emp.obj and emp.exe respectively. These two files (emp.obj and emp.exe files are

automatically created by the compiler at compile time.)

1.16 printf( ) Function: Writing Output Data

The printf( ) function is used to write information to standard output (normally

monitor screen). The structure of this function is

printf(format string, list of arguments);

The format string contains the following:

- Characters that are simply printed on the screen.

- Specifications that begin with a % sign and define the output format for display of each item.

- Escape sequence characters that begin with a \ sign such as \n, \t, \b etc.Examplesprintf(“This is C statement”);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 19: 1. Programming in ‘C’

printf(“The number is:%d”,a);printf(“The number %d is equal to %d”,10,10);

Field type, format specifiers used by printf( )

Character Argument Resulting Outputcdsf

CharacterIntegerStringFloating point

A single characterSigned decimal integerPrints character stringsSingle floating point number

Note: Use a prefix l with %d, %u, %x, %0 to specify long integer (for example, %ld).

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

System Ready

Enter Program

Edit Source Program

Compile Source Program

Synta

x

Errors

?

Link with System Library

Execute Object Code

Logic and

Data

Errors?

CORRECT OUTPUT

Stop

Program Code

C Compiler

System Library

Input Data

Page 20: 1. Programming in ‘C’

1.18 scanf( ) Function: getting user input

The real power of a technical C program is its ability to interact with the program

user. This means that the program gets input values for variables from users.

The scanf( ) function is a built-in C function that allows a program to get user

input from the keyboard. The structure of this function is

scanf(format string,&list of arguments);

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

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

PROGRAMSProg.1: To print a message on the screen.

/* Printing a message on the screen */

#include<stdio.h>#include<conio.h>void main() {

clrscr();printf(“This is my First Program in C ”);getch();

}

Output

This is my First Program in C

Prog.2: To print our Institute Name.

/* Printing our institute name */

#include<stdio.h>#include<conio.h>void main(){

clrscr(); printf(“Welcome to Millennium Software Solutions”);

getch();}

Output

Welcome to Millennium Software Solutions

Prog.3: To Display Multiple Statements.

/* Printing our Institute Address*/

#include<stdio.h>#include<conio.h>

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 21: 1. Programming in ‘C’

void main(){

clrscr(); printf(“Millennium Software Solutions”);

printf(“\nVisakhapatnam”); getch();

}

Output

Millennium Software Solutions Visakhapatnam

Prog.4: To Display a value of single variable

/*Initialization of a variable*/

#include<stdio.h>#include<conio.h>void main(){ int a; /* Declaration */

clrscr(); a = 10; /* Initialization */ printf(“The value is:%d”,a); getch();

}

Output

The value is:10

Prog.5: To Display values of two variables.

/*Declaration and Initialization of a variables*/

#include<stdio.h>#include<conio.h>void main(){

int a=10,b=20; clrscr();

printf(“%d is a value,%d is b value”,a,b); getch();

}

Output

10 is a value,20 is b value

Prog.6: To calculate the sum of two numbers.

/* Sum of two numbers */

#include<stdio.h>#include<conio.h>void main(){

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 22: 1. Programming in ‘C’

int a=10,b=20; clrscr(); printf(“Sum of two numbers is:%d”,a+b); getch();

}

Output

Sum of two numbers is:30

Prog.7: To calculate all arithmetic operations.

/*All arithmetic operations*/

#include<stdio.h>#include<conio.h>void main(){

int a=4,b=2; clrscr(); printf(“Sum is:%d”,a+b); printf(“\nDiff is:%d”,a-b); printf(“\nProd is:%d”,a*b); printf(“\nQuo is:%d”,a/b); printf(“\n Rem is:%d”,a%b);

getch();}

OutputSum is:6Diff is:2Prod is:8Quo is:2Rem is:0

Prog.8: To swap two variables using third variable.

/* Swapping of two variables*/

#include<stdio.h>#include<conio.h>void main(){

int a=10,b=20,c; clrscr(); printf(“Before swapping:%d,%d”,a,b) ; c = a; a = b; b = c; printf(“\nAfter swapping:%d,%d”,a,b); getch();

}Output

Before swapping:10,20After swapping:20,10

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 23: 1. Programming in ‘C’

Prog.9: To initialize all datatypes (int, char, float)

/* Initialization of all datatypes */

#include<stdio.h>#include<conio.h>void main(){

int a=10;char i=’x’;float pi=3.14;clrscr(); printf(“The integer is:%d”,a);printf(“\nThe char is:%c”,i);printf(“\nThe float is:%.2f”,pi);getch();

}Output

The integer is:10The char is:xThe float is:3.14

Prog.10: To input a number and display on the screen.

/* Input and display a number */

#include<stdio.h>#include<conio.h>void main( ){

int n;clrscr( );printf(“Enter a number:”);scanf(“%d”,&n);printf(“%d is given by you”,n);getch( );

}Output

Enter a number:10 (press Enter)10 is given by you

Prog.11: To input two numbers and print them.

/* Scanning two numbers and printing 1st method*/

#include<stdio.h>#include<conio.h>void main( ){

int a,b;clrscr( );printf(“Enter 2 numbers:”);scanf(“%d%d”,&a,&b);printf(“The 2nos are:%d,%d”,a,b);getch( );

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 24: 1. Programming in ‘C’

}

Output

Enter 2 numbers:10 20 (press Enter)The 2nos are:10,20

(OR)

/* Scanning two numbers and printing 2nd method*/

#include<stdio.h>#include<conio.h>void main( ){

int a,b;clrscr( );printf(“Enter a value:”);scanf(“%d”,&a);printf(“Enter b value:”);scanf(“%d”,&b);printf(“The 2nos are:%d,%d”,a,b);getch( );

}

Output

Enter a value:10 (press Enter)Enter b value:20 (press Enter)The 2nos are:10,20

Prog.12:Input two numbers and calculate all arithmetic operations

/* To calculate all arithmetic operations */

#include<stdio.h>#include<conio.h>void main( ){

int a,b;clrscr( );printf(“Enter a value:”);scanf(“%d”,&a);printf(“Enter b value:”);scanf(“%d”,&b);printf(“a+b=%d”,a+b);printf(“\na-b=%d”,a-b);printf(“\na*b=%d”,a*b);printf(“\na/b=%d”,a/b);printf(“\nRem=%d”,a%b);getch( );

}

Output

Enter a value:4Enter b value:2a+b=6

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 25: 1. Programming in ‘C’

a-b=2a*b=8a/b=2Rem=0

Prog.13: Swapping two numbers with using third variable.

/* Swapping 2variable using third variable */

#include<stdio.h>#include<conio.h>void main( ){

int a,b,c;clrscr( );printf(“Enter a value:”);scanf(“%d”,&a);printf(“Enter b value:”);scanf(“%d”,&b);printf(“Before swapping the values are:%d,%d”,a,b);c = a;a = b;b = c;printf(“\nAfter swapping the values are:%d,%d”,a,b);getch( );

}

OutputEnter a value:10Enter b value:20Before swapping the values are:10,20After swapping the values are:20,10

Prog.14: Swapping two numbers without using third variable./* Swapping 2variables without using third variable */#include<stdio.h>#include<conio.h>void main(){

int a,b;clrscr( );printf(“Enter a and b values:”);scanf(“%d%d”,&a,&b);printf(“Before swapping the values are:%d,%d”,a,b);a = a+b;b = a-b;a = a-b;printf(“\nAfter swapping the values are:%d,%d”,a,b);getch( );

}

Output

Enter a value:10Enter b value:20

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 26: 1. Programming in ‘C’

Before swapping the values are:10,20After swapping the values are:20,10

Prog.15: To convert the hours into minutes and seconds

/* Conversion of hours into minutes and seconds */

#include<stdio.h>#include<conio.h>void main( ){

int hr;clrscr( );printf(“Enter an hour:”);scanf(“%d”,&hr);printf(“minutes=%d”,hr*60);printf(“\nseconds=%d”,hr*60*60);getch( );

}

Output

Enter an hour:2minutes=120seconds=7200

Prog.16: To convert the years into days and months

/* Conversion of years into days and months */

#include<stdio.h>#include<conio.h>void main( ){

int y;clrscr( );printf(“Enter a year:”);scanf(“%d”,&y);printf(“Days=%d”,y*365);printf(“\nMonths=%d”,y*12);getch( );

}

Output

Enter a year:2Days=730Months=24

Prog.17: To calculate Area and Perimeter of a Rectangle

/* Area and Perimeter of a Rectangle */

#include<stdio.h>#include<conio.h>void main( ){

int l,b;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 27: 1. Programming in ‘C’

clrscr( );printf(“Enter l and b values:”);scanf(“%d%d”,&l,&b);printf(“Area=%d”,2*(l+b));printf(“\nPerimeter=%d”,l*b);getch( );

}

Output

Enter l and b values:2 4Area=12Perimeter=8

Prog.18: To calculate Area and Perimeter of a Square

/* Area and Perimeter of a Square */

#include<stdio.h>#include<conio.h>void main( ){

int s;clrscr( );printf(“Enter s value:”);scanf(“%d”,&s);printf(“Area=%d”,s*s);printf(“\nPerimeter=%d”,4*s);getch( );

}

Output

Enter s value:3Area=9Perimeter=12

Prog.19: To calculate Area and Circumference of a Circle

/* Area and Circumference of a Circle */

#include<stdio.h>#include<conio.h>void main( ){

float r,pi=3.14;clrscr( );printf(“Enter radius of a circle:”);scanf(“%f”,&r );printf(“Area=%.2f”,2*pi*r);printf(“\nCircumference=%.2f”,pi*r*r);getch( );

}

Output

Enter radius of a circle:2Area=12.56

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 28: 1. Programming in ‘C’

Circumference=12.56

Prog.20: To calculate total and average of a student.

/* Total and Average calculation */

#include<stdio.h>#include<conio.h>void main( ){

int stuno,sub1,sub2,sub3;float tot,avg;clrscr( );printf(“Enter stuno:”);scanf(“%d”,&stuno);printf(“Enter sub1:”);scanf(“%d”,&sub1);printf(“Enter sub2:”);scanf(“%d”,&sub2);printf(“Enter sub3:”);scanf(“%d”,&sub3);tot = sub1 + sub2 + sub3;avg = tot/3;printf(“\nTotal=%.2f”,tot);printf(“\nAverage=%.2f”,avg);getch( );

}

Output

Enter stuno:101Enter sub1:65Enter sub2:65Enter sub3:65Total=195.00Average=65.00

- x -

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 29: 1. Programming in ‘C’

2. CONTROL STRUCTURES

2.1 Introduction: A C statement consists of keywords, expressions and other

statements. There are two types of statements in C. These are single statements and

compound statements. A compound statement is a series of statements enclosed with in

braces ({}) while a single statement ends with a semicolon (;).

The control flow statements of a language determine the order in which the

statements are executed.

We also need to be able to specify that a statement, or a group of statements, is to

be carried out conditionally, only if some condition is true. Also we need to be able to

carry out a statement or a group of statements repeatedly based on certain conditions.

These kinds of situations are described in C using Conditional Control and Loop

Control structures.

A conditional structure can be implemented in C using

(a) The if statement

(b) The if-else statement

(c) The nested if-else statement

(d) The switch statement.

whereas loop control structures can be implemented in C using

(a) while loop

(b) do-while loop

(c) for statement

2.2 The if statement

The if statement is used to control the flow of execution of statements. The

general form of if statement is

if (condition)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 30: 1. Programming in ‘C’

statement;

Suppose if it is required to include more than one statement, then a compound statement

is used, in place of single statement. The form of compound statement is

if (condition){

statement1;statement2;

}If the condition is true, then the statement/statements will be executed. If the condition is

false, then the statement/statements will not be executed. A simple condition relates two

quantities using relational operators (==, !=, <, <=, >, >=).

Relation operator

The quantities may be variables, constants or expressions.

Example

The following program illustrates whether the number is even or odd.

/* Even or Odd */

#include<stdio.h>#include<conio.h>void main( ){

int n;clrscr( );printf(“Enter a number:”);scanf(“%d”,&n);if(n%2==0)printf(“It is Even number”);if(n%2!=0)printf(“It is Odd number”);getch( );

}

Output 1

Enter a number:4It is Even number

Output 2

Enter a number:5It is Odd numberNote that there is no semicolon between the condition and the statement i.e., no

semicolon following if(n%2==0).

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

quantity 1 quantity 2

Page 31: 1. Programming in ‘C’

It is important to note that, if the condition is false the statement is skipped and

control goes to the next statement immediately after if statement.

2.3 The if-else Statement

The general form of if-else statement is…

if (condition)statement1;

elsestatement2;

If the condition is true, then statement1 is executed. Otherwise if the condition

is false, then the statement2 is executed. Here statements statement1 and statement2 are

either simple statements or compound statements.

That is…

if (condtion){

statements /* if block */}else{

statements /* else */}

Note that only one block will be executed but not both.

Example

Program illustrates the if-else statements.

/* Even or Odd using if-else */

#include<stdio.h>#include<conio.h>void main( ){

int n;clrscr( );printf(“Enter a number:”);scanf(“%d”,&n);if(n%2==0)printf(“Even number”);elseprintf(“Odd number”);getch( );

}Output 1

Enter a number:4Even number

Output 2

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 32: 1. Programming in ‘C’

Enter a number:5Odd number

2.4 Nested if-else Statements

When a series of conditions are involved, we can use more than one if-else

statement in nested form. This form is also known as if-else if-else statements. The

general form of if-else if-else statement is

if (condition)statements;

else if (condition)statements;

elsestatements;

Note that a program contains number of else if statements and must be ended with else

statement.

Example

Program illustrates the if-else if-else statements.

/* Find the highest of three values */

#include<stdio.h>#include<conio.h>void main( ){

int a,b,c;clrscr( );printf(“Enter the three values:”);scanf(“%d%d%d”,&a,&b,&c);if(a>b && a>c)printf(“%d is big”,a);else if(b>a && b>c)printf(“%d is big”,b);elseprintf(“%d is big”,c);getch( );

}

Output 1

Enter the three values:3 5 77 is big

Output 2

Enter the three values:5 6 26 is big

Output 3

Enter the three values:3 2 13 is big

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 33: 1. Programming in ‘C’

2.5 The Switch Statement – Selecting One Of Many Alternatives

The Switch statement is an extension of the if-else if-else statement. The switch

makes one selection when there are several choices to be made. The direction of the

branch taken by the switch statement is based on the value of any int (or int compatible)

variable or expression.

The general form of Switch statement is shown below.

switch (variable){

case constant1:statement 1;case constant2:statement 2;case constant3:statement 3;“ “ ““ “ ““ “ “case constant n:statement n;default :statement;

}

The variable following the keyword switch is any C expression that that will

result an integer value.

The break statement used inside each case of the switch, causes an intermediate

exit from the switch statement; and continue onto the next statement outside the switch

statement.

Note: If the break statement is not including, all of the statements at and below the

match will be executed.

The advantage of switch over if is that it leads to a more structured program and

the level of indentation is manageable. C allows nesting switch statements, i.e., a switch

may be a part of a case.

Example

Program illustrates the switch statement.

/* Words corresponding Numbers */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number(0-9):”);scanf(“%d”,&n);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 34: 1. Programming in ‘C’

switch(n){

case 0: printf(“Zero”); break;

case 1: printf(“One”);break;

case 2: printf(“Two”);break;

case 3: printf(“Three”);break;

case 4: printf(“Four”);break;

case 5: printf(“Five”);break;

case 6: printf(“Six”);break;

case 7: printf(“Seven”);break;

case 8: printf(“Eight”);break;

case 9: printf(“Nine”);break;

default:printf(“More than 9”);}

getch();}

Output 1

Enter a number (0-9):0Zero

Output 2

Enter a number (0-9): 10More than 9

PROGRAMS

Conditional Operators (?:)

Prog.21: To check whether the year is leap or not

/* Inputting year is Leap or not */

#include<stdio.h>#include<conio.h>void main(){

int year;clrscr();printf(“Enter year:”);scanf(“%d”,&year);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 35: 1. Programming in ‘C’

(year%4==0)?printf(“Leap year”):printf(“Not leap year”);getch();

}

Output 1

Enter year:1990Not leap year

Output 2

Enter year:1996Leap year

Prog.22: To find the biggest number in two variables

/* Biggest number in two variables */

#include<stdio.h>#include<conio.h>void main(){

int a,b;clrscr();printf(“Enter a,b values:”);scanf(“%d%d”,&a,&b);(a>b)?printf(“a is big”):printf(“b is big”);getch();

}Output 1

Enter a,b values:3 4b is big

Output 2

Enter a,b values:4 2a is big

Prog.23: To check the enter number is single digit or not

/* Single digit or not */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);

(n<=9)?printf(“Single digit”):printf(“Not single digit”);getch();

}

Output 1

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 36: 1. Programming in ‘C’

Enter a number:5Single digit

Output 2

Enter a number:12Not single digit

Prog.24: To check the number is whether even or odd

/* Even or Odd */

#include<stdio.h>#include<conio.h>void main(){

int x;clrscr();printf(“Enter a number:”);scanf(“%d”,&x);

(x%2==0)?printf(“It is Even Number”):printf(“It is Odd Number”);getch();

}

Output 1

Enter a number:5It is Odd Number

Output 2

Enter a number:4It is Even Number

Prog.25: To check the number is positive, negative or zero.

/* To check whether +ve, -ve or zero */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);

(n>0)?printf(“+ve”):(n<0)?printf(“-ve”):printf(“zero”);getch();

}

Output 1

Enter a number: -2-ve

Output 2

Enter a number:0zero

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 37: 1. Programming in ‘C’

Output 3

Enter a number:5+ve

Prog.26: Find the highest number in three variables.

/* Biggest number in 3 variables */

#include<stdio.h>#include<conio.h>void main(){

int a,b,c;clrscr();printf(“Enter a,b,c values:”);scanf(“%d%d%d”,&a,&b&c);(a>b && a>c)?printf(“a is big”):(b>a && b>c)?printf(“b is big”):printf(“c is big”);getch();

}

Output 1

Enter a,b,c values:3 5 7c is big

Output 2

Enter a,b,c values:8 4 6a is big

If statement

Prog.27: To check whether the year is leap or not

/* Inputting year is Leap or not */

#include<stdio.h>#include<conio.h>void main(){

int year;clrscr();printf(“Enter year:”);scanf(“%d”,&year);

if(year%4==0)printf(“Leap year”);if(year%4!=0)printf(“Not leap year”);getch();

}

Output 1

Enter year:1990Not leap year

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 38: 1. Programming in ‘C’

Output 2

Enter year:1996Leap year

Prog.28: To find the biggest number in two variables

/* Biggest number in two variables */

#include<stdio.h>#include<conio.h>void main(){

int a,b;clrscr();printf(“Enter a,b values:”);scanf(“%d%d”,&a,&b);if(a>b)printf(“a is big”);if(a<b)printf(“b is big”);getch();

}Output 1

Enter a,b values:3 4b is big

Output 2

Enter a,b values:4 2a is bigProg.29: To check the enter number is single digit or not

/* Single digit or not */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);if(n<=9)printf(“Single digit”);if(n>9)printf(“Not single digit”);getch();

}

Output 1

Enter a number:5Single digit

Output 2

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 39: 1. Programming in ‘C’

Enter a number:12Not single digit

Prog.30: To check the number is positive, negative or zero.

/* To check whether +ve, -ve or zero */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);if(n>0)printf(“+ve”);if(n<0)printf(“-ve”);if(n==0)printf(“zero”);getch();

}

Output 1

Enter a number: -2-ve

Output 2

Enter a number:0zero

Output 3

Enter a number:5+ve

Prog.31: Find the highest number in three variables.

/* Biggest number in 3 variables */

#include<stdio.h>#include<conio.h>void main(){

int a,b,c;clrscr();printf(“Enter a,b,c values:”);scanf(“%d%d%d”,&a,&b&c);if(a>b && a>c)printf(“a is big”);if(b>a && b>c)printf(“b is big”);if(c>a && c>b)printf(“c is big”);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 40: 1. Programming in ‘C’

getch();}

Output 1

Enter a,b,c values:3 5 7c is big

Output 2

Enter a,b,c values:8 4 6a is big

Output 3Enter a,b,c values:4 9 1b is bigIf-else Statement

Prog.32: To check the enter number is single digit or not

/* Single digit or not */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);if(n<=9)printf(“Single digit”);elseprintf(“Not single digit”);getch();

}

Output 1

Enter a number:5Single digit

Output 2

Enter a number:12Not single digit

Prog.33: To find the biggest number in two variables

/* Biggest number in two variables */

#include<stdio.h>#include<conio.h>void main(){

int a,b;clrscr();printf(“Enter a,b values:”);scanf(“%d%d”,&a,&b);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 41: 1. Programming in ‘C’

if(a>b)printf(“a is big”);elseprintf(“b is big”);getch();

}Output 1

Enter a,b values:3 4b is big

Output 2

Enter a,b values:4 2a is bigProg.34: To check whether the year is leap or not

/* Inputting year is Leap or not */

#include<stdio.h>#include<conio.h>void main(){

int year;clrscr();printf(“Enter year:”);scanf(“%d”,&year);

if(year%4==0)printf(“Leap year”);elseprintf(“Not leap year”);getch();

}

Output 1

Enter year:1990Not leap year

Output 2

Enter year:1996Leap year

Prog.35: To check whether the character is vowel or consonant.

/* Vowel or Consonant */

#include<stdio.h>#include<conio.h>void main(){

char x;clrscr();printf(“Enter a letter:”);scanf(“%c”,&x);if(x==’a’ || x==’A’ || x==’e’ || x==’E’ || x==’i’ || x==’I’ || x==’o’ || x==’O’ || x==’u’ || x==’U’)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 42: 1. Programming in ‘C’

printf(“It is Vowel”);elseprintf(“It is Consonant”);getch();

}

Output 1

Enter a letter:bIt is Consonant

Output 2

Enter a letter:uIt is Vowel

If-else if-else statement

Prog.36: Find the highest number in three variables.

/* Biggest number in 3 variables */

#include<stdio.h>#include<conio.h>void main(){

int a,b,c;clrscr();printf(“Enter a,b,c values:”);scanf(“%d%d%d”,&a,&b&c);if(a>b && a>c)printf(“a is big”);else if(b>a && b>c)printf(“b is big”);elseprintf(“c is big”);getch();

}Output 1

Enter a,b,c values:3 5 7c is big

Output 2

Enter a,b,c values:8 4 6a is big

Output 3

Enter a,b,c values:4 9 1b is big

Prog.37: To check the number is positive, negative or zero.

/* To check whether +ve, -ve or zero */

#include<stdio.h>#include<conio.h>

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 43: 1. Programming in ‘C’

void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);if(n>0)printf(“+ve”);else if(n<0)printf(“-ve”);elseprintf(“zero”);getch();

}

Output 1

Enter a number: -2-ve

Output 2

Enter a number:0zero

Output 3

Enter a number:5+ve

Prog.38:To calculate the grade of a student.

/* Grade of a student */

#include<stdio.h>#include<conio.h>void main(){

int stuno,sub1,sub2,sub3;float tot,avg;clrscr( );printf(“Enter stuno:”);scanf(“%d”,&stuno);printf(“Enter sub1:”);scanf(“%d”,&sub1);printf(“Enter sub2:”);scanf(“%d”,&sub2);printf(“Enter sub3:”);scanf(“%d”,&sub3);tot = sub1 + sub2 + sub3;avg = tot/3;printf(“\nTotal=%.2f”,tot);printf(“\nAverage=%.2f”,avg);if(avg>=60)printf(“\nFirst Class”);else if(avg>=50)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 44: 1. Programming in ‘C’

printf(“\nSecond Class”);else if(avg>=35)printf(“\nThird Class”);elseprintf(“\nFail”);getch( );

}Output 1

Enter stuno:101Enter sub1:65Enter sub2:65Enter sub3:65Total=195.00Average=65.00First Class

Output 2

Enter stuno:105Enter sub1:30Enter sub2:65Enter sub3:65Total=160Average=53.34Second Class

Prog.39:To calculate the grade of a student if passed.

/* Grade of a student if passed*/

#include<stdio.h>#include<conio.h>void main(){

int stuno,sub1,sub2,sub3;float tot,avg;clrscr( );printf(“Enter stuno:”);scanf(“%d”,&stuno);printf(“Enter sub1:”);scanf(“%d”,&sub1);printf(“Enter sub2:”);scanf(“%d”,&sub2);printf(“Enter sub3:”);scanf(“%d”,&sub3);tot = sub1 + sub2 + sub3;avg = tot/3;printf(“\nTotal=%.2f”,tot);printf(“\nAverage=%.2f”,avg);if(sub1>=35 && sub2>=35 && sub3>=35){

if(avg>=60)printf(“\nResult:First Class”);else if(avg>=50)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 45: 1. Programming in ‘C’

printf(“\nResult:Second Class”);else printf(“\nResult:Third Class”);

}elseprintf(“\nResult:Fail”);getch( );

}Output 1

Enter stuno:101Enter sub1:65Enter sub2:65Enter sub3:65Total=195.00Average=65.00Result:First Class

Output 2

Enter stuno:105Enter sub1:30Enter sub2:65Enter sub3:65Total=160Average=53.34Result:Fail

Prog.40:To print the Result of a student.

/* Result of a student*/

#include<stdio.h>#include<conio.h>void main(){

int stuno,sub1,sub2,sub3;float tot,avg;clrscr( );printf(“Enter stuno:”);scanf(“%d”,&stuno);printf(“Enter sub1:”);scanf(“%d”,&sub1);printf(“Enter sub2:”);scanf(“%d”,&sub2);printf(“Enter sub3:”);scanf(“%d”,&sub3);tot = sub1 + sub2 + sub3;avg = tot/3;printf(“\nTotal=%.2f”,tot);printf(“\nAverage=%.2f”,avg);if(sub1>=35 && sub2>=35 && sub3>=35){

if(avg>=60)printf(“\nResult:First Class”);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 46: 1. Programming in ‘C’

else if(avg>=50)printf(“\nResult:Second Class”);else printf(“\nResult:Third Class”);

}else{

if(sub1<35 && sub2>=35 && sub3>=35)printf(“\nResult:Fail in Sub1”);else if(sub1>=35 && sub2<35 && sub3>=35)printf(“\nResult:Fail in Sub2”);else if(sub1>=35 && sub2>=35 && sub3<35)printf(“\nResult:Fail in Sub3”);else if(sub1<35 && sub2<35 && sub3>=35)printf(“\nResult:Fail in Sub1 & Sub2”);else if(sub1<35 && sub2>=35 && sub3<35)printf(“\nResult:Fail in Sub1 & Sub3”);else if(sub1>=35 && sub2<35 && sub3<35)printf(“\nResult:Fail in Sub2 & Sub3”);elseprintf(“\nResult:Fail in all subjects”);

}getch( );

}

Output 1

Enter stuno:101Enter sub1:65Enter sub2:65Enter sub3:65Total=195.00Average=65.00Result:First Class

Output 2

Enter stuno:105Enter sub1:30Enter sub2:65Enter sub3:65Total=160Average=53.34Result:Fail in Sub1

Output 3

Enter stuno:103Enter sub1:60Enter sub2:30Enter sub3:50Total=140Average=46.67Result:Fail in Sub2

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 47: 1. Programming in ‘C’

Prog.41:To check whether letter is small, capital, digit or special symbol

/* Small, Capital, Digit or Special Symbol */

#include<stdio.h>#include<conio.h>void main(){

char x;clrscr();printf(“Enter a letter:”);scanf(“%c”,&x);if(x>=’a’ && x<=’z’)printf(“Small letter”);else if(x>=’A’ && x<=’Z’)printf(“Capital letter”);else if(x>=’0’ && x<=’9’)printf(“Digit”);elseprintf(“Special Symbol”);getch();

}

Output 1

Enter a letter:aSmall letter

Output 2

Enter a letter:CCapital letter

Output 3

Enter a letter:6Digit

Output 4

Enter a letter:#Special Symbol

Switch statement

Prog.42: To check whether the letter is vowel or consonant

/* Vowel or Consonant */

#include<stdio.h> #include<conio.h>void main(){

char x;clrscr();printf(“Enter a char:”);scanf(“%c”,&x);switch(x)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 48: 1. Programming in ‘C’

{case ‘a’:case ‘A’:case ‘e’:case ‘E’:case ‘i’:case ‘I’:case ‘o’:case ‘O’:case ‘u’:case ‘U’:printf(“Vowel”);

break;default:printf(“Consonant”);

}getch();

}

Output 1

Enter a char:aVowel

Output 2

Enter a char:bConsonant

Output 3

Enter a char:UVowel

Prog.43: To print words corresponding numbers below 9

/* Numbers -> words (0-9)*/

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number(0-9):”);scanf(“%d”,&n);switch(n){

case 0:printf(“Zero”);break;

case 1:printf(“One”);break;

case 2:printf(“Two”);break;

case 3:printf(“Three”);break;

case 4:printf(“Four”);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 49: 1. Programming in ‘C’

break;case 5:printf(“Five”);

break;case 6:printf(“Six”);

break;case 7:printf(“Seven”);

break;case 8:printf(“Eight”);

break;case 9:printf(“Nine”);

break;default:printf(“More than 9”);

}getch();

}Output 1

Enter a number(0-9):3Three

Output 2

Enter a number(0-9):12More than 9

Prog.44:To print Day corresponding Number

/* Number corresponding Day */

#include<stdio.h>#include<conio.h>void main(){

int n;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);switch(n){

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(“No week day”);}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 50: 1. Programming in ‘C’

getch();}

Output 1

Enter a number:3Tuesday

Output 2

Enter a number:9No week day

Prog.45: To print color name corresponding letter

/* Letter -> color name */

#include<stdio.h>#include<conio.h>void main(){

char x;clrscr();printf(“Enter a char:”);scanf(“%c”,&x);switch(x){

case ‘w’:printf(“w->white”);break;

case ‘b’:printf(“b->black”);break;

case ‘l’:printf(“l->blue”);break;

case ‘y’:printf(“y->yellow”);break;

case ‘g’:printf(“g->green”);break;

case ‘r’:printf(“r->red”);break;

case ‘o’:printf(“o->orange”);break;

default:printf(“No color”);}getch();

}

Output 1

Enter a char:ll->blue

Output 2

Enter a char:yy->yellow

Output 3

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 51: 1. Programming in ‘C’

Enter a char:cNo color

The exit( ) Function

The exit( ) is a function in the standard library of C. This function causes

immediate termination of the program and execution control return to the operating

system. In general, the termination to exit( ) function is 0 to indicate that termination is

normal. Other arguments may be used to indicate some sort of an error.

Prog.46: To calculate Arithmetic operations depends on user choice.

/* Arithmetic operation depends on user choice*/

#include<stdio.h>#include<conio.h>void main(){

int a,b,choice;clrscr();printf(“Welcome to Arithmetic operations”);printf(“\n--------------------------------\n”);printf(“\n\t1.Add”);printf(“\n\t2.Sub”);printf(“\n\t3.Mul”);printf(“\n\t4.Div(quo)”);printf(“\n\t5.Rem”);printf(“\n--------------------------------\n”);printf(“\nEnter U r choice here:”);scanf(“%d”,&choice);printf(“Enter 2nos:”);scanf(“%d%d”,&a,&b);switch(choice){

case 1:printf(“\nThe sum is:%d”,a+b);break;

case 2:printf(“\nThe sub is:%d”,a-b);break;

case 3:printf(“\nThe Product is:%d”,a*b);break;

case 4:printf(“\nThe quo is:%d”,a/b);break;

case 5:printf(“\nThe rem is:%d”,a%b);break;

default:exit(0);}getch();

}

Output 1

Welcome to Arithmetic operations--------------------------------

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 52: 1. Programming in ‘C’

1.Add2.Sub3.Mul4.Div(quo)5.Rem

--------------------------------Enter U r choice here:1Enter 2nos:5 4The sum is:9

Output 2

Welcome to Arithmetic operations--------------------------------

1.Add2.Sub3.Mul4.Div(quo)5.Rem

--------------------------------Enter U r choice here:6Enter 2nos:3 4

Prog.47: To calculate Arithmetic operations depends on arithmetic operator

/* Arithmetic operations depends on arithmetic operator */

#include<stdio.h>#include<conio.h>void main(){

int a,b;char ch;clrscr();printf(“Enter any arithmetic operator(+,-,*,/,%):”);scanf(“%c”,&ch);printf(“Enter 2nos:”);scanf(“%d%d”,&a,&b);switch(ch){

case ‘+’:printf(“\nThe sum is:%d”,a+b);break;

case ‘-‘:printf(“\nThe sub is:%d”,a-b);break;

case ‘*’:printf(“\nThe Product is:%d”,a*b);break;

case ‘/’:printf(“\nThe quo is:%d”,a/b);break;

case ‘%’:printf(“\nThe rem is:%d”,a%b);break;

default:exit(0);}getch();

}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 53: 1. Programming in ‘C’

Output 1

Enter any arithmetic operator(+,-,*,/,%):*Enter 2nos:45The Product is:20

- x -

3. LOOPS

3.1 Def: A portion of program that is executed repeatedly is called a loop.

The C programming language contains three different program statements for program

looping. They are

1. For loop

2. While loop

3. Do-While loop

3.2 The For Loop

The for loop is most common in major programming languages. However, the

for loop in languages is very flexible and very powerful. Generally, the for loop is used

to repeat the execution statement for some fixed number of times.

The general form of for loop is

for(initialization;condition;increment/decrement)statement;

where the statement is single or compound statement.

initialization is the initialization expression, usually an assignment to the loop-

control variable. This is performed once before the loop actually begins execution.

condition is the test expression, which evaluated before each iteration of the loop,

which determines when the loop will exist.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 54: 1. Programming in ‘C’

increment is the modifier expression, which changes the value of loop control

variable. This expression is executed at the end of each loop.

Semi colons separate these three sections.

The for loop repeats the execution of the statement as long as the conditional

expression evaluates to true. Once this test condition becomes false, the for loop will

terminate and control resumes to the statement that immediately following for loop.

The following program illustrates the use of for loop

/* Print 1 to 10 numbers */

#include<stdio.h>#include<conio.h>void main(){

int i;clrscr();for(i=1;i<=10;i++)printf(“\n%d”,i);getch();}

In this example, the for loop is repeated 10 times.

In for-loop, any or all of the three sections in the parentheses can be omitted,

although the semicolons must remain. If the conditional expression is omitted, it is

assumed to have a value1 and the loop continues infinitely.

The for statement

for(; ;){

statement;}

is an infinite loop. This can be terminated by using a break statement or an exit()

function.

The comma operator, is the power of the for loop. The general rule of comma

operator is multiple C expressions may be separated by a comma operator as

expression1, expression2, expression3, ………… and so on.

Expressions separated by comma operator are evaluated from left to right. For example,

the following for statement initializes the value of counter1 and counter2 values; and

also increments the counter1 and counter2 for each iteration.

for (counter1=0,counter=1;couter<=10;coutr1++,counter2++)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 55: 1. Programming in ‘C’

printf(“\n%d %d”,counter1,counter2);

Of all operations in C the comma operator has the lowest precedence.

This important feature of loops in C languages is that the statement in the loop

also can be omitted. Generally this type of loops is used in time-delay programs. For

example.

for(i=0,j=5;i<10 && j<50;i++,j=i+j)printf(“\n%d %d,”i,j);

This loop is repeated as long as the value of 1 is less than 10 and the value of j is

less than 50.

The increment and decrement operators are very useful in loops for incrementing

or decrementing the loop-control variable.

3.3 Nested Loops: C allows nested loops, i.e., a loop within a loop. The nested loops

are generally used when we want to run the program repeated by placing the entire

program within a loop such as while or for loop. In such case, prompt may be included

whether to continue the program or to terminate.

3.4 The While Loop

The while loop is best suited to repeat a statement or a set of statements as long as

some condition is satisfied.

The general form of while loop is

initial expression;while(conditional-expression){

statement;increment/decrement;

}

where the statement (body of the loop) may be a single statement or a compound

statements. The expression (test condition) must results zero or non-zero.

First of all, the expression in the while loop is evaluated. If the result is true (non-

zero), then the statement is executed and the expression is evaluated again. The

statements continue executes until the expression evaluates to false (zero). Then the loop

is finished and the program execution continues with the statement that follows by body

of while loop.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 56: 1. Programming in ‘C’

The statement in the while loop is executed zero or more times depending on the

expression. If the expression evaluates to false at the first time, then the statement is

never executed.

3.5 The do-while loop

The structure of do-while loop is similar to while loop. The difference is that in

case of do-while loop the expression is evaluated after the body of loop is executed. In

case of while loop the expression is evaluated before executing body of loop.

The general form of do-while statement is

do{

statement;}while(expression);

where statement is a single statement or compound statement. In contrast to while

loop statement (body of loop), do-while loop is executed one or more times.

In do-while loop, first the statement is executed and then the expression is tested.

If the expression evaluates to false, the loop terminates and the execution control transfer

to the next statement that follows it. Otherwise, if expression evaluates to true (non-

zero), execution of the statement is repeated and the iterative process continues.

In case of do-while loop, the statement is executed at least once, whereas in case

of while loop, the statement may not execute at all if the expression results false for the

first time itself.

PROGRAMS

The for loop

Prog.48: To print the message 10 times.

/* Print a message 10 times */

#include<stdio.h>#include<conio.h>void main(){

int i;clrscr();for(i=1;i<=10;i++)printf(“\nMillennium Software Solutions”);getch();

}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 57: 1. Programming in ‘C’

Output

Millennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software Solutions

Prog.49: To print 1 to 10 numbers.

/* Print 1 to 10 numbers */

#include<stdio.h>#include<conio.h>void main(){

int i;clrscr();for(i=1;i<=10;i++)printf(“\n%d”,i);getch();

}

Output

12345678910

Prog.50: To print 1 to 10 even numbers.

/* Print even numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i;clrscr();for(i=2;i<=10;i=i+2)printf(“\n%d”,i);getch();

}Output

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 58: 1. Programming in ‘C’

246810

Prog.51: To print 1 to 10 odd numbers.

/* Print odd numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i;clrscr();for(i=1;i<=10;i=i+2)printf(“\n%d”,i);getch();

}

Output13579Prog.52: To calculate sum of 10 natural numbers.

/* Sum of first 10 natural numbers */

#include<stdio.h>#include<conio.h>void main(){

int i,sum=0;clrscr();for(i=1;i<=10;i++)sum = sum + i;printf(“The sum of 10 natural numbers is:%d”,sum);getch();

}

Output

The sum of 10 natural numbers is:55

Prog.53: To calculate sum of even numbers below 10.

/* Sum of even numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i,sum=0;clrscr();

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 59: 1. Programming in ‘C’

for(i=2;i<=10;i=i+2)sum = sum + i;printf(“The sum of even numbers is:%d”,sum);getch();

}

Output

The sum of even numbers is:30

Prog.54: To calculate sum of odd numbers below 10.

/* Sum of odd numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i,sum=0;clrscr();for(i=1;i<=10;i=i+2)sum = sum + i;printf(“The sum of odd numbers is:%d”,sum);getch();

}Output

The sum of odd numbers is:25

Prog.55: To print 1 to n numbers.

/* Print 1 to n numbers */

#include<stdio.h>#include<conio.h>void main(){

int i,n;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=1;i<=n;i++)printf(“\n%d”,i);getch();

}

Output

Enter n value:512345

Prog.56: To print 1 to n even numbers.

/* Print 1 to n even numbers */

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 60: 1. Programming in ‘C’

#include<stdio.h>#include<conio.h>void main(){

int i,n;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=2;i<=n;i=i+2)printf(“\n%d”,i);getch();

}

Output

Enter n value:152468101214

Prog.57: To print 1 to n odd numbers.

/* Print 1 to n odd numbers */

#include<stdio.h>#include<conio.h>void main(){

int i,n;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=1;i<=n;i=i+2)printf(“\n%d”,i);getch();

}

Output

Enter n value:1513579111315

Prog.58: To calculate sum of 1 to n numbers

/* Sum of 1 to n numbers */

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 61: 1. Programming in ‘C’

#include<stdio.h>#include<conio.h>void main(){

int i,n,sum=0;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=1;i<=n;i++)sum = sum + i;printf(“Sum of first %d numbers is:%d”,n,sum);getch();

}

Output

Enter n value:5Sum of first 5 numbers is:15

Prog.59: To calculate 1 to n even numbers sum

/* Sum of 1 to n even numbers */

#include<stdio.h>#include<conio.h>void main(){

int i,n,sum=0;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=2;i<=n;i=i+2)sum = sum + i;

printf(“The sum of below %d even numbers is:%d”,n,sum);getch();

}

Output

Enter n value:10The sum of below 10 even numbers is:30

Prog.60: To calculate 1 to n odd numbers sum

/* Sum of 1 to n odd numbers */

#include<stdio.h>#include<conio.h>void main(){

int i,n,sum=0;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=1;i<=n;i=i+2)sum = sum + i;

printf(“The sum of below %d even numbers is:%d”,n,sum);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 62: 1. Programming in ‘C’

getch();}

Output

Enter n value:10The sum of below 10 odd numbers is:25

Prog.61: To calculate factorial of first five natural numbers.

/* Factorial of five */

#include<stdio.h>#include<conio.h>void main(){

int i,fact=1;clrscr();for(i=1;i<=5;i++)fact = fact * i;printf(“The factorial is:%d”,fact);getch();

}

Output

The factorial is:120

Prog.62: To calculate factorial of any number

/* Factorial of any number */

#include<stdio.h>#include<conio.h>void main(){

int i,n;long int fact =1;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);for(i=1;i<=n;i++)fact = fact * i;printf(“Factorial is:%ld”,fact);getch();

}

Output

Enter n value:8Factorial is:40320

Prog.63: To check the input number is prime or not.

/* Prime or not*/

#include<stdio.h>#include<conio.h>void main()

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 63: 1. Programming in ‘C’

{int n,status=0,i;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);if(n==1)printf(“It is prime number”);else{ for(i=2;i<n;i++) {

if(n%i == 0){

status =1;break;

} }}if(status == 0)printf(“It is prime number”);elseprintf(“It is not prime number”);getch();

}

Prog.64: To print Fibonacci series (1,1,2,3,5,8,13,…………)

/* Fibonacci Series */

#include<stdio.h>#include<conio.h>void main(){

int m;int n0,n1,n2,i;int count;clrscr();n0=1;n1=1;printf(“Enter the number of Fibonacci series:”);scanf(“%d”,&m);printf(“%d %d”,n0,n1);for(i=3;i<=m;i++){

n2 = n0+n1;printf(“ %d”,n2);n0 = n1;n1 = n2;

}getch();

}

Output

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 64: 1. Programming in ‘C’

Enter the number of Fibonacci series: 71 1 2 3 5 8 13

Nested For Loop

Pyramids

Prog.65: To print the following format** ** * ** * * * * * * * *

/* ** ** * ** * * * * * * * * */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=1;i<=5;i++){

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

printf(“* ”);}

printf(“\n”);}getch();

}

Output

** ** * ** * * * * * * * *Prog.66: To print the following format

11 21 2 31 2 3 4 1 2 3 4 5

/* 1

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 65: 1. Programming in ‘C’

1 21 2 31 2 3 4 1 2 3 4 5 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=1;i<=5;i++){

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

printf(“%d ”,j);}

printf(“\n”);}getch();

}

Output

11 21 2 31 2 3 4 1 2 3 4 5

Prog.67: To print the following format

12 23 3 34 4 4 4 5 5 5 5 5

/* 12 23 3 34 4 4 4 5 5 5 5 5 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=1;i<=5;i++){

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

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 66: 1. Programming in ‘C’

printf(“%d ”,i);}

printf(“\n”);}getch();

}

Output

12 23 3 34 4 4 4 5 5 5 5 5Prog.68: To print the following format

5 5 5 5 54 4 4 43 3 32 2 1

/* 5 5 5 5 54 4 4 43 3 32 2 1 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=5;i>=1;i--){

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

printf(“%d ”,i);}

printf(“\n”);}getch();

}

Output

5 5 5 5 54 4 4 43 3 32 2 1

Prog.69: To print the following format

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 67: 1. Programming in ‘C’

1 2 3 4 51 2 3 41 2 31 2 1

/* 1 2 3 4 51 2 3 41 2 31 21 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=5;i>=1;i--){

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

printf(“%d ”,j);}

printf(“\n”);}getch();

}

Output

1 2 3 4 51 2 3 41 2 31 21

Prog.70: To print the following format

1 1 1 1 12 2 2 23 3 34 4 5

/* 1 1 1 1 12 2 2 23 3 34 4 5 */

#include<stdio.h>#include<conio.h>void main()

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 68: 1. Programming in ‘C’

{int i,j;clrscr();for(i=1;i<=5;i++){

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

printf(“%d ”,i);}

printf(“\n”);}getch();

}

Output

1 1 1 1 12 2 2 23 3 34 4 5

Prog.71: To print the following format

5 4 3 2 15 4 3 25 4 35 4 5

/* 5 4 3 2 15 4 3 25 4 35 4 5 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=1;i<=5;i++){

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

printf(“%d ”,j);}

printf(“\n”);}getch();

}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 69: 1. Programming in ‘C’

Output

5 4 3 2 15 4 3 25 4 35 4 5

Prog.72: To print the following format

5 5 4 5 4 35 4 3 25 4 3 2 1

/* 5 5 4 5 4 35 4 3 25 4 3 2 1 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=5;i>=1;i--){

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

printf(“%d ”,j);}

printf(“\n”);}getch();

}

Output

5 5 4 5 4 3 5 4 3 2 5 4 3 2 1

Prog.73: To print the following format

5 4 3 2 15 4 3 25 4 35 4 5

/* 5

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 70: 1. Programming in ‘C’

4 43 3 32 2 2 2 1 1 1 1 1 */

#include<stdio.h>#include<conio.h>void main(){

int i,j;clrscr();for(i=5;i>=1;i--){

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

printf(“%d ”,i);}

printf(“\n”);}getch();

}

Output

5 4 4 3 3 32 2 2 2 1 1 1 1 1

While Loop

Prog.74 : To print the message 10 times.

/* Print a message 10 times */

#include<stdio.h>#include<conio.h>void main(){

int i=1;clrscr();while(i<=10){ printf(“\nMillennium Software Solutions”); i++;}getch();

}

Output

Millennium Software SolutionsMillennium Software SolutionsMillennium Software Solutions

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 71: 1. Programming in ‘C’

Millennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software SolutionsMillennium Software Solutions

Prog.75: To print 1 to 10 numbers.

/* Print 1 to 10 numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=1;clrscr();while(i<=10){ printf(“\n%d”,i); i++;}getch();

}

Output

12345678910

Prog.76: To print 1 to 10 even numbers.

/* Print even numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i=2;clrscr();while(i<=10){ printf(“\n%d”,i); i + =2;}getch();

}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 72: 1. Programming in ‘C’

Output246810

Prog.77: To print 1 to 10 odd numbers.

/* Print odd numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i=1;clrscr();while(i<=10){ printf(“\n%d”,i); i + =2;}getch();

}

Output13579

Prog.78: To calculate sum of 10 natural numbers.

/* Sum of first 10 natural numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=1,sum=0;clrscr();while(i<=10){ sum + = i; i++;}printf(“The sum of 10 natural numbers is:%d”,sum);getch();

}

Output

The sum of 10 natural numbers is:55

Prog.79: To calculate sum of even numbers below 10.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 73: 1. Programming in ‘C’

/* Sum of even numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i=2,sum=0;clrscr();while(i<=10){ sum = sum + i; i +=2;}printf(“The sum of even numbers is:%d”,sum);getch();

}

Output

The sum of even numbers is:30

Prog.80: To calculate sum of odd numbers below 10.

/* Sum of odd numbers below 10 */

#include<stdio.h>#include<conio.h>void main(){

int i=1,sum=0;clrscr();while(i<=10){ sum = sum + i; i +=2;}printf(“The sum of odd numbers is:%d”,sum);getch();

}Output

The sum of odd numbers is:25

Prog.81: To print 1 to n numbers.

/* Print 1 to n numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=1,n;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);while(i<=n){

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 74: 1. Programming in ‘C’

printf(“\n%d”,i); i++;}getch();

}

Output

Enter n value:512345

Prog.82: To print 1 to n even numbers.

/* Print 1 to n even numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=2,n;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);while(i<=n){ printf(“\n%d”,i); i +=2;}getch();

}

Output

Enter n value:152468101214

Prog.82: To print 1 to n odd numbers.

/* Print 1 to n odd numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=1,n;clrscr();printf(“Enter n value:”);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 75: 1. Programming in ‘C’

scanf(“%d”,&n);while(i<=n){ printf(“\n%d”,i); i + = 2;}getch();

}

Output

Enter n value:1513579111315

Prog.83: To calculate sum of 1 to n numbers

/* Sum of 1 to n numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=1,n,sum=0;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);while(i<=n){ sum + = i; i++;}printf(“Sum of first %d numbers is:%d”,n,sum);getch();

}

Output

Enter n value:5Sum of first 5 numbers is:15

Prog.84: To calculate 1 to n even numbers sum

/* Sum of 1 to n even numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=2,n,sum=0;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 76: 1. Programming in ‘C’

clrscr();printf(“Enter n value:”);scanf(“%d”,&n);while(i<=n){ sum + =i; i + =2;}

printf(“The sum of below %d even numbers is:%d”,n,sum);getch();

}

Output

Enter n value:10The sum of below 10 even numbers is:30

Prog.85: To calculate 1 to n odd numbers sum

/* Sum of 1 to n odd numbers */

#include<stdio.h>#include<conio.h>void main(){

int i=1,n,sum=0;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);while(i<=n){ sum + =i; i + = 2;}

printf(“The sum of below %d even numbers is:%d”,n,sum);getch();

}Output

Enter n value:10The sum of below 10 odd numbers is:25

Prog.86: To calculate factorial of first five natural numbers.

/* Factorial of five */

#include<stdio.h>#include<conio.h>void main(){

int i=1,fact=1;clrscr();while(i<=5){ fact * =i; i++;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 77: 1. Programming in ‘C’

}printf(“The factorial is:%d”,fact);getch();

}

Output

The factorial is:120

Prog.87: To calculate factorial of any number

/* Factorial of any number */

#include<stdio.h>#include<conio.h>void main(){

int i=1,n;long int fact =1;clrscr();printf(“Enter n value:”);scanf(“%d”,&n);while(i<=n){ fact * = i; i++;} printf(“Factorial is:%ld”,fact);getch();

}

Output

Enter n value:8Factorial is:40320

Prog.88: To check the input number is prime or not.

/* Prime or not*/

#include<stdio.h>#include<conio.h>void main(){

int n,status=0,i=2;clrscr();printf(“Enter a number:”);scanf(“%d”,&n);if(n==1)printf(“It is prime number”);else{ while(i<n) {

if(n%i == 0){

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 78: 1. Programming in ‘C’

status =1;break;

} i++; }}if(status == 0)printf(“It is prime number”);elseprintf(“It is not prime number”);getch();

}

Prog.89: To print Fibonacci series (1,1,2,3,5,8,13,…………)

/* Fibonacci Series */

#include<stdio.h>#include<conio.h>void main(){

int m;int n0,n1,n2,i=3;int count;clrscr();n0=1;n1=1;printf(“Enter the number of Fibonacci series:”);scanf(“%d”,&m);printf(“%d %d”,n0,n1);while(i<=m){

n2 = n0+n1;printf(“ %d”,n2);n0 = n1;n1 = n2;i++;

}getch();

}

Output

Enter the number of Fibonacci series: 71 1 2 3 5 8 13

do-while Loop:

Note: Do all above programs using do-while loop syntax.

Syn: initialization;

do{

statements;incre / decre;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 79: 1. Programming in ‘C’

}while(condition);

- x -

4. ARRAYS

4.1 Def: An Array is a collection of same data type. The elements of an array are

referred by a common name and are differentiate from one another by their position with

in an array. The elements of an array can be of any data type but all elements in an array

must be of the same type.

The general form of declaring a array is

type array_name[size];

where type is a valid datatype, array_name is the name of the array and size is the

number of elements that array_name contains.

Example:

int A[100],marks[20];float rates[50];char name[30];

int A[100];here int data type of elements that an arrayA name of array100 size of an array

The individual elements of an array can be referenced by means of its subscript (or index)Suppose A is an array of 20 elements, we can reference each element as

A[0] 1st elementA[1] 2nd element

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 80: 1. Programming in ‘C’

A[2] 3rd element::::A[19] 20th element

Note: Subscript enclosed within parenthesis.

In C subscript starts from 0. That is, if we declare an array of size n, then we can

refer the elements from 0 to (n-1)th element.

Generally Arrays are 3 types. They are

(i) Single Dimensional Array(ii) Double Dimensional Array(iii) Multi Dimensional Array

4.2 Single Dimensional Array

The general form of Single Dimensional array is:

datatype variable[size];

Example:

int A[20];

Initialization of arrays during declaration

Similar to other datatypes, the array also can be initialized at the time of declaration.

int num[5] ={3,2,1,5,4};char name[15] = {‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’,’s’};float rate[] = {20.5,15.75,12.34};

The following points can be noted regarding initialization of an array at the time of declaration:

1. The size of an array can be omitted in the declaration. If the size is omitted, then the compiler will reserve the memory location corresponds to number of individual elements that includes in the declaration.

2. If the array elements are not given any specific values, they are supposed to contain garbage values.

3. C will not allow to specify repetition of an initialization, or to initialize an ]element in the middle of an array without supplying all the preceding values.

The following program illustrates the Initialization of array

#include<stdio.h>#include<conio.h>void main(){

int a[5] = {4,3,2,1,5},i;clrscr();

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 81: 1. Programming in ‘C’

printf(“The elements in an array:”);for(i=0;i<=4;i++)printf(“%d\n”,i);getch();

}

Inserting elements into an array

#include<stdio.h>#include<conio.h>void main(){

int a[5],i;clrscr();printf(“Enter 5 elements into an array:”);for(i=0;i<=4;i++)scanf(“%d”,&a[i]);printf(“The 5 elements are:”);for(i=0;i<=4;i++)printf(“\n%d”,a[i]);getch();

}

4.3 Two-Dimensional Array

The general form of Two-Dimensional Arrays is

type array_name[row_size][column_size];

Example:

int a[2][2];

Initializing Two-Dimensional Arrays

Like the one-dimensional arrays, following their declaration with a list of initial values

enclosed in braces may initialize two-dimensional arrays. For example,

int a[2][2] ={1,2,5,4};

initializes the elements of the first row to zero and the second row to one. The

initialization is done row by row. The above statement can be equivalently written as

int a[2][2]={{1,2},{5,4}};

We can also initialize a two-dimensional array in the form of a matrix as shown below:

int a[2][2]= {{1,2},{5,4}

};

Program showing two-dimensional arrays

#include<stdio.h>

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 82: 1. Programming in ‘C’

#include<conio.h>void main(){int a[2][2],i,j;clrscr();printf(“Enter 4 elements into array:”);for(i=0;i<=1;i++){ for(j=0;j<=1;j++){scanf(“%d”,&a[i][j]);}}printf(“The 4 elements are:\n”);for(i=0;i<=1;i++){for(j=0;j<=1;j++){printf(“%d ”,a[i][j]);}printf(“\n”);}getch();}

5. Handling of Character Strings

As it was mentioned earlier character is stored internally as an integer. For

convenience the C compiler as well as the programmer treat certain values as characters

and manipulate them accordingly. Like an integer array, a group of characters can be

stored in a character array. These character arrays are often called strings. A string is

an array of characters. There is no string built-in data type in C. But we can declare

string as an array of characters. To recognize a character array, it should end with a null

character (‘\0’). For example, the string SCIENCE would be stored as

‘S’ ‘C’ ‘I’ ‘E’ ‘N’ ‘C’ ‘E’ ‘\0’The length of a string is the number of characters it contains excluding null

character. Hence, the number of locations needed to store a string is one more than

length of string.

In this example, the length of the string is 7. Since, the first null character in a

string is assumed to be the end of a string, more exactly the length of a string can be

defined as the number of non-null characters between the first character and first null

character in a string.

Declaring and initializing string variables

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 83: 1. Programming in ‘C’

The general form of declaration of string variable is

char string-name[size];

where, string-name is the name of a string and size is the maximum number of

characters the string-name can contain.

Example:char name[30];char designation[25];char date_of_join[8];

String variables can be initialized at the time of declaration.Example:char name[30] = “Millennium”;char designation[25] = “Computers”;

A string can also be initialized at the time of declaration in the following ways.char name[30] = “Millennium”;

orchar name[30] ={‘M’,’i’,’l’,’l’,’n’,’n’,’i’,’u’,’m’,’\0’};

orchar name[] = “Millennium”;

orchar name[] = {‘M’,’i’,’l’,’l’,’e’,’n’,’n’,’i’,’u’,’m’,’\0’};

Note that, when initialize a character array by listing its elements, we must explicitly

specify the null terminator. When a character string is assigned to a character array, C

adds the null character at the end of string automatically.

A two-dimensional array can be initialized to a list of strings. For example,

char day[7][15] = { “Monday”,“Tuesday”,“Wednesday”,“Thursday”,“Friday”,“Saturday”,“Sunday”

};

Reading and writing strings

The scanf(), printf() function is used with %s with format specification to read

and print a string.

Example:char str[30];scanf(“%s”,str);printf(“%s”,str);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 84: 1. Programming in ‘C’

In the case of reading strings, the ampersand (&) is not required before the string

variable name. As mentioned earlier, one of the limitations of the scanf() function is that

it is not capable of holding multiword strings, even though it can read them.

Example:#include<stdio.h>#include<conio.h>void main(){ char line[80]; clrscr(); printf(“Enter a line\n”); scanf(“%s”,line); printf(“The entered line is:%s”,line); getch();}

While executing this program, if you have typed asThis is a line

Then the output isThe entered line is: This

To overcome this type of situation, we can use gets() function in place of scanf()

function. Similarly puts() function can be used in place of printf() function.

The gets() function will continue to read and hold a string of input until it

encounters a new line character (‘\n’). It will replace the new line character with a null

character (‘\0’), thus creating a string. The above program can be written using gets() and

puts() function as….

#include<stdio.h>#include<conio.h>void main(){ char line[80]; clrscr(); printf(“Enter a line\n”); gets(line); puts(“The entered string is:”); puts(line); getch();}

5.1 String handling Functions: string.h

Every C compiler provides a large set of string handling library functions, which

are contained in the header file string.h

The following table shows some of the functions available in string.h header file.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 85: 1. Programming in ‘C’

Function

Meaning

strcat()

strlen()

strlwr()

strupr()

strcpy()

strcmp()

strrev()

String concatenate. Append one string to another. First character of string2

overwrites null character of string1.

Returns the length of the string not counting the null character.

Converts a string to lower case.

Converts a string to upper case.

Copies a string into another.

Compares two strings

Reverses a string.

Note: The functions deal with strings (a string of characters) ending with null character ‘\0’. To use these functions, including the following line in the program.

#include<string.h>5.2 strcat() function

The strcat() function concatenates the source string at the end of the target string.

For example “Computing” and “Techniques” on concatenation would result in string

“ComputingTechniques”. The general form is strcat(string1, string2); strong2 appends

to string1 and the first character to string2 overwrites null character of first string1. This

function returns the first argument i.e., string1. The string2 remains unchanged.

Example:#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char s1[30],s2[15]; clrscr(); printf(“Enter String1:”); gets(s1); printf(“Enter String2:”); gets(s2); printf(“The entire string is:%s”,strcat(s1,s2)); getch();}

Output

Enter String1:MillenniumEnter String2:Software SolutionsThe entire string is:MillenniumSoftware Solutions

5.3 strcmp() function:

strcmp(string1, string2);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 86: 1. Programming in ‘C’

strcmp() function compares two strings to find out whether they are same or

different. The two strings are compared character by character until there is a mismatch

or end of one of the strings is reached, whichever occurs first. If the two strings are

same, strcmp() returns a value 0. If they are not same, it returns the numeric difference

between the ASCII values of the first non-matching characters. That is, it returns less

than 0 if string1 is less than string2, and greater than 0 if string1 is greater than string2.

Example:

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char s1[25],s2[25]; int c; clrscr(); printf(“Enter string1:”); gets(s1); printf(“Enter string2:”); gets(s2); c=strcmp(s1,s2); if(c>0) printf(“String1 > String2”); else if(c<0) printf(“String2 > String1”); else printf(“Both are equal”); getch();}

Output

Enter String1:abcEnter String2:ABCString1 > String2

5.4 strcpy() function

strcpy(String1, String2);

The strcpy() function is used to copy the character string from String2 to String1.

This function returns the result string String1 the String2 remains unchanged. String2

may be a character array or a string constant.

Example:

#include<stdio.h>#include<conio.h>#include<string.h>void main()

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 87: 1. Programming in ‘C’

{ char s1[15],s2[15]; clrscr(); printf(“Enter String1:”) gets(s1); printf(“The String2 is:%s”,strcpy(s2,s1)); getch();}

Output

Enter String1:MillenniumThe String2 is:Millennium

5.5 strlen() function

This function counts the number of characters present in a string. The counting

ends at the first null character.

strlen (String1);The strlen() function returns the length of the argument String1 excluding the null

character. The argument may be a string constant.

Example:

#include<stdio.h>#include<conio.h>#include<string.h>void main(){ char str[30]; clrscr(); printf(“Enter a string:”); gets(str); printf(“The length of a string is:%d”,strlen(str)); getch();}

Output

Enter a string: Millennium Software SolutionsThe length of a string is:29

5.6 strupr(), strlwr(), strrev() functions

The strupr() function is converted the string into upper case and strlwr() function

is converted the string into lower case and strrev() function prints the entire string in

reverse order.

Example:

#include<stdio.h>#include<conio.h>#include<string.h>void main()

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 88: 1. Programming in ‘C’

{ char str[15]; clrscr(); printf(“Enter a string:”); gets(str); printf(“The upper case string is:%s”,strupr(str)); printf(“\nThe lower case string is:%s”,strlwr(str)); printf(“\nThe reverse string is:%s”,strrev(str)); getch();}

Output

Enter a string:millennium The upper case string is:MILLENNIUMThe lower case string is:millenniumThe reverse string is:muinnellim

6. Functions and Storage Classes

6.1 User-defined Functions

Functions are building blocks of C. Function performs the same set of instructions on

different sets of data or at different portions of a program. C functions can be classified

into two categories, namely library functions and user-defined functions. main is an

example of user-defined functions. printf and scanf belong to the category of library

functions. The main distinction between these two categories is that library functions are

not required to be written by us whereas a user-defined function has to be developed by

the user at the time of writing a program.

Advantages of user-defined functions:

1. It facilitates top-down modular programming as shown in fig. In this

programming style, the high level logic of the overall problem is solved first

while the details of each lower-level function are addressed later.

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

places. This factor is particularly critical with microcomputers where memory

space is limited.

3. As mentioned earlier, it is easy to locate and isolate a faulty function for further

investigations.

4. Many other programs may use a function. This means that a C programmer can

build on what others have already done, instead of starting over, from scratch.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Main Program

Function1 Function2 Function3 Function4 Function5

Page 89: 1. Programming in ‘C’

Function Declaration

Top-Down modular programming, using functions

The general form of C function is

Return-type Function-name (parameter list)

parameter declaration;

{

Body of function;

}

6.2 Features of Functions:

(a) Function Declaration and prototypes.

(b) Calling functions by value or by reference.

(c) Recursion

6.3 Category of functions:

A function, depending on whether arguments are present or not and whether a

value is returned or not, may belong to one of the following categories:

Category 1: Functions with no arguments and no return values.

Category 2: Functions with arguments and no return values.

Category 3: Functions with arguments and return values.

Example:

6.3.1 Functions with no arguments and nor return values

#include<stdio.h>#include<conio.h>void printline();void main(){

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 90: 1. Programming in ‘C’

Return Type

Function Name

Function Call

Called Function

clrscr(); printline(); printf(“This illustrates the use of C functions\n”); printline(); getch();}

void printline(){ int i; for(i=1;i<=40;i++) printf(“-”);printf(“\n”);}

6.3.2 Arguments but no Return values

#include<stdio.h>#include<conio.h>void swap(int,int);void main(){ int a,b; clrscr(); printf(“Enter 2 numbers:”); scanf(“%d%d”,&a,&b); swap(a,b); getch();}void swap(int x, int y){ int z; z = x; x = y; y = z;printf(“\nAfter swapping:%d,%d”,x,y);}

Actual arguments: The arguments mentioned in function call are called as “actual

arguments”. For example, in the function call statement swap(a,b), the two parameters a

and b are known as Actual parameters.

Formal arguments: The arguments in the function declaration are called as “Formal

arguments”. In the function definition swap(int x, int y), the parameters x and y are

known as Formal parameters.

6.3.3 Arguments with Return Values

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 91: 1. Programming in ‘C’

#include<stdio.h>#include<conio.h>int big(int,int);void main(){ int a,b,max; clrscr(); printf(“Enter 2 numbers:”); scanf(“%d%d”,&a,&b); max = big(a,b); printf(“\nThe biggest number is:%d”,max); getch();}int big(int x, int y){ if(x>y) return x; else return y;}

6.4 Recursion: Recursion is a technique to be used to call itself. In C, it is possible for

the functions to call themselves. A function is called recursive if a statement with in the

body of a function calls the same function itself.

Example:#include<stdio.h>#include<conio.h>long int fact(int);void main(){ int n; long int res; clrscr(); printf(“Enter a positive number:”); scanf(“%d”,&n); res = fact(n); printf(“The factorial is:%ld”,res); getch();}long int fact(int n){ long int f; if(n==1) return 1; else f = n*fact(n-1); return f;}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 92: 1. Programming in ‘C’

The following are important points about functions:

1. All C programs must contain atleast one function.[The main() function serves this rule]

2. A function can return only one value. Thus we should not specify two values to

return.

3. The return type in function declaration is optional. If no return type is specified it

is assumed to be an integer which is default.

4. When a function is not returning any value, void type can be used as return type.

5. Parameter list is optional.

6. ‘C’ provides a statement return

return expression

7. Return statement is used in function definition to communicate the return value to

the calling function.

8. Return statement indicates exit from the function and return to the point from

where the function was invoked.

9. There may be any number of return statements in function definition, but only one

return statement will activate in a function call.

10. The variable declarations within the function (between braces { }) are local to the

function and are not available outside the function.

11. If there is no return statement, the program will return to the calling point after it

reaches the end of the function body (}).

12. A function call can be used wherever a variable of same type is used (except the

left side of an assignment statement).

13. There should be one to one correspondence between the actual and formal

parameters in type, order and number.

14. C allows recursion. That is a function can call itself.

15. A C function cannot be defined in another function.

6.5 Functions with Arrays

Like the values of simple variables, it is also possible to pass the values of an array to a

function. To pass an array to a called function, it is sufficient to list the name of the

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 93: 1. Programming in ‘C’

array, without any subscripts, and the size of the array as arguments. For example, the

call

largest(a,n);will pass all the elements contained in the array a of size n. The called function expecting

this call must be appropriately defined. The largest function header might look like:

int largest(array,size);int array[];int size;

Program: Sorting of array elements

#include<stdio.h>#include<conio.h>void main(){ int i; int marks[5]; clrscr(); printf(“Enter 5 sub marks:”); for(i=0;i<=4;i++) scanf(“%d”,&marks[i]); printf(“\nMarks before sorting\n”); for(i=0;i<=4;i++) printf(“%d”,marks[i]); sort(marks,5); printf(“\nMarks after sorting\n”); for(i=0;i<=4;i++) printf(“%d”,marks[i]); getch();}void sort(int x[],int n){ int i,j,t; for(i=1;i<=n-1;i++) for(j=1;j<=n-1;j++) if(x[j-1] >= x[j]) { t = x[j-1]; x[j-1] = x[j]; x[j] = t; }}

6.6 Variables and Storage Classes: There are three basic places in a C program

where variables will be declared: inside the function, in the definition of function

parameters, or outside of all functions. These variables are called local variables, formal

parameters, and global variables respectively.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 94: 1. Programming in ‘C’

Local Variables: The body of any function comprises of two parts: declaration of

variables and a set of executable statements. Variables declared inside a function are

called local variables. This name derives from the fact that a variable inside a function

can be used only inside that function. An attempt on our part or access the local variable

of one function in another, will draw an error from the compiler: Identifier undefined.

Global Variables: C program consists of three sections namely: the preprocessor

directives, the global variable section and finally the functions. The variables that are

declared in the global variable section are called global variables. While a local variable

can be used only inside a function in which it is declared, a global variable can be used

anywhere in the program.

Block Variables: Yet another place to declare variables is inside any block: these

variables are called block variables and these can be used only inside that block.

Global Vs Local Variables:

There are a number of differences between global variables and local variables.

1. Local variables can be used only inside the function or the block in which they are

declared. On the other hand, global variables can be used throughout the

program.

2. The rules of initialization differ. All global variables, in the absence of explicit

initialization, are automatically initialized. A global int variable begins with the

value 0, a global float gets initialized to 0.0, a global char holds the ASCII null

byte, and a global pointer points to NULL. As against this, local variables do not

get initialized to any specified value, when a value is not provided. Thus a local

variable begins with an unknown value, which may be different each time.

3. Global variables get initialized only once, before the program starts executing.

But, local variables get initialized each time the function or block containing their

declaration is entered.

4. The initial value that you supply for a global variable must be a constant, whereas

a local variable can contain variables in its initializer.

5. A local variable loses its value, the moment the function/block containing it is

exited. Global variables retain their values throughout their execution.

Storage classes:

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 95: 1. Programming in ‘C’

The storage class of a variable dictates how, when and where storage will be

allocated for the variable. The different storage classes available are:

1. Auto 2. Register 3. Extern 4. Static1. Auto: Automatic variables are declared inside a function in which they are to be

utilized. They are created when the function is called and destroyed automatically

when the function is exited, hence the name automatic. Automatic variables are

therefore private (or local) to the function in which they are declared. Because of

this property, automatic variables are also refereed to as local or internal

variables.

A variable declared inside a function without storage class specification is, by

default, an automatic variable.

One important feature of automatic variables is that their value cannot be changed

accidentally by what happens in some other function in the program. This assures

that we may declare and use the same variable name in different functions in the same

program without causing any confusion to the compiler.

Program: ILLUSTRATION OF WORKING OF auto VARIABLES

#include<stdio.h>#include<conio.h>void function1();void function2();void main(){ int m = 1000; clrscr(); function2(); printf(“%d\n”,m); getch();}void function1(){ int m = 10; printf(“%d\n”,m);}void function2(){ int m = 100; function1(); printf(“%d\n”,m);}

2. Register: It is possible for use to attribute the register storage class to certain

variables. We can tell the compiler that a variable should be kept in one of the

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 96: 1. Programming in ‘C’

machine’s registers, instead of keeping in the memory (where normal variables

are stored). Since a register access is much faster than a memory access, keeping

the frequently accessed variables in the register will lead to faster execution of

programs. This is done as follows:

register int count;

The important point while using register variables is, registers of CPU do not have

addresses. Thus, we should not refer the address of a register variable.

For example,The following statement will result an error.

register int i;scanf(“%d”,&i);

Example:#include<stdio.h>#include<conio.h>void main(){ register int count; int sum; clrscr(); for(count=0;count<10;count++) sum = sum + count; printf(“The sum is:%d”,sum); getch();}

3. Extern: This is the default storage class for all global variables. Extern storage

class variables get initialized (to zero in the case of integers) automatically, retain

their value throughout the execution of the program and can be shared by

different modules of the same program. However, assuming “int intvar;”is

present in a.c., to be also to have proper binding with the same variable, b.c

(another file) should have “extern int intvar”.

Example:a.c file b.c file

#include<stdio.h> float f = 84.237;#include<conio.h> extern int intvar;int intvar; funct(char c, int intvar)extern float f; {void main() char c1,c2;{ :char ch; :funct(ch,intvar); }

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 97: 1. Programming in ‘C’

printf(“%f”,f);getch();}

If we intend to share a variable say f, between a.c and b.c files, f must be declared

in both files. Note that it is qualified as extern in a.c file. The extern qualifier indicated

the compiler that f is a variable of type float for which no memory needs to be allocated

and it will be allocated elsewhere. Note that if a variable is declared as extern, it must

appear as global variable once in another source file.

4. Static: The static storage class has a number of implications depending upon its usage.

(a) The default storage class for all local variables is auto. This can be changed to static by prefixing the declaration with the keyword static as in static int intvar. A local variable with static storage class is still a local variable as far as its scope is concerned, it is still available only inside the function in which it is declared. But certain other properties of the variable change; It gets initialized to zero automatically, is initialized only once, (during program startup) and it retains its value throughout the execution of the program.

(b) When applied to a global variable, the global variable becomes inaccessible outside the file in which it is declared.

(c) This storage class can be applied to functions too. Similar to case 2, the functions become inaccessible outside the file.

Example:#include<stdio.h>#include<conio.h>void main(){ function1( ); function1( ); function1( ); getch();}void function1(){ static int n; n++; printf(“\nThe value of n is:%d”,n);}The output of above program is

The value of n is 1The value of n is 2The value of n is 3

Note that the static variable is initialized to zero automatically.Test the above program without the keyword static to understand the static storage class

clearly.

Storage class

Type Default initialvalue

Wheredeclared

Scope Life Storage

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 98: 1. Programming in ‘C’

Autoor

noneLocal

An unpredictable value, which is often called a garbage value

within the function or block

only within the function / block where it is declared

until function block is no longer active

Memory

Register Local Garbage value within the function or block

only within the function / block where it is declared

until function block is no longer active

CPU registers

Static Local Zero within the function or block

only within the function / block where it is declared

until program ends, value of the variable persists between different function calls

Memory

Extern Global Zero A heat of all functions within a file

All files including other files where declared extern

While any of these files are active. That is, as long as the program’s execution doesn’t come to an end

Memory

-x -

7. Structures and Unions7.1 INTRODUCTION

We seen that arrays can be used to represent a group of data items that belong to the same

type, such as int or float. However, if we want to represent a collection of data items of

different types using a single name, then we cannot use an array. Fortunately, C supports

a constructed data type known as structure, which is a method for packing data of

different types. A structure is a convenient tool for handling a group of logically

related data items. These fields are called structure elements or members.

7.2 Declaring A Structure

The general form of a structure declaration statement is given below:

struct <structure name>{ structure element1; structure element2; structure element3; ………. ……….}

Example:

struct book{ char name[20]; char author[15]; int pages; float price;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 99: 1. Programming in ‘C’

}Note that the above declaration has not declared any variables. It simply

describes a format called template to represent information.

We can declare structure variables using the tag name anywhere in the program.

For example, the statement

struct book book1, book2,book3;

declares book1, book2, book3 as variables of type struct book.

It is also allowed to combine both the template declaration and variables

declaration in one statement. The declaration

struct book{ char name[20]; char author[15]; int pages; float price;}book1,book2,book3;

is valid. The use of tag name is optional. For example,struct { char name[20]; char author[15]; int pages; float price;

}book1,book2,book3;

declares book1, book2, book3 as structure variables representing three books, but does

not include a tag name for later use in declarations.

Note the following points while declaring a structure type:

(a) The closing brace in the structure type declaration must be followed by a

semicolon.

(b) It is important to understand that a structure type declaration does not tell the

compiler to reserve any space in memory. All a structure declaration does is, it

defines the ‘form’ of the structure.

(c) Usually structure type declaration appears at the top of the source code file, before

any variables or functions are defined.

7.3 ACCESSING STRUCTURES ELEMENTS

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 100: 1. Programming in ‘C’

We can assign values to the members of a structure in a number of ways. As mentioned

earlier, the members themselves are not variables. They should be linked to the structure

variables in order to make them meaningful members. The link between a member and a

variable is established using the member operator ‘.’ Which is also known as ‘dot

operator’ or ‘period operator’. The general form is

Structure-Variable. Structure-Member;For example,

book1.price;

We can also use scanf to give the values through the keyboard.

scanf(“%s”,book1.name);scanf(“%d”,&book1.pages);

are valid input statements.

Example:

Program: Defining and Assigning Values to Structure Members#include<stdio.h>#include<conio.h>struct personal{ char name[20]; int day; char month[10]; int year; float salary;};void main(){ struct personal person; clrscr(); printf(“Input values\n”); scanf(“%s%d%s%d%f”,person.name, &person.day, person.month,

&person.year, &person.salary); printf(“%s %d %s %d,%.2f\n”,person.name,person.day,

person.month,person.month,person.year,person.salary); getch();}

Output

Input Values

Mahesh 15 February 1982 5000Mahesh 15 February 1982 5000.00

7.4 ARRAYS OF STRUCTURES

We use structures to describe the format of a number of related variables. For example,

in analyzing the marks obtained by a class of students, we may use a template to describe

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 101: 1. Programming in ‘C’

student name and marks obtained in various subjects and then declare all the students as

structure variables. In such cases, we may declare an array of structures, each element of

the array representing a structure variable. For example,

struct class student[100];

defines an array called student, that consists of 100 elements. Each element is defined to

be of the type struct class. Consider the following declaration:

struct marks{ int sub1; int sub2; int sub3;}s[5];

Program: Usage of an array of structures#include<stdio.h>#include<conio.h>struct book{ char name[15]; float price; int pages;}b[3];void main(){ int i; clrscr(); printf(“Enter name, price and pages(3 records):”); for(i=0;i<=2;i++) scanf(“%s %f %d”,b[i].name,&b[i].price,&b[i].pages); printf(“\nThe details are:\n”); printf(“name\tprice\tpages”); for(i=0;i<=2;i++) printf(“\n%s %f %d”,b[i].name,b[i].price,b[i].pages); getch();}linkfloat(){ float a=0,*b; b = &a; a = *b;}

Now a comment about the program

What is the function linkfloat() doing here? If you don’t define it you are bound to get

the error “Floating Point Formats Not linked” with majority of C compilers. What

causes this error to occur? When parsing our source file, if the compiler encounters a

reference to the address of a float, it sets a flag to have the linker link in the floating-point

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 102: 1. Programming in ‘C’

emulator. A floating point emulator is used to manipulate floating point numbers in

runtime library functions like scanf().

7.5 ARRAYS WITHIN STRUCTURES

C permits the use of arrays as structure members. We have already used arrays of

characters inside a structure. Similarly, we can use single-or multi-dimensional arrays of

type int or float. For example, the following structure declaration is valid:

struct marks{ int number; float sub[3];}s[2];

7.6 STRUCTURES WITHIN STRUCTURES

Structures within a structure means nesting of structures. Nesting of structures is

permitted in C. Let us consider the following structure definition:

struct salary{ char name[20]; char dept[10]; struct { int dearness; int house_rent; int city; }allowance;}employee;

The salary structure contains a member named allowance which itself is a structure with

three members. The members contained in the inner structure namely dearness,

house_rent, and city can be referred to as

employee.allowance.dearnessemployee.allowance.house_rentemployee.allowance.city

7.7 STRUCTURES AND FUNCTIONS

We know that the main philosophy of C language is the use of the functions. Therefore,

it is natural that C supports the passing of structure values as arguments to functions.

There are three methods by which the values of a structure can be transferred from one

function to another.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 103: 1. Programming in ‘C’

The first method is to pass each member of the structure as an actual argument of

the function call. The actual arguments are then treated independently like ordinary

variables. This is the most elementary method and becomes unmanageable and

inefficient when the structure size is large.

The second method involves passing of a copy of the entire structure to the called

function. Since the function is working on a copy of the structure, any changes to

structure members within the function are not reflected in the original structure (in the

calling function). It is, therefore, necessary for the function to return the entire structure

back to the calling function. All compilers may not support this method of passing the

entire structure as a parameter.

The third approach employs a concept pointers to pass the structure as an

argument. In this case, the address location of the structure is passed to the called

function. The function can access indirectly the entire structure and work on it. This is

similar to the way arrays are passed to functions. This method is more efficient as

compared to the second one.

In this section, we discuss in detail the second method, while the third approach

using pointers is discussed in the next chapter, where pointers are dealt in detail.

The general format of sending a copy of a structure to the called function is:

Function_Name (structure variable name)

The called function takes the following form:

data_type function_name(st_name)struct_type st_name;{

………………return(expression);

}

The following points are important to note:

1. The called function must be declared for its type, appropriate to the data type it is

expected to return. For example, if it is returning a copy of the entire structure,

then it must be declared as struct with an appropriate tag name.

2. The structure variable used as the actual argument and the corresponding formal

argument in the called function must be of the same struct type.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 104: 1. Programming in ‘C’

3. The return statement is necessary only when the function is returning some data.

The expression may be any simple variable or structure variable or an expression

using simple variables.

4. When a function returns a structure, it must be assigned to a structure of identical

type in the calling function.

5. The called function must be declared in the calling function for its type, if it is

placed after the calling function.

Example:

Program: STRUCTURE AS FUNCTION PARAMETERS

#include<stdio.h>#include<conio.h>struct stores{ char name[20]; float price; int quantity;};struct stores update(struct stores,float,int);float mul(struct stores);void main(){ float p_increment, value; int q_increment; static struct stores item={“XYZ”,25.75,12}; clrscr(); printf(“\nInput increment values:”) ; printf(“price increment and quantity increment\n”); scanf(“%f%d”,&p_increment,&q_increment); item = update(item,p_increment,q_increment); printf(“\nUpdate values of item”); printf(“\n\nName:%s”,item.name); printf(“\nPrice:%.2f”,item.price); printf(“\nQuantity:%d”,item.quantity); value = mul(item); printf(“\nValue of the item=%.2f”,value); getch();}struct stores update(struct stores product, float p, int q){ product.price+=p; product.quantity+=q; return(product);}float mul(struct stores stock)

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 105: 1. Programming in ‘C’

{ return stock.price*stock.quantity;}

7.8 UNIONS

Unions are a concept borrowed from structures and therefore follow the same syntax as

structures. However, there is major distinction between them in terms of storage. In

structures, each member has its own storage location, whereas all the members of a union

use the same location. This implies that, although a union may contain many members of

different types, it can handle only one member at a time. Like structures, a union can be

declared using the keyword union as follows:

union item{ int m; float x; char c;}code;

7.9 SIZE OF STRUCTURES

We normally use structures, unions, and arrays to create variables of large sizes. The

actual size of these variables in terms of bytes may change from machine to machine.

We may use the unary operator sizeof to tell us the size of a structure (or any variable).

The expression

sizeof(struct x)

will evaluate the number of bytes required to hold all the members of the structure x. If y

is a simple structure variable of type struct x, then the expression

sizeof(y)would also give the same answer.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 106: 1. Programming in ‘C’

- x -

8. Pointers

8.1 INTRODUCTION Pointers are another important feature of C language. They are a

powerful tool and handy to use once they are mastered. There are a number of reasons

for using pointers.

1. A pointer enables us to access a variable that is defined outside the function.

2. Pointers are more efficient in handling the data tables.

3. Pointers reduce the length and complexity of a program.

4. They increase the execution speed.

5. The use of a pointer array to character strings results in saving of data storage

space in memory.

8.2 ACCESSING THE ADDRESS OF A VARIABLE

The actual location of a variable in the memory is system dependent and therefore, the

address of a variable is not known to us immediately. We can determine the address of

the variable with the help of the operator & in C. We have already seen the use of this

address operator in the scanf function. The operator & immediately preceding a variable

returns the address of the variable associated with it. For example,

p = &quantity;

would assign the address to the variable p. The & operator can be remembered as

‘address of’.

Example: Accessing Addresses of variables

#include<stdio.h>#include<conio.h>

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 107: 1. Programming in ‘C’

void main(){ char a; int x; float p, q; clrscr(); a = ‘A’; x = 125; p = 10.25, q = 18.76; printf(“%c is stored at address %u”, a, &a); printf(“\n%d is stored at address %u”, x, &x); printf(“\n%f is stored at address %u”, p, &p); printf(“\n%f is stored at address %u”, q, &q); getch();}

8.3 DECLARING AND INITIALIZING POINTERS

In C, every variable must be declared for its type. Since pointer variables contain

addresses that belong to a separate data type, they must be declared as pointers before we

use them. The declaration of a pointer variable takes the following form:

datatype *pt_name;

This tells the compiler three things about the variable pt_name.

1. The asterisk (*) tells the variable pt_name is a pointer variable.

2. pt_name needs a memory location.

3. pt_name points to a variable of type datatype.

For example,int *p;

declares the variable p as a pointer variable that points to an integer data type.

Remember that the type int refers to the data type of the variable being pointed to by p

and not the type of the value of the pointer. Similarly, the statement

float *x;

declares x as a pointer to a floating point variable.Once a pointer variable has been declared, it can be made to point to a variable using an

assignment statement such as

p = &quantity;

which causes p to point to quantity. That is, p now contains the address of quantity. This

is known as pointer initialization. Before a pointer is initialized, it should not be used.

A pointer variable can be initialized in its declaration itself. For example,

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 108: 1. Programming in ‘C’

int x, *p=&x;

is perfectly valid. It declares x as an integer variable and p as a pointer variable and then

initializes p to the address of x. Note carefully that this is an initialization of p, not *p.

And also remember that the target variable x is declared first. The statement

int *p=&x, x;is not valid.

8.4 ACCESSING A VARIABLE THROUGH ITS POINTER

Once a pointer has been assigned the address of a variable, the question remains as to

how to access the value of the variable using the pointer. This is done by using another

unary operator * (asterisk), usually known as the indirection operator. Consider the

following statements:

int quantity, *p, n;quantity = 179;p = &quantity;n = *p;

The first line declares quantity and n as integer variables and p as a pointer variable

pointing to an integer. The second line assigns the value 179 to quantity and the third

line assigns the address of quantity to the pointer variable p. The fourth line contains the

indirection operator *. When the operator * is placed before a pointer variable in an

expression, the pointer returns the value of the variable of which the pointer value is the

address. In this case, *p returns the value of the variable quantity, because p is the

address of quantity. The * can be remembered as ‘value of address’. Thus the value of

n would be 179.

Example: Program to illustrate the use of indirection operator ‘*’#include<stdio.h>#include<conio.h>void main(){ int x, y; int *ptr; clrscr(); x = 10; ptr = &x; y = *ptr; printf(“Value of x is %d”,x); printf(“\n%d is stored at address %u”, x, &x); printf(“\n%d is stored at address %u”, *&x , &x); printf(“\n%d is stored at address %u”, *ptr, ptr); printf(“\n%d is stored at address %u”, y, &*ptr); printf(“\n%d is stored at address %u”, ptr, &ptr);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 109: 1. Programming in ‘C’

printf(“\n%d is stored at address %u”, y, &y); getch();}

Example: Arithmetic operations on Pointers#include<stdio.h>#include<conio.h>void main(){ int a, b, *p1, *p2; clrscr(); a = 4; b = 2; p1 = &a; p2 = &b; printf(“\n Sum = %d”,*p1 + *p2); printf(“\n Sub = %d”,*p1 - *p2); printf(“\n Mul = %d”,*p1 * *p2); printf(“\n Div = %d”,*p1 / *p2); printf(“\n Rem = %d”,*p1 % *p2); getch();}

8.5 POINTERS AND ARRAYS

When an array is declared, the compiler allocates a base address and sufficient amount of

storage to contain all the elements of the array in contiguous memory locations. The base

address is the location of the first element (index 0) of the array. The compiler also

defines the array name as a constant pointer to the first element.

If we declare p as an integer pointer, then we can make the pointer p to point to the array

x by the following assignment:

p = x;This is equivalent to

p = &x[0];When handling arrays, instead of using array indexing, we can use pointers to access

array elements. Note that *(p+3) gives the value of x[3]. The pointer accessing method

is much faster than array indexing.

Example: Pointers in one-dimensional array#include<stdio.h>#include<conio.h>void main(){ int *p, sum=0,i; clrscr(); printf(“Enter 5 elements:”); for(i=0;i<=4;i++) scanf(“%d”,*(p+i)); for(i=0;i<=4;i++) sum = sum + *p;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 110: 1. Programming in ‘C’

printf(“\nThe sum is:%d”,sum); getch();}

Pointers can be used to manipulate two-dimensional arrays as well. We know that in a

one-dimensional array x, the expression

*(x + i) or *( p + i)

represents the element x[i]. Similarly, an element in a two-dimensional array can be

represented by the pointer expression as follows:

*(*(a+i)+j) or *(*(p+i)+j)

8.6 DYNAMIC MEMORY ALLOCATION

C language requires the number of elements in an array to be specified at compile time.

But we may not be able to do so always. Our initial judgment of size, if it is wrong, may

cause failure of the program or wastage of memory space.

Many languages permit a programmer to specify an array’s size at run time. The

process of allocating memory at run time is known as dynamic memory allocation. In C

language there are four library routines known as “memory management functions” that

can be used for allocating and freeing memory during program execution.

Memory Allocation Functions

Function

Task

malloc Allocates requested size of bytes and returns a pointer to the first byteof the allocated space.

calloc Allocates space for an array of elements, initializes them to zero and thenreturns a pointer to the memory.

Free Frees previously allocated space.realloc Modifies the size of previously allocated space.Allocating a Block of Memory

A block of memory may be allocated using the function malloc. The malloc

function reserves a block of memory of specified size and returns a pointer of type void.

This means that we can assign it to any type of pointer. It takes the following form:

ptr = (datatype *)malloc(byte-size);

ptr is a pointer of type datatype. The malloc returns a pointer (of datatype) to an area of

memory with size byte-size.

Example:x = (int *) malloc (sizeof(int) * n);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 111: 1. Programming in ‘C’

Note: In above example n is always a numeric.

Example: Use of malloc Function#include<stdio.h>#include<conio.h>void main(){ int *p, n, i; clrscr(); printf(“Enter n value:”); scanf(“%d”,&n); p = (int) malloc(sizeof(int)*n); printf(“\nEnter %d numbers:”,n); for(i=0;i<n;i++) scanf(“%d”,*(p+i)); printf(“\nThe numbers are:”); for(i=0;i<n;i++) printf(“\n%d”,*(p+i)); getch();}

Allocating Multiple Blocks of Memory

calloc is another memory allocation function that is normally used for requesting memory

space at run time for storing derived data types such as arrays and structures. While

malloc allocates a single block of storage space, calloc allocates multiple blocks of

storage, each of the same size, and then sets all bytes to zero. The general form of calloc

is:

ptr = (datatype *) calloc (n,elem-size);

The above statement allocates contiguous space for n blocks, each of size elem-size bytes.

All bytes are initialized to zero and a pointer to the first byte of the allocated region is

returned. If there is not enough space, a NULL pointer is returned.

Releasing the Used Space

Compile-time storage of a variable is allocated and released by the system in accordance

with its storage class. With the dynamic run-time allocation, it is our responsibility to

release the space when it is not required. The release of storage space becomes important

when the storage is limited. We may release that block of memory for future use, using

the free function:

free(ptr);

ptr is a pointer to a memory block which has already been created by malloc or calloc.

Altering the Size of a Block

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 112: 1. Programming in ‘C’

It is likely that we discover later, the previously allocated memory is not sufficient and

we need additional space for more elements. It is also possible that the memory allocated

is much larger than necessary and we want to reduce it. In both the cases, we can change

the memory size already allocated with the help of the function realloc. This process is

called the reallocation of memory. For example, if the original allocation is done by the

statement

ptr = malloc(size);

then reallocation of space may be done by the statement

ptr = realloc(ptr, newsize);

8.7 POINTERS AND CHARACTER STRINGS

We know that a string is an array of characters, terminated with a null character. Like in

one-dimensional arrays, we can use a pointer to access the individual characters in a

string.

Example: Pointers and Character Strings#include<stdio.h>#include<conio.h>void main(){ char *str; int i=0; clrscr(); printf(“Enter a string:”); gets(str); while(*str!=’\0’) { i++; str++; } printf(“\nThe length is:%d”,i); getch();}

8.8 POINTERS AND FUNCTIONS

In functions we can pass the duplicate values for the actual parameters, but we can pass

the address of a variable as an argument to a function in the normal fashion. When we

pass addresses to a function, the parameters receiving the addresses should be pointers.

The process of calling a function using pointers to pass the addresses of variable is

known as call by address.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 113: 1. Programming in ‘C’

Example: Pointers as function Parameters#include<stdio.h>#include<conio.h>void main(){ int a,b; clrscr(); printf(“Enter 2 numbers:”); scanf(“%d %d”,&a,&b); printf(“\nBefore exchange: a=%d, b=%d”,a, b); swap(&a,&b); printf(“\nAfter exchange: a=%d, b=%d”,a, b); getch();}void swap(int *x, int *y){ int z; z = *x; *x = *y; *y = z;}

8.9 POINTERS AND STRUCTURES

We know that the name of an array stands for the address of its zeroth element. The same

thing is true of the names of arrays of structure variables. Suppose product is an array

variable of struct type. The name product represents the address of its zeroth element.

Consider the following declaration:

struct inventory{ char name[30]; int number;}product[3], *ptr;

Example: Pointers to Structure variables#include<stdio.h>#include<conio.h>struct invent{ char name[20] ; int number;}product[3], *ptr;void main(){ clrscr(); printf(“INPUT\n\n”); printf(“Enter name and number(3 records):”); for(ptr = product;ptr<product+3;ptr++) scanf(“%s %d”,ptr->name,&ptr->number); printf(“\n\nOUTPUT”); for(ptr = product;ptr<product+3;ptr++) printf(“\n%s\t%d”,ptr->name,ptr->number); getch();

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 114: 1. Programming in ‘C’

}

8.10 DYNAMIC MEMORY ALLOCATION

We may also use malloc to allocate space for complex data types such as

structures. Example:

st_var = (struct store *)malloc(sizeof(struct store));

where st_var is a pointer of type struct store.

9. File Management in C9.1 INTRODUCTION

A file is a place on the disk where a group of related data is stored. Like most other

languages, C supports a number of functions that have the ability to perform basic file

operations, which include:

Naming a file,

Opening a file,

Reading data from a file,

Writing data to a file, and

Closing a file.

High level I/O functions

Function Name Operation

fopen() Creates a new file for useOpens an existing file for use.

fclose() Closes a file which has been opened for use.Getc() Reads a character from a file.putc() Writes a character to a file.fprintf() Writes a set of data values to a file.fscanf() Reads a set of data values from a file.getw() Reads an integer from a file.putw() Writes an integer to file.fseek() Sets the position to a desired point in the fileFtell() Gives the current position in the filerewind() Sets the position to the beginning of the file.

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 115: 1. Programming in ‘C’

9.2 DEFINING AND OPENING A FILE

If we want to store data in a file in the secondary memory, we must specify certain things

about the file, to the operating system. They include:

1. Filename.

2. Data Structure.

3. Purpose.

Following is the general format for declaring and opening a file:

FILE *fp;fp = fopen(“filename”, “mode”);

The first statement declares the variable fp as a “pointer to the data type FILE”. As

stated earlier, FILE is a structure that is defined in the I/O library. The second statement

opens the file named filename and assigns as identifier to the FILE the pointer fp. This

pointer which contains all the information about the file is subsequently used as a

communication link between the system and the program.

The second statement also specifies the purpose of opening this file. The mode

does this job. Mode can be one of the following:

r open the file for reading only.

w open the file for writing only.

a open the file for appending (or adding) data to it.

Note that both the filename and mode are specified as strings. They should be enclosed

in double quotation marks.

When trying to open a file, one of the following things may happen:

1. When the mode is ‘writing’ a file with the specified name is created if the file

does not exist. The contents are deleted, if the file already exists.

2. When the purpose is ‘appending’, the file is opened with the current contents safe.

A file with the specified name is created if the file does not exist.

3. If the purpose is ‘reading’, and if it exists, then the file is opened with the current

contents safe; otherwise an error occurs.

Consider the following statements:

FILE *p1, *p2;p1 = fopen(“data”,”r”);p2 = fopen(“results”,”w”);

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 116: 1. Programming in ‘C’

Many recent compilers include additional modes of operation. They include:

r+ The existing file is opened to the beginning for both reading and writing.w+ Same as w except both for reading and writinga+ Same as a except both for reading and writing.

We can open and use a number of files at a time. This number however depends on the

system we use.

9.3 CLOSING A FILE

A file must be closed as soon as all operations on it have been completed. The general

form is:

fclose(file_pointer);

9.4 INPUT/OUTPUT OPERATIONS ON FILES

Once a file is opened, reading out of or writing to it is accomplished using the standard

I/O routines that are listed.

The getc and putc Functions

The simplest file I/O functions are getc and putc. These are analogous to getchar and

putchar functions and handle one character at a time. Assume that a file is opened with

mode w and file pointer fp1. Then, the statement

putc(c, fp1);

writes the character contained in the character variable c to the file associated with FILE

pointer fp1. Similarly, getc is used to read a character from a file that has been opened in

read mode. For example, the statement

c = getc(fp2);

would read a character from the file whose file pointer is fp2.The file pointer moves by one character position for every operation of getc or

putc. The getc will return an end-of-file marker EOF, when end of the file has been

reached. Therefore, the reading should be terminated when EOF is encountered.

Example: Writing to and Reading from a File#include<stdio.h>#include<conio.h>void main(){ FILE *f1; char c; clrscr();

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 117: 1. Programming in ‘C’

printf(“Data Input\n\n”); f1 = fopen(“INPUT”, “w”); while((c=getchar()!=EOF) putc(c,f1); fclose(f1); printf(“\nData Output\n\n”); f1 = fopen(“INPUT”,”r”); while((c=getc(f1))!=EOF) printf(“%c”,c); fclose(f1); getch();}

9.5 The fprintf and fscanf Functions

So far, we have seen functions which can handle only one character or integer at a time.

Most compilers support two other functions, namely fprintf and fscanf, that can handle a

group of mixed data simultaneously.

The functions fprintf and fscanf perform I/O operations that are identical to the

familiar printf and scanf functions, except of course that they work on files. The first

argument of these functions is a file pointer which specifies the file to be used. The

general form of fprintf is

fprintf(fp, “control string”, list);

where fp is a file pointer associated with a file that has been opened for writing. The

control string contains output specifications for the items in the list. The list may include

variables, constants and strings. Example:

fprintf(f1, “%s %d %f”,name,age,7.5);

Here, name is an array variable of type char and age is int variable.

The general format of fscanf is

fscanf(fp, “control string”, list);This statement would cause the reading of the items in the list from the file specified by

fp, according to the specifications contained in the control string. Example:

fscanf(f2, “%s %d”, item, &quantity);

Like scanf, fscanf also returns the number of items that are successfully read. When the

end of file is reached, it returns the value of EOF.

Example: Handling of files with mixed Data Types

#include<stdio.h>#include<conio.h>void main(){ FILE *fp;

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 118: 1. Programming in ‘C’

int number, quantity, i; float price, value; char item[10], filename[10]; clrscr(); printf(“Input file name\n”); scanf(“%s”,filename); fp = fopen(filename, “w”); printf(“Input inventory data\n\n”); printf(“Enter Item name, Number, price and quantity (3 records):\n”); for(i=1;i<=3;i++) { fscanf(stdin, “%s %d %f %d”,item, &number, &price, &quantity); fprintf(fp, “%s %d %.2f %d”, item, number, price, quantity); } fclose(fp); fprintf(stdout, “\n\n”); fp = fopen(filename, “r”); printf(“Item name Number price quantity value\n”); for(i=1;i<=3;i++) { fscanf(fp, “%s %d %f %d”,item, &number, &price, &quantity); value = price * quantity; fprintf(stdout, “%-8s %7d %8.2f %8d %11.2f\n”,item, number, price, quantity, value);} fclose(fp); getch();}

9.6 COMMAND LINE ARGUMENTS

What is a command line argument? It is a parameter supplied to a program when the

program is invoked. This parameter may represent a filename the program should

process. For example, if we want to execute a program to copy the contents of a file

named X_FILE to another one named Y_FILE, then we may use a command line like

C:\TC>PROGRAM X_FILE Y_FILE

PROGRAM is the filename where the executable code of the program is stored. This

eliminates the need for the program to request the user to enter the filenames during

execution. How do these parameters get into the program?

We know that every C program should have one main function and that it marks

the beginning of the program. But what we have not mentioned so far is that it can also

take arguments like other functions. In fact main can take two arguments called argc

and argv and the information contained in the command line is passed on to the program

through these arguments, when main is called up by the system.

The variable argc is an argument counter that counts the number of arguments on

the command line. The argv is an argument vector and represents an array of character

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 119: 1. Programming in ‘C’

pointers that point to the command line arguments. The size of this array will be equal to

the value of argc. For instance, for the command line given above, argc is three and

argv is array of three pointers to strings as shown below:

argv[0] PROGRAMargv[1] X_FILEargv[2] Y_FILE

In order to access the command line arguments, we must declare the main

function and its parameters as follows:

main(argc,argv);int argc;char *argv[];

The first parameter in the command line is always the program name and

therefore argv[0] always represents the program name.

Example: Command line Arguments

#include<stdio.h>#include<conio.h>void main(argc,argv)int argc;char *argv[];{ FILE *fp; int i; char word[15]; clrscr(); fp = fopen(argv[1],"w"); printf("\nNo.of arguments in Command line=%d\n\n",argc); for(i=2;i<argc;i++) fprintf(fp,"%s",argv[i]); fclose(fp);

printf("Contents of %s file\n\n",argv[1]); fp=fopen(argv[1],"r"); for(i=2;i<argc;i++) { fscanf(fp,"%s",word); printf("%s",word); } fclose(fp); printf("\n\n"); for(i=0;i<argc;i++) printf("%*s\n",i*5,argv[i]); getch();}

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam

Page 120: 1. Programming in ‘C’

- x -

MILLENNIUM SOFTWARE SOLUTIONS Visakhapatnam