• No results found

C Notes

N/A
N/A
Protected

Academic year: 2021

Share "C Notes"

Copied!
132
0
0

Loading.... (view fulltext now)

Full text

(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

(2)

Step 4. Store the result in variable d Step 5. Print the value of d

Step 6. End of the program

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

(3)

Double sided

Rectangle Predefined Process

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

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.

Start Read N Count = 0 Sum = 0 Avg = 0 Sum = Sum + a Count = Count+1 Count< =n ?

(4)

True

False

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

special

(5)

character set is given below.

Alphabets A, B, C, …………Z 1960

1963 CPL Cambridge University Hard to learn, difficult to implement 1967 BCPL Martin 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.

(b) Machine oriented languages or Low-level languages: These languages have been designed to give a better machine efficiency, i.e., faster program execution.

(6)

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

(7)

3. Instructions

4. Functions, Program

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

a, b, c, ………z

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

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

Character/Symbol Meaning Character/Symbol Meaning

~ . ? “ ( [ { / < = - # & % _ Tilde Period Question Mark Double Quote Left Parenthesis Left Bracket Left Brac e Slash Less than Equal to Minus Hash Ampersand Percent Underscore Blank Space , ; : „ ) ] } \ > ! + $ * ^ | Comma Semicolon Colon

Apostrophe (single quote) Right Parent hesis

Right Bracket Right Brace Back Slash Greater than Exclamatory Mark Plus Dolor Sign Asterisk (or star) Carat

Vertical 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).

(8)

(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.

(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 Data types

A data type 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.

(9)

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

Data types Description SizeBytes)(No. of Range

Char Single character 1 0 to 255

Int An integer 2 -32768 to +32767

Float Floating point number 4 -2,147,483,648 to

+2,147,483,647

Double Floating point number 8 Approximately 15 digits of

Precision

Void No data type 0

signed char Character 1 -128 to 127

unsigned char Unsigned character 1 0 to 255

short signed int Short signed integer 2 -32768 to +32767

short unsigned int Short unsigned integer 3 0 to 65535

Long singed int Long signed integer 4 -2,147,483,648 to

+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 Data types

Basic data types Derived data types

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

(10)

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

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.

(11)

(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.

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

The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive.

The exponent must have at least one digit, which must be a positive or negative

integer. Default sign is positive.

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.

(12)

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.

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 value Escape Sequence Meaning 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.

(13)

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.

(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:

Alpha income x fyear_9899 matrix

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

(14)

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 /.

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.

(15)

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 + - * / % Addition

Subtraction; also for unary minus Multiplication

Division

(16)

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 than

Greater than or Equal to Less than

Less than or Equal to Equal to

Not 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 AND Logical OR Logical NOT

(17)

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.

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 Complement Bitwise OR Bitwise AND

Bitwise Exclusive OR (XOR) Right Shift

Left 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 --

(18)

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.

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 + b a = 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

(19)

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

* / % + - Multiplication Division Modulo Addition Subtraction Left to right “ “ “ “ 3 3 3 4 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( )

(20)

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

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.

(21)

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,

(22)

/* Welcome to „C‟ ,/* programming*/ */

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

(23)

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.

Examples

printf(“This is C statement”); 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 Output

c d s f Character Integer String Floating point A single character Signed decimal integer Prints character strings Single floating point number

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

example, %ld).

System Ready

Enter Program

Edit Source Program

Compile Source Program

Synta x Errors?

Link with System Library Execute Object Code Logic and Data Errors? Program Code C Compiler System Library Input Data

(24)

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 );

PROGRAMS

Prog.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();

(25)

}

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> void main()

{

clrscr();

printf(“Millennium Software Solutions”); printf(“\n Visakhapatnam”);

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

(26)

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() { 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(); }

Output Sum is:6

(27)

Prod is:8 Quo is:2 Rem 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,20 After swapping:20,10

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:10 The char is:x The 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( ) {

(28)

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( );

}

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

(29)

/* 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:4 Enter b value:2 a+b=6 a-b=2 a*b=8 a/b=2 Rem=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( );

}

Output Enter a value:10 Enter b value:20

(30)

Before swapping the values are:10,20 After 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:10 Enter b value:20

Before swapping the values are:10,20 After 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:2 minutes=120 seconds=7200

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

/* Conversion of years into days and months */ #include<stdio.h>

(31)

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:2 Days=730 Months=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; 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 4 Area=12

Perimeter=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( ); }

(32)

Output Enter s value:3 Area=9

Perimeter=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:2 Area=12.56

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

(33)

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

-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

(34)

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) 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

quantity

(35)

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:4 It is Even number Output 2 Enter a number:5 It is Odd number

Note that there is no semicolon between the condition and the

statement i.e., no semicolon following if(n%2==0).

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; else

statement2;

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

(36)

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”); else printf(“Odd number”); getch( ); } Output 1 Enter a number:4 Even number Output 2 Enter a number:5 Odd number

2.4 Nested if-else Statements

When a series of conditions are involved, we can use more than one else statement in nested form. This form is also known as

if-else if-if-else statements. The general form of if-if-else if-if-else statement

(37)

if (condition) statements; else if (condition) statements; else statements;

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); else printf(“%d is big”,c); getch( ); } Output 1

Enter the three values:3 5 7 7 is big

Output 2

Enter the three values:5 6 2 6 is big

Output 3

Enter the three values:3 2 1 3 is big

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

(38)

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);

(39)

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):0 Zero Output 2 Enter a number (0-9): 10 More 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);

(40)

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

}

Output 1 Enter year:1990 Not leap year

Output 2 Enter year:1996 Leap 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 4 b is big

Output 2 Enter a,b values:4 2 a 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();

}

(41)

Enter a number:5 Single digit

Output 2 Enter a number:12 Not 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:5 It is Odd Number Output 2 Enter a number:4 It 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:0 zero

(42)

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 7 c is big

Output 2

Enter a,b,c values:8 4 6 a 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:1990 Not leap year

(43)

Output 2 Enter year:1996 Leap 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 4 b is big

Output 2 Enter a,b values:4 2 a is big

Prog.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:5 Single digit Output 2

(44)

Enter a number:12 Not 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:0 zero 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”);

(45)

getch(); }

Output 1

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

Output 2

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

Output 3

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

If-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”); else

printf(“Not single digit”); getch(); } Output 1 Enter a number:5 Single digit Output 2 Enter a number:12 Not 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);

(46)

if(a>b) printf(“a is big”); else printf(“b is big”); getch(); } Output 1 Enter a,b values:3 4 b is big

Output 2 Enter a,b values:4 2 a is big

Prog.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”); else

printf(“Not leap year”); getch();

}

Output 1 Enter year:1990 Not leap year

Output 2 Enter year:1996 Leap 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‟)

(47)

printf(“It is Vowel”); else printf(“It is Consonant”); getch(); } Output 1 Enter a letter:b It is Consonant Output 2 Enter a letter:u It 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”); else printf(“c is big”); getch(); } Output 1

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

Output 2

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

Output 3

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

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

/* To check whether +ve, -ve or zero */ #include<stdio.h>

(48)

void main() { int n; clrscr(); printf(“Enter a number:”); scanf(“%d”,&n); if(n>0) printf(“+ve”); else if(n<0) printf(“-ve”); else printf(“zero”); getch(); } Output 1 Enter a number: -2 -ve Output 2 Enter a number:0 zero 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)

(49)

printf(“\nSecond Class”); else if(avg>=35) printf(“\nThird Class”); else printf(“\nFail”); getch( ); } Output 1 Enter stuno:101 Enter sub1:65 Enter sub2:65 Enter sub3:65 Total=195.00 Average=65.00 First Class Output 2 Enter stuno:105 Enter sub1:30 Enter sub2:65 Enter sub3:65 Total=160 Average=53.34 Second 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)

(50)

printf(“\nResult:Second Class”); else printf(“\nResult:Third Class”); } else printf(“\nResult:Fail”); getch( ); } Output 1 Enter stuno:101 Enter sub1:65 Enter sub2:65 Enter sub3:65 Total=195.00 Average=65.00 Result:First Class Output 2 Enter stuno:105 Enter sub1:30 Enter sub2:65 Enter sub3:65 Total=160 Average=53.34 Result: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)

(51)

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”); else

printf(“\nResult:Fail in all subjects”); } getch( ); } Output 1 Enter stuno:101 Enter sub1:65 Enter sub2:65 Enter sub3:65 Total=195.00 Average=65.00 Result:First Class Output 2 Enter stuno:105 Enter sub1:30 Enter sub2:65 Enter sub3:65 Total=160 Average=53.34 Result:Fail in Sub1 Output 3 Enter stuno:103 Enter sub1:60 Enter sub2:30 Enter sub3:50 Total=140 Average=46.67 Result:Fail in Sub2

(52)

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”); else printf(“Special Symbol”); getch(); } Output 1 Enter a letter:a Small letter Output 2 Enter a letter:C Capital letter Output 3 Enter a letter:6 Digit 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)

(53)

{ 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:a Vowel Output 2 Enter a char:b Consonant Output 3 Enter a char:U Vowel

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”);

(54)

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):3 Three Output 2 Enter a number(0-9):12 More 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”); }

(55)

getch(); } Output 1 Enter a number:3 Tuesday Output 2 Enter a number:9 No 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:l l->blue Output 2 Enter a char:y y->yellow Output 3

(56)

Enter a char:c No 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

(57)

Welcome to Arithmetic operations --- 1.Add 2.Sub 3.Mul 4.Div(quo) 5.Rem --- Enter U r choice here:1

Enter 2nos:5 4 The sum is:9

Output 2

Welcome to Arithmetic operations --- 1.Add 2.Sub 3.Mul 4.Div(quo) 5.Rem --- Enter U r choice here:6

Enter 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); }

(58)

}

Output 1

Enter any arithmetic operator(+,-,*,/,%):* Enter 2nos:4

5

The 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;

(59)

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.

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; }

References

Related documents

The others (e.g. Playing Videos, adding the shutdown button) are not crucial to the camera project but can be done if you’re also interested in exploring these capabilities.

Cannnot access this java program, declaring unwanted global variables declared inside that this content is added in object occupies a variable used by keeping

¾ Private: A variable or method can only be used in the class where it is defined.. Any variable declared inside a method is

Checks in the Ultimate Limit States Design Combinations Stress-Strain-Curves Design Internal Forces Design for Bending with or without Longitudinal Force or Longitudinal Force

Workstation A and its respective IP phone (both on the same segment) are attached to a Dell PowerConnect switch that forwards data and voice traffic to an office gateway/router,

betnovate crema fimosis adultos precio del betnovate crema can i use betnovate n on my face betnovate n skin cream price in india betamethasone injection site pregnancy

produced using a more “natural” production method (i.e. organic agriculture). However, so far there is no common and objective definition of clean label. This review paper aims to

Class Work and  Homework Policy: