• No results found

C Notes

N/A
N/A
Protected

Academic year: 2021

Share "C Notes"

Copied!
69
0
0

Loading.... (view fulltext now)

Full text

(1)

CONTENTS OF ‘C’ LANGUAGE

Introduction to ‘C’

Importance of ‘C’

Sample Program

Basic Structure of ‘C’ Programs

Constants, Variable, Data types

Operators and expressions

Assignment Operators

Decision making and branching

Simple if statement

if .... else statement

Nested if .... else statement

else if ladder

The Switch Statement

The Conditional Operator(?:)

The goto statement

Decision making and looping

The while statement

The do ... while statement

The for statement

Arrays

One -dimensional arrays

Two -dimensional arrays

Multi -dimensional arrays

Handling of character strings

User -Defined Functions

Cal by value

Call by Reference

Recursion

Structures and Unions

Enum

Pointers

Pre-processor

Macro

File Management in ‘C’

(2)

Creator of Such a Wonderful language “C”

• The C programming language was designed by Dennis Ritchie at Bell Laboratories in the early 1970s.

• Its Immediate ancestors and Influenced by – ALGOL 60 (1960),

– CPL (Cambridge, 1963), – BCPL (Martin Richard, 1967),

BCPL Reference Manual by Martin Richards, dated July 1967. The language described here supplied the basis for much of our own work and that of others. The linked page discusses the circumstances, while the files linked under it have the manual itself.

– B (Ken Thompson, 1970)

Ken Thompson instead ended up developing a compiler for a new high-level language he called B, based on the earlier BCPL language developed by Martin Richard. Where it might take several pages of detailed PDP-7 assembly code to accomplish a given task, the same functionality could typically be expressed in a higher level language like B in just a few lines. B was thereafter used for further development of the Unix system, which made the work much faster and more convenient.

C was not written as a teaching aid, but as an implementation language. C is a computer language and a programming tool which has grown popular

because programmers like it! It is a tricky language but a masterful one. Sceptics have said that it is a language in which everything which can go wrong does go wrong. True, it does not do much hand holding, but also it does not hold anything back. If you have come to C in the hope of finding a powerful language for writing everyday computer programs, then you will not be disappointed. C is ideally suited to modern computers and modern programming.

• Traditionally used for systems programming, though this may be changing in favor of C++

(3)

– The C Programming Language, by Brian Kernighan and Dennis Ritchie, 2nd

Edition, Prentice Hall. – Referred to as K&R .

High Levels and Low Levels

Any kind of object that is sufficiently complicated can be thought of as having levels of detail; the amount of detail we see depends upon how closely we scrutinize it. A computer falls definitely into the category of complex objects and it can be thought of as working at many different levels. The terms low level and high level are often used to describe these onion-layers of complexity in computers. Low level is perhaps the easiest to understand: it describes a level of detail which is buried down amongst the working parts of the machine: the low level is the level at which the computer seems most primitive and machine-like. A higher level describes the same object, but with the detail left out.

C is called a high level, compiler language. The aim of any high level computer language is to provide an easy and natural way of giving a programme of instructions to a computer (a computer program). The language of the raw computer is a stream of numbers called machine code.

Basic ideas about C:

What to do with a compiler. What can go wrong .

Using a compiler language is not the same as using an interpreted language like BASIC or a GNU shell. It differs in a number of ways. To begin with, a C program has to be created in two stages:

(4)

 Firstly, the program is written in the form of a number of text files using a screen editor. This form of the program is called the source program. It is not possible to execute this file directly.

 Secondly, the completed source file is passed to a compiler--a program which generates a new file containing a machine code translation of the source text. This file is called an object file or executable file. The executable file is said to have been compiled from the source text.

Compiler languages do not usually contain their own editor, nor do they have words like RUN with which to execute a finished program.

The Compiler

A C program is made by running a compiler which takes the typed source program and converts it into an object file that the computer can execute. A compiler usually operates in two or more phases (and each phase may have stages within it). These phases must be executed one after the other.

This development of Unix in C had two important consequences:

 Portability. It made it much easier to port Unix to newly developed computers, because it eliminated the need to translate the entire operating system to the new assemble language by hand:

(5)

o First, write a C-to-assembly language compiler for the new machine. o Then use the new compiler to automatically translate the Unix C language

source code into the new machine's assembly language.

o Finally, write only a small amount of new code where absolutely required by hardware differences with the new machine.

 Improvability. It made Unix easy to customize and improve by any programmer that could learn the high-level C programming language. Many did learn C, and went on to experiment with modifications to the operating system, producing many useful new extensions and enhancements.

Standard C:

• Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C

• International standard (ISO) in 1990 which was adopted by ANSI and is known as

C89

As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99)

IMPORTANCE OF C:

 A set of built-in functions and operators can be used to write any complex program.

 Programs written in C are efficient and fast.

 This is,due to its variety of data types and powerful operators. It is many times faster than BASIC.

 Several standard functions are available which can be used for developing programs.

 C is highly portable.

 C language is well suited for structured programming, thus requiring the

 User to think of a problem in terms of modules or blocks.

 A proper collection of these modules would make a complete program. This modular structure makes program debugging, testing and maintenance easier.

 Another important feature of C is its ability to extend itself.

 A C program is basically a collection of functions that are supported by the C library.

 We can continuously add our own functions to the C library.

 With the availability of a large number of functions, the programming task becomes simple.

(6)

Programming style

C is actually a free format language. This means that there are no rules about how it must be typed, when to start new lines, where to place brackets or whatever.

The reasons for choosing a well structured style are that:

Long programs are manageable only if programs are properly organized.

Programs are only understandable if care is taken in choosing the names of variables and functions.

 It is much easier to find parts of a program if a strict ordering convention is

maintained. Such a scheme becomes increasingly difficult to achieve with the size and complexity of the problem.

Elements of a C Program

A C development environment includes

– System libraries and headers: a set of standard libraries and their header files. For example see /usr/include and glibc.

– Application Source: application source and header files

– Compiler: converts source to object code for a specific platform

– Linker: resolves external references and produces the executable module

C Standard Header Files you may want to use

• Standard Headers you should know about:

Stdio.h – file and console (also a file) io: perror , printf, open , close , read ,

write , scanf , etc.

stdlib.h - common utility functions: malloc , calloc , strtol , atoi etc

string.h - string and byte manipulation: strlen , strcp y, strcat , memcpy ,

(7)

ctype.h – character types: isalnum , isprint , isupport , tolower, etc.errno.h – defines errno used for reporting system errors

math.h – math functions: ceil, exp, floor, sqrt, etc.signal.h – signal handling facility: raise, signal, etcstdint.h – standard integer: intn_t, uintn_t, etc

time.h – time related facility: asctime, clock, time_t, etc.

User program structure

– there must be one main function where execution begins when the program is run. This function is called main

• int main (void) { ... },

• int main (int argc, char *argv[]) { ... }

• UNIX Systems have a 3rd way to define main(), though it is not POSIX.1

compliant

int main (int argc, char *argv[], char *envp[])

• additional local and external functions and variables.

The form of a C program

What goes into a C program? What will it look like?

The basic building block in a C program is the function. Every C program is a collection of one or more functions, written in some arbitrary order. One and only one of these functions in the program must have the name main(). This function is always the starting point of a C program, so the simplest C program would be just a single function definition:

main () { }

The parentheses () which follow the name of the function must be included even though they apparently serve no purpose at this stage. This is how C distinguishes functions from ordinary variables.

(8)

FORMAT OF A SIMPLE C PROGRAM:

main() Function name { // Start of program

---——— Program statements ———

} End of program

/* A program that prints out the sentence This is my first C program. */ #include <stdio.h>

int main (void) {

printf ("This is my first C program.\n"); return (0);

}

BASIC STRUCTURE OF C PROGRAM

A C program can be viewed as a group of building blocks called functions.

A function is a subroutine that may include one or more statements designed to perform a specific task. To write a C program, we first create functions and then put them together. A C program may contain one or more

Sections

Documentation Section (Comments about the program) Link Section (Header)

Global Declaration Section

main() Function Section {

Declaration Part (Variable Declaration) Executable Part (Statements)

}

(9)

Function1 Function2

……….. (User-defined functions) Function

The documentation section consists of a set of comment lines giving the name of the program,

the author and other details which the programmer would like to use later.

The link section provides instructions to the compiler to link functions from the system library.

There are some variables that are used in more than one function. Such

variables are called global variables and are declared in the global declaration section that is outside of all the functions.

Every C program must have one main() function section. This section contains two parts,

1. declaration part and 2. executable part.

The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and the closing braces.

The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function section is the logical end of the program. All the

statements in the declaration and executable parts end with a semicolon. The subprogram section contains all the user-defined functions that are called in the main function.

User defined -functions are generally placed immediately after the main function, although they may appear in any order. All sections, except the main function may be absent when they are not required.

EXECUTING OF A ‘C’ PROGRAM

Executing a program written in C involves a series of steps. These are: 1. Creating the program

2. Compiling the program

3. Linking the program with functions that are needed from the C library 4. Executing the program.

The C Character Set:

A character denotes any alphabet, digit or special symbol used to represent information. The characters in C are grouped into the following categories:

1. Letters 2. Digits

3. Special Characters 4. White Spaces

White spaces may be used to separate words, but are prohibited between the characters of keywords and identifiers.

1. Letters:

Uppercase A……Z

Lowercase a……z

2. Digits:

All decimal digits 0 ... 9

(10)

Comma (,) & ampersand(&) Period (.) & caret(^) Semi colon (;) & asterisk(*) Colon (:) & minus(-) Question mark (?) & plus sign(+)

apostrophe (‘) & opening angle bracket(<) Quotation mark (“) & less than sign(<)

Exclamation mark (!) & closing angle bracket(>) vertical bar (|) & greater than sign(>) slash (/) & left parenthesis(( ) back slash (\) & right parentheses ( )) tilde (~) & left bracket([)

under score (_) & right bracket(]) dollar sign ($) & left brace({) percent sign (%) & right brace(}) number sign (#)

4. White Space: Blank space

C Tokens (Constants, Variables and Keywords):

A constant is a quantity that doesn’t change. This quantity can be stored at a locations in the memory of the computer. A variable also can be stored in the memory of the computer. But the contents of the variable can be changed.

Types of C Constants:

C constants can be divided into two major categories: 1. Primary Constants & 2. Secondary Constants

1. Primary Constants we learn Integer Constants, Real Constants, Character Constants and

2. Secondary Constants we learn Array, Pointers, Structures, Union, Enum etc.

Rules for constructing Integer Constants:

a) An integer constant must have at least one digit b) It must not have a decimal point.

c) It can be either positive or negative.

d) If no sign precedes an integer constant it is assumed to be positive. e) No commas or blanks are allowed within an integer constant.

f) The allowable range for integer constants is -32768 to 32767.

Ex: 426 +782 -8000 -7605

/* program for Integer no’s */ # include<stdio.h> void main() { int a, b,c; clrscr(); c=a+b; printf(“value of c is %d”,c); getch();

(11)

}

Rules for constructing Real Constants:

a) A real constant must have at least one digit b) It must have a decimal point.

c) It can be either positive or negative.

d) If no sign precedes a real constant it is assumed to be positive. e) No commas or blanks are allowed within an real constant. f) The allowable range for real constants is -3.4e38 to 3.4e38. Ex: +325.34 +782.0 -80.76 -760.578 #include <stdio.h> int main (void) { /* declarations */ int a; double x; /* executable statements */ a = 1000; x = 100.583665; printf ("%d\n", a); printf ("%3d\n", a); printf ("%4d\n", a); printf ("%5d\n", a); printf ("\n"); printf ("%lf\n", x); printf ("%15lf\n", x); printf ("%15.4lf\n", x); printf ("%18.2lf\n", x); printf ("%12.0lf\n", x); return (0); }

Rules for constructing Character Constants:

a) A character constant is a single alphabet, a single digit or a single special symbol enclosed within single inverted commas.

b) The maximum length of a character constant can be 1 character. Ex: ‘A’ ‘I’ ‘5’ ‘=‘ / * Inputting characters

A program that asks the user for 4 characters and displays them on the screen. #include <stdio.h>

(12)

{

/* declarations */

char letter1, letter2, letter3, letter4;

printf ("enter a name: ");

scanf ("%c%c%c%c", &letter1, &letter2, &letter3, &letter4);

printf ("you entered: %c%c%c%c", letter1, letter2, letter3, letter4); printf (" / backwards: %c%c%c%c\n", letter4, letter3, letter2, letter1); return (0);

} output:

enter a name: lucky you entered : lucky

C Keywords:

Keywords are the words whose meaning has already been explained to the C compiler. The keywords cannot be used as variable names. There are only 32 keywords available in C. auto double if static

break else int struct case enum long switch char extern near typedef const float register union continue far return unsigned default for short void do goto signed while

C Instructions:

There are basically four types of instructions in C. 1. Type Declaration Instruction

2. Input/Output Instruction 3. Arithmetic Instruction 4. Control Instruction

1. 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. Type declaration statement is usually written at the beginning of the C program.

Example:

Int bas;

float rs, grossal; char name, code;

2. Input/Output Instruction:

This instruction is used to perform the function of supplying input data to a program (scanf() function and obtaining the output results from it ( printf() function).

Trying printf and scanf

A program that asks the user for two numbers and prints out the sum and the product. #include <stdio.h>

int main (void) {

(13)

/* declarations */ double x, y, z;

/* executable statements */

printf ("Enter two integer numbers: "); scanf ("%lf %lf", &x, &y);

z = x + y;

printf ("\nThe sum of %lf and %lf is %f.\n", x, y, z); printf ("\nThe product of %lf and %lf is %lf.\n", x, y, x*y);

return (0); }

3. 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 variables and constants appearing on the right hand side of = are connected by arithmetic operators like +, - *, and /.

Example:

int ad;

float kot, data; ad = 3200; kot = 0.0056;

data = ad + kot+ 32 +5;

The variables and constants together are called operands and +, -, *, / arecalled operators. The right hand side is evaluated and this value is then

assigned to the variable on the left hand side. C allows only one variable on left hand side of =. Character constants are stored in character variable as follows: char a, b, d;

a = ‘F’; b = ‘G’; d = ‘+’;

An Arithmetic

operation between an integer and integer always yields an integer result. Operation between a real and real always yields a real result.

Operation between an integer and real always yields a real result.

Operation Result Operation Result

5/2 2 2/5 0

5.0/2 2.5 2.0/5 0.4 5/2.0 2.5 2/5.0 0.4 5.0/2.0 2.5 2.0/5.0 0.4

The arithmetic operations are performed an order given below: 1. Multiplication 2. Division 3. Modulo Division 4. Addition 5. Substraction 6. Assignment.

4. Control instruction:

This instruction is used to control the sequence of execution of various statements in a C program. The control instructions determine the flow of control in a program. There are four types of control instructions in C.

(14)

2. Selection or Decision Control Instruction 3. Repition or Loop Control Instruction 4. Case Control Instruction

OPERATORS AND EXPRESSIONS

C supports a rich set of operators. An operator is a symbol that tells the computer to

perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of the mathematical of logical expressions.

C operators can be classified into eight categories as shown below:

1. Arithmetic operators 2. Relational operators 3. Logical operators 4. Assignment operators

5. Increment and decrement operators 6. Conditional operators

7. Bitwise operators 8. Special operators

1. ARITHMETIC OPERATORS:

C provides all the basic arithmetic operators (+, -, *, /). The unary minus operator, in effect, multiplies its single operand by -1. Therefore, a number preceded by a minus sign changes its sign. Operator Meaning + Addition - Subtraction * Multiplication / Division % Modulo division

Interger division truncates any fractional part.

/* Example for Arithmatic operations */

#include<stdio.h> #include<conio.h> main() { int x,y,z=0; clrscr();

printf(" enter the values of x and y :"); scanf("%d %d",&x,&y);

z=x+y;

printf("\n the addition of two numbers : %d",z); z=x-y;

printf("\n the subtraction of two numbers : %d",z); z=x*y;

printf("\n the multiplication of two numbers : %d",z); z=x/y;

printf("\n the division of two numbers : %d",z); z=x%y;

printf("\n the remainder of x/y is : %d",z); getch();

(15)

RELATIONAL OPERATORS:

We often compare two quantities, and depending on their relation, take certain decisions. For example, we may compare the age of two persons, or the price of two items, and so on. These comparisons can be done with the help of relational operators.

C supports six relational operators as shown below:

Relational Operators

Operator Meaning

< is less than

<= is less than or equal to > is greater than

>= is greater than or equal to

!= is not equal to == is equal to 4.5 <= 10 TRUE 4.5 < -10 FALSE -35 >= 0 FALSE 10 < 7+5 TRUE

a+b = = c+d TRUE (only if the sum of values of a and b is equal to the sum of values of c and d.)

LOGICAL OPERATORS:

C has the following three logical operators.

1. && meaning logical AND 2. || meaning logical OR 3. ! meaning logical NOT

Some examples of the usage of logical expressions are given below: 1. if(age > 55 && salary < 1000)

2. if(number < 0 || number > 100) ASSIGNMENT OPERATORS

Assignment operators are used to assign the result of an expression to a variable. C has a set of shorthand assignment operators as shown below:

v op = exp;

where v is a varible, exp is an expression and op is a shorthand assignment operator.

It is equivalent to v = v op (exp);

/* A program that makes a few changes in variable values using the assignment operator. */ #include <stdio.h>

int main (void) {

/* declarations */ int a, b, c, d, e;

(16)

/* fill variable a */ a = 10;

/* modify variable a few times*/ a = 20;

a = 10 + a; a = a + a + 2; a = 2 + a;

/* a few more assignments */ b = a; c = b = 5; c = 10 + a; d = a + a + 2; e = 20 + a; a = a - b + c;

/* the final values are... */

printf ("a:%4d\n b:%4d\n c:%4d\n d:%4d\n e:%4d\n", a, b, c, d, e); return (0);

}

Shorthand Assignment Operators: Statement with simple Statement with

assignment operator shorthand operator

a = a + 1 a + = 1 a = a - 1 a - = 1 a = a * a a * =a a = a*(n+1) a* = (n+1) a = a / (n+1) a / = (n+1) a = a % b a % = b

INCREMENT AND DECREMENT OPERATORS:

C has two very useful operators not generally found in other languages.

These are the increment and decrement operators: + + and

-Increment and decrement

/ *A program showing the different uses of the increment and decrement operators. */ #include <stdio.h>

int main (void) { int a, b; a = 5; /* increment (++) */ /* a is incremented by 1 */ ++a;

(17)

/* a is once more incremented by 1 */ a++;

printf ("After a++, a is now %d\n", a);

/* a is incremented but b gets the current a */ b = a++;

printf ("After b=a++, a is now %d and b is %d\n", a, b); /* a is incremented and b gets the incremented a */ b = ++a;

printf ("After b=++a, a is now %d and b is %d\n", a, b); /* decrement (--) */

/* a is decremented by 1 */ --a;

printf ("After --a, a is now %d\n", a); /* a is once more decremented by 1 */ a--;

printf ("After a--, a is now %d\n", a);

/* a is decremented but b gets the current a */ b = a--;

printf ("After b=a--, a is now %d and b is %d\n", a, b); /* a is decremented and b gets the decremented a */ b = --a;

printf ("After b=++a, a is now %d and b is %d\n", a, b); return (0);

}

CONDITIONAL OPERATOR:

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

exp1 ? exp2 : exp3;

To find out a number which is greater than other number. This can be done by using if.. else statements as follows: a = 10; b = 15; if (a > b) x =a; else x = b;

These same program can be written as shown below: x = (a >b)? a: b;

#include<stdio.h> void main()

{

Int a=5,b=5;

(18)

}

BITWISE OPERATOR

C has a distinction of supporting special operators known as bitwise operators for

manipulation of data at bit level. These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be

applied to float or double. SPECIAL OPERATORS

C supports some special operators such as comma operator, sizeof operator, pointer

operators (& and *) and member selection operators ( . And ->).

The sizeof Operator

The sizeof is a compile time operator and, when used with an operand, it returns the number of bytes the operand occupies. The operand may be a variable, a constant or a data type qualifier.

Example:

m = sizeof(sum);

8. DECISION MAKING AND BRANCHING INTRODUCTION

In C program, a set of statements which are normally executed sequentially in the order in which they appear. This happens when no options or no repetitions of certain calculations are necessary. However, in practice, we have a number of situations where we may have to change the order of execution of statements based on certain conditions, or repeat a group of statements until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly. C language provides decision making statements known as control or decision making statements.

There are four type of such statements. 1. if statement

2. switch statement

3. Conditional operator statement 4. goto statement

SIMPLE IF STATEMENT

The general form of a simle if statement is

if(test expression)

{

statement-block; }

statement-x;

The statement-block may be a single statement or a group of statements. If the test

expression is true, the statement-block will be executed; otherwise the statement-block will be skipped and the execution will jump to the statement-x. Remember, when the condition is true both the statement-block and the statement-x are executed in sequence.

(19)

#include<stdio.h> void main(){ Int raining; If(raining=true)

Printf(“ this is rainy season”); Printf(“this is too rainy”); Getch();

:

IF ... ELSE STATEMENT

The if .... else statement is an extension of the simple if statement. The general form is if(test expression)

{ True-block statement(s) } else { False-block statement(s) } statement-x

If the test expression is true, then the true-block statement(s), immediately following the if statement are executed; otherwise, the false-block statement(s) are executed. In either case, either true-block or false-block will be executed, not both. In both the cases, the control is transfered subsequently to statement-x.

Expression is true if

x = = y x is equal to y x != y x is not equal to y x < y x is less than y x > y x is greater than y

x <= y x is less than or equal to y x >= y x is greater than or equal to y

Even vs. odd

/* A program that determines if an integer number is odd or even. #include <stdio.h>

int main (void) {

int number, even;

/* ask user for number */ printf ("Enter an integer number: ");

scanf ("%d", &number);

/* determine if number is even and put in variable */ even = (number % 2 == 0);

/* display report */ if (even)

(20)

else

printf ("%d is an odd number. \n", number); return (0);

}

11. NESTED IF ... ELSE STATEMENT:

When a series of decisions are involved, we may have to use more than one if ... else statement in nested form as follows:

12. ELSE IF LADDER

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

An electric power distribution company charges its domestic

consumers as follows:

Consumption Units Rates of charge 0 to 200 Rs. 0.50 per unit

201 to 400 Rs. 100 plus Rs. 0.65 per unit

401 to 600 Rs. 230 plus Rs. 0.80 per unit excess of 400 601 and above Rs. 390 plus Rs. 1.00 per unit

excess of 600 if(units <= 200) charges = 0.5*units; else if(unit <= 400) charges = 100 + 0.65* (units-200); else if(unit <= 600) charges = 230 + 0.80*(units-400); else charges = 390 + 1.00*(units - 600); THE SWITCH STATEMENT

We can design a program using if statements to control the selection. However, the complexity of such a program increases dramatically when the number of alternatives increases. The program becomes difficult to read and

follow. C has a bult-in multiway decision statement known as a switch. The switch

statement test the value of a given variable (or expression) against a list of case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below:

The expression is an integer expression or characters. Value-1, value-2 ... are constants are known as case

lables. Each of these values should be unique within a swich statement. block-1, block-2 ... are statement

lists. There is no need to put braces around these blocks. Note that case labels end with a colon(:). When the switch is executed, the value of the expression is successively compared against the values value-1, value-2, ...

If a case is found whose value matches with the value of the expression, then the block of statements that

follows the case are executed.:

The Switch Statement is shown below:

(21)

{ case value-1: block-1; break; case value-2: block-2; break; ... default: default-blcok; break; } statement-x;

The traffic light program (switch)

A program that displays the recommended actions depending on the color of a traffic light. Unlike the previous program, this implementation uses the switch statement.

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

char colour;

/* ask user for colour */

printf ("Enter the colour of the light (R,G,Y,A): "); scanf ("%c", &colour);

/* test the alternatives */ switch (colour) { /* red light */ case 'R': case 'r': printf ("STOP! \n"); break;

/* yellow or amber light */ case 'Y': case 'y': case 'A': case 'a': printf ("CAUTION! \n"); break; /* green light */ case 'G': case 'g': printf ("GO! \n"); break; /* other colour */ default:

printf ("The colour is not valid.\n"); }

(22)

}

15. THE GOTO STATEMENT

C supports the goto statement to branch unconditionally from one point to another in the

program. Although it may not be essential to use the goto statement in a highly structured language like C, there may be occations when the use of goto might be desirable. The goto requires a label in a order to identify the place where the branch is to be made. A label is any valid variable name, and must be followed by a colon. The label is placed immediately before the statement where the control is to transferred. Before goto statement. if condition must be added. The general forms of goto and label statements are shown below:

Forward jump Backward jump if(test expression)

goto label; label:

... statement; ... ... ... ...

label: if(test expression)

statement; goto label;

The label: can be anywhere in the program either before or after the goto label; statement. During the running of a program when a statement like goto begin; is met, the flow of control will jump to the statement immediately

following the label begin:.Note that a goto breaks the normal sequential execution of the program. If the label: is before the statement goto label; a loop will be formed and some statements will be executed repeatedly. Such a jump is known as backward jump. On the other hand, if the label: is placed after the goto label; some statements will be skipped and the jump is known as a forward jump. A goto is often used at the end of a program to direct the control to go to the input statement, to read further data. Consider the following

example: main() { double x, y; read: scanf(“%lf”, &x); if(x < 0) goto read; y = sqrt(x); printf(“%lf\n”, y); }

16. DECISION MAKING AND LOOPING

INTRODUCTION

It is possible to execute a segment of a program repeatedly by introducing a counter and later testing it using the if statement and goto statement. It forms a loop. In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop consists of two segments, one known as the body of the loop and the other known as the control statement. The control statement tests certain

conditions and then directs the repeated execution of the statements contained in the body of the loop. Depending on the position of the control statement in the loop, a control

(23)

exit-controlled loop. In entry-control loop, the control conditions are tested before the

start of the loop execution. If the conditions are not satisfied, then the body of the loop will not be executed. In the case of an exit-controlled loop,

the test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time.

A looping process, in general, would include the following four steps: 1. Setting and initialization of a counter.

2. Execution of the statements in the loop.

3. Test for a specified condition for exection of the loop. 4. Incrementing the counter.

The C language provides for three loop constructs for performing loop operations. They are: 1.The while statement 2.The do - while statement 3. The for statement

17. THE WHILE STATEMENT

The simplest of all the looping structures in C is the while statement. The basic format of the while statement is shown below:

while(test condition)

{

body of the loop }

The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test condition is once again evaluated and if it is

true, the body is executed once again. This process of repeated execution of the body continues until the test condition finally becomes false and the control is tranferred out of the loop. On exit, the program continues with the statement immediately after the body of the loop. The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. However, it is a good practice to use braces even if the body has only one statement.

A simple count from 1 to 100

/* A program that displays the numbers between 1 and 100. #include <stdio.h>

int main (void) {

int n;

n = 1; /* loop initialization */ /* the loop */

while (n <= 100) /* loop condition */ {

printf ("%d ", n); /* loop body */ n = n + 1; /* loop update */ }

return (0); }

18. THE DO ... WHILE STATEMENT

In while loop a test condition is checked before the loop is executed. Therefoere, the body of the looop may not be executed at all if the condition is not satisfied at the very first attempt. On some occations it might be necessary

to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. The takes the form:

(24)

do

{

body of the loop }

while(test-condition);

On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated. If the condition is true, the program continues to

evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Since the test-condition is evaluated at the bottom of the loop, the do ...

while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once.

/* Program to demonstrate do - while program to print menu */

#include<stdio.h> #include<conio.h> main() { int choice,x,y; char c='y'; clrscr();

printf(" enter the two numbers :"); scanf("%d %d",&x,&y); do{ printf("--- MENU ---\n"); printf(" 1 . ADD \n"); printf(" 2 . SUB \n"); printf(" 3 . MUL \n"); printf(" 4 . DIV \n"); printf(" 5 . EXIT \n"); printf(" enter your choice :"); scanf("%d",&choice);

switch(choice) {

case 1: printf("\n sum= %d ",x+y); break;

case 2: if(x>y)

printf("\n difference = %d ",x-y); else

printf("\n difference = %d",y-x); break;

case 3: printf("\n multiplication = %d ",x*y); break;

case 4: if(y!=0)

printf("\n division = %d ",x/y); else

printf("\n infinity "); break;

case 5: exit(0);

default: printf("\n invalid in-put"); break;

(25)

}

fflush(stdin);

printf(" do u want to continue (y/n) :"); scanf("%c",&c);

}while(c=='y'||c=='Y'); getch();

}

THE FOR STATEMENT

The for loop is another entry-controlled loop that provides a more concise loop control structure. The general form of the for loop is shown below:

for(initialization; test-condition; increment)

{

body of the loop }

The execution of the for statement is as follows:

1. Initialization of the control variable is done first, using assignment statements such as i=1. The variable i is known as loop-control variable.

2. The value of the control variable is tested using the test-condition. The test condition is a

relational expression, such as i<10 that determines when the loop will exit. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.

3. When the body of the loop is executed, the control is transferred back to the for

statement after evaluating the last statement in the loop. Now, the control variable is incremented using an assignment statement such

as i = i+1 and the new value of the control variable is again tested to see whether it saatisfies the loop condition. If the conition is satisfied, the body of the looop is again executed. This process continues till the value of the

control variable fails to satisfy the test-condition. #include<stdio.h> void main() { int x; clrscr(); for(x = 0; x <= 9; x = x + 1) { printf(“%d”, x); } printf(“\n”); getch(); }

Comparision of the while, do, for loops

While do for n = 1; n = 1; for(n = 1; n <= 10; ++n) while(n <= 10) do { { { --- --- } n = n + 1; n = n + 1; } } while(n <= 10);

(26)

ARRAYS

Aset of variables of same type is called array.An array shares a common name. For instance, we can define an array name salary to represent a set of salries of a group of employees. A particular value is indicated by writing a

number called index number or subscript in brackets after the array name. For example,

salary[10]

while the complete set of values is referred to as an array, the individual values are called elements. Array can be of any variable type.

ONE-DIMENSIONAL ARRAYS

A list of items can be given one variable name using only one subscript

and such a variable is called a single - subscripted variable or onedimensional array.

In C, single-subscripted variable xi can be expressed as x[0], x[1], x[2], ... x[n-1]

The subscript begins with number 0. That is

x[0]

is allowed. For example, if we want to represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable number, then we may declare the variable number as follows

int number[5];

and the computer reserves five storage locations and afterwards numbers are inserted as shown below:

35 number[0] 40 number[1] 20 number[2] 57 number[3] 19 number[4] Declaration of Arrays

Like any other variable, arrays must be declared before they are used. The general form of array declaration is

type variable-name[size];

The type specifies the type of element that will be contained in the array, such as int, float, or char and the size indicates the maximum number of elements that can be stored inside the array. For example,

float height[50]; int group[10];

The C language treats character strings simply as array of characters. The size in a

character string represents the maximum number of characters that the string can hold. For instance,

char name[10];

declares the name as a character array (string) variable that can hold a maximum of 10 characters. Suppose we read the following string constant into the string variable name. “WELL DONE”

Initialization of Arrays:

We can initialize the elements of arrays in the same way as the ordinaryvariables when they are declared. The general form of initialization of arrays is:

(27)

static type array-name[size] = {list of values}; The values in the list are separated by commas. For example, the statement static int number[3] = {0, 0, 0};

will declare the variable number as an array of size 3 and will assign zero to each element. If the number of values in the list is less than the number of elements, then only that many elements will be initialized. The remaining

elements will be set to zero automatically. For instance, static float total[5] = {0.0, 15.75, -10}; #include<stdio.h> #include<conio.h> main() { int arr[6]={67,78,89,65,69,75},i; //clrscr(); for(i=0;i<6;i++) printf("%3d",arr[i]); return 0; }

/* A program is to calculate the sum of a array */ main()

{

int arr[6],i,sum=0; clrscr();

printf("enter the elements into an array :"); for(i=0;i<6;i++)

scanf("%d",&arr[i]); for(i=0;i<6;i++) sum=sum+arr[i];

printf("\n total marks = %d ",sum); getch();

}

TWO - DIMENSIONAL ARRAYS:

The data in a table can be considered as two-dimenstional array. Two-dimensional arrays are declared as follows:

type array_name [row_size][column_size];

Two dimensional arrays are stored in memory as shown below: As with the

single-dimensional arrays, each dimension of the array is indexed from zero to its maximum size minus one; the first index selects the row and

the second index selects the column within that row. INITIALIZING TWO –DIMENSIONAL ARRAYS

Like the one-dimensional arrays, two-dimensional arrays may beinitialized by following their declaration with a

list of initial values enclosed in braces. For example: static int table[2][3] = {0, 0, 0, 1, 1, 1};

initializes the elements of the first row to zero and the secnd row to one. The initialization is done row by row.

The above statement can be equivalently written as static int table[2][3] = {{0, 0, 0}, {1, 1, 1}};

by surrounding the elements of each row by braces. We can also initialize a two-dimensional array in the form of

(28)

static int table[2][3] = { {0, 0, 0}, {1, 1, 1} } ; /* Example for a Double Dimensions */ main()

{

int a[2][2],i,j,b[2][2],c[2][2]; clrscr();

printf("enter the elements into an array a:"); for(i=0;i<2;i++)

for(j=0;j<2;j++) scanf("%d",&a[i][j]);

printf("enter the elements into an array b:"); for(i=0;i<2;i++) for(j=0;j<2;j++) scanf("%d",&b[i][j]); for(i=0;i<2;i++) for(j=0;j<2;j++) c[i][j]=a[i][j]+b[i][j];

printf("\nthe elements of an array c :\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) printf("%5d",c[i][j]); printf("\n"); } getch(); }

/* A program is to find addition of a matrices */ #include <stdio.h> void main() { int a[10][10],b[10][10],c[10][10]; int m,n,p,q,i,j; clrscr();

printf("ENTER THE SIZE OF THE MATRIX A: "); scanf("%d%d",&m,&n);

printf("ENTER THE SIZE OF THE MATRIX B: "); scanf("%d%d",&p,&q);

if(m==p && n==q) {

printf("ENTER THE VALUES INTO MATRIX A: "); for(i=0;i<m;i++)

for(j=0;j<n;j++) scanf("%d",&a[i][j]);

printf("ENTER THE VALUES INTO MATRIX B: "); for(i=0;i<p;i++)

(29)

for(j=0;j<q;j++) scanf("%d",&b[i][j]);

printf("THE MATRIX addition is: \n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { c[i][j]=a[i][j]+b[i][j]; printf("%d\t",c[i][j]); } printf("\n"); } } else

printf("ADDITION NOT POSSIBLE"); getch();

}

/* A program is to find multiplication of matrices */ #include<stdio.h> void main() { int a[r1][c1],b[r2][c2],c[r][c],i,j; printf("\nenter r1,c1,r2,c2"); scanf("%d%d%d%d",&r1,&c1,&r2,&c2); printf("enter the 1 ele");

for(i=0;i<r1;i++) for(j=0;j<c1;j++) scanf("%d",&a[i][j]); printf("\nenter the 2 ele"); for(i=0;i<r2;i++) for(j=0;j<c2;j++) scanf("%d",b[i][j]); if(c1==r2) { printf("\nmultiplication is possible"); } else

printf("multiplication is not possible"); c[i][j]=0; for(i=0;i<r2;i++) { for(j=0;j<c1;j++) { for(k=0;k<c1;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } for(i=0;i<r1;i++) for(j=0;j<c2;j++) printf("%d",c[i][j]); getch(); }

(30)

C allows arrays of three or more dimensions. The general form of a multi-dimensional array is type array_name[s1][s2][s3] ... [sm];

where si is the size of the ith dimension. Some example are: int survery[3][5][12];

and float table[5][4][5][3];

survey is a three-dimensional array declared to contain 180 integer type elements. Similarly table is a four-dimensional array containing 300 elements of floating-point type. The array survey may represent a survey

data of rainfall during the last three years from January to December in five cities. HANDLING OF CHARACTER STRINGS

INTRODUCTION:

A string is an array of characters. Any group of characters defined between double quotation marks is a constant string.

Example:

“Man is obviously made to think.” For example,

printf(“\“Well Done!\” ”); will output the string

“Well Done!” while the statement printf(“WellDone!”); will output the string

WellDone!

Character strings often used to build meaningful and readable programs. The common operations performed on character strings are:

 Reading and Writing strings

 Combining strings together.

 Copying one string to another.

 Comparing strings for equality.

 Extracting a portion of a string.

DECLARING AND INITIALIZING STRING VARIABLES:

A string variable is any valid C variable name and is always declared as an array. The general form of declaration of a string variable is

char string_name[size];

The size determines the number of characters in the string-name. Some examples are:

char city[10]; char name[30];

Reading a Line of Text:

In many text processing applications, we need to read in an entire time of text from the terminal. It is not possible to use scanf function to read a line containing more than one word. This is because the scanf terminates reading

as soon as a space is encountered in input. We have learned to read a single character from the terminal, using the

(31)

function getchar.

WRITING STRINGS TO SCREEN

We have used the printf function with %s format to print strings to the screen. The format %s can be used to display an array of characters that is terminated by the null character. For example, the statement

printf(“%s”, name);

can be used to display the entire contents of the array name.

The following features of the %s specifications.

1. When the field width is less than the length of the string, the entire string is printed. 2. The integer value on the right side of the decimal point specifies the number of characters to be printed.

3. When the number of characters to be printed is specified as zero, nothing is printed. 4. The minus sign in the specification causes the string to be printed left-justified. printf(“%*.*s\n”, w, d, string);

OPERATIONS ON CHARACTERS

C allows us to manipulate characters the same way we do with numbers. Whenever a

character constant or character variable is used in an expression, it is automatically converted into an integer value by the system. The integer value depends on the local character set of the system. To write a character in its integer representation, we may write it as an integer. For example, if the machine uses the ASCII representation, then,

x = ‘a’; printf(“%d\n”, x);

will display the number 97 on the screen.

In ASCII character set, the decimal numbers 65 to 90 represent upper-case alphabets (A-Z) and 97 to 122 represent lower-case alphabets (a-z).

The values from 91 to 96 are excluded using an if statement in the for loop.

The C labrary supports a function that converts a string of digits into their integer values. The function takes the form

x = atoi(string);

STRING - HANDLING FUNCTIONS

The C library supports a large number of string-handling functions that can be used to carry out many of the string manipulations. Following are the most commonly used string-handling functions.

Function Action

strcat() concatenates two strings strcmp() compares two strings

strcpy() copies one string over another strlen() finds the length of a string. strrev() reversing the string.

strlwr() converts upper case to lower case. strupr() converts lower case to upper case. strcat() Function

(32)

form: strcat(string1, string2);

C permits nesting of strcat functions. For example, the statement

strcat (strcat (string1, string2), string3); #include<string.h>

#include<stdio.h> void main()

{

char destination[25]="This is ",c[8] = " Turbo ", turbo[5]=" C++"; clrscr(); strcat(destination,c); strcat(destination,turbo); printf("%s\n",destination); getch(); } strcmp() Function

The strcmp function compares two strings identified b the arguments and has a value 0 if they are equal. If they are not, it has the numeric difference between the first non matching characters in the strings. It takes the form:

strcmp(string1, string2);

string1 and string2 may be string variables or string constants. Examples are: strcmp(“Rom”, “Ram”); #include<string.h> #include<stdio.h> void main() { char buf1[10],buf2[10]; int ptr; clrscr();

printf("enter two strings :"); scanf("%s %s",buf1,buf2); ptr=strcmp(buf2, buf1); printf("diff =%d\n",ptr); if(ptr==0)

printf("two strings are equal\n "); else if (ptr > 0)

printf("\nbuffer 2 is greater than buffer 1\n"); else

printf("buffer 2 is less than buffer 1\n"); getch();

}

strcopy() Function

The strcpy function works almost like a string-assignment operator. It takes the form strcpy(string1, string2);

For example, the statement strcpy(city, “DELHI”);

(33)

#include<stdio.h> #include<string.h> void main() { char string[10]; char str1[10]="abcdefghi"; clrscr(); strcpy(string,str1); printf("%s\n", string); getch(); } strlen() Function

This function counts and returns the number of characters in a string. n = strlen(string);

where n is an integer variable which receives the value of the length of the string. #include<stdio.h> #include<conio.h> #include<string.h> void main() { int l=0;

char string[25]="Borland International"; clrscr();

l=strlen(string); printf("%d\n",l); getch();

}

/* A program is to find the reverse of a string */ #include<stdio.h>

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

{

char forward[10] = "string"; clrscr();

printf("Before strrev(): %s\n",forward); strrev(forward);

printf("After strrev(): %s\n",forward); getch();

}

/* A program is to convert upper case to lower case */ #include <stdio.h>

#include <string.h> void main()

(34)

char string[25] = "BorlandInternational"; clrscr();

printf("string prior to strlwr: %s\n", string); strlwr(string);

printf("string after strlwr: %s\n", string); getch();

}

/* A program is to find the converts lower case to upper case */ #include <stdio.h>

#include <string.h> void main()

{

char string[25] = "BorlandInternational"; clrscr();

printf("string prior to strupr: %s\n", string); strupr(string);

printf("string after strupr: %s\n", string); getch();

}

USER-DEFINED FUNCTIONS

INTRODUCTION:

A function is a self-contained block of statements that perform a task of some kind. A function performs same type of task every time. Every C program can be thought of as a collection of these functions. Generally we use three primary functions, namely, main,

printf, and scanf. We shall consider in detail how a function is designed, how two or more

functions are put together and how they communicate with one another. C functions can be classified into two categories, namely,

1. Library functions and 2. user-defined functions.

Note: main is an example of user-defined function.

printf and scanf belongs to the category of library functions.

The main difference 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.

NEED FOR LIBRARY& USER-DEFINED FUNCTIONS

Every program must have a main function to indicate where the program has to begin its execution. If only main function is used, then the program may become too big and complex, and it will be difficult to debug,

test and maintain it. So we use independent functions in main function. These functions are much easier to understand, debug, and test.

(35)

The main function calls familier functions from C library. The function of specific type can be prepared by the user called user-defined function. The user-defined functions are kept after the main function ends. Whenever

these user-defined functions are required, the main function calls the required function. Then the main function can be called as calling function and the user-defined function is called

called function.

A user-defined function is a seft-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a ‘block box’ that takes some data from the main program and returns a value. The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out. Every C program can be designed using a collection of these block boxes.

THE FORMAT OF USER-DEFINED FUNCTION:

All user-defined functions have the form given below:

function-name(argument list)

argument declaration; {

local variable declarations; executable statement1; executable statement1; ---return(expression); }

All parts are not essential. Some may be absent. For example, the argument list and its associated argument declarartion parts are optional. The declaration of local variable is required only when any local variable are

used in the function. A function can have any number of executable statements.

The return statement is the mechanism for returning a value to the calling function. This is an optional statement. Its absence indicates that no value is being returned to the calling function.

CATEGORY OF USER-DEFINED FUNCTIONS

A user-defined function, depending on whether arguments are present or not and whether a value is returned or not, may belongs 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.

Variable Declaration:

Varible declaration can be two types: They are: Local And Global

Where a program's fingers can't reach.

From the computer's point of view, a C program is nothing more than a collection of

functions and declarations. Functions can be thought of as sealed capsules of program code which float on a background of white space, and are connected together by means of function calls. White space is the name given to the white of an imaginary piece of paper

(36)

upon which a program is written, in other words the spaces and new line characters which are invisible to the eye. The global white space is only the gaps between functions, not the gaps inside functions.

Global Variables:

Global variables are declared in the white space between functions. If every function is a ship floating in this sea of white space, then global variables (data storage areas which also float in this sea) can enter any ship and also enter anything inside any ship (See the

diagram). Global variables are available everywhere;. they are created when a program is started and are not destroyed until a program is stopped.

Local Variables:

Local variables are more interesting. They can not enter just any region of the program because they are trapped inside blocks. To use the ship analogy: if it is imagined that on board every ship (which means inside every function) there is a large swimming pool with many toy ships floating inside, then local variables will work anywhere in the swimming pool (inside any of the toys ships, but can not get out of the large ship into the wide beyond. The swimming pool is just like a smaller sea, but one which is restricted to being inside a

particular function.

1. NO ARGUMENTS AND NO RETURN VALUES

When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. In effect, there is

no data transfer between the calling function and the called function. main()

{

printf(“I love India.\n”);

neha(); shilpa(); }

neha()

{

printf(“Do you love India?\n”); } shilpa()

{

printf(“I too love India.\n”); }

The output of the above program when executed would be as under: o/p: I love India.

Do you love India? I too love India.

2. ARGUMENTS BUT NO RETURNVALUES:

When a function has an argument, it receives data from the terminal and it is

transferred to the called function. If there is no calculations in the calling function, then it does not return any value to the main function.

(37)

The mechanism used to convey information to the user-defined function is the arugument or parameter. The arugment for parameter may be a variable or character constant. These arguments must be in parentheses.

Example: main() { char ch; clrscr(); printf("Enter a character\n"); scanf("%c", &ch); clrscr(); printline(ch);

printf("\nWelcome to Neha Computers\n"); printline(ch); printf("\n"); getch(); } printline(char x) { int i; for(i=1; i <= 25; i++) printf("%c", x); }

The output will be under the control of the user, if ch is * then the the output will be as under:

In this program ch can be called as argument or paramenter. It receives argument from the terminal. This argument can be called actual argument. This argument is transferred to the user-defined function. In the

User defined function we find another argument called formal argument which must be declared in the parenthesis. If you use actual argument in the user defined function, then the compiler would still treat them as different variable since they are in different function. In this user-defined function nothing is to be returned. Therefore, it is not necessary to use the return statement. Immediately after the closing brace the control is returned to the calling function.

3.

ARGUMENTS WITH RETURN VALUES

When a function has arguments, it receives data from the terminal and they are transferred to the called function. The calculations are done in the calling function, then it returns the to the main function for further processing

or displaying.

Example:

/* Sending and receiving values between calling and called functions */ main()

{

int a, b, c, sum; clrscr();

printf("Enter any three numbers\n"); scanf("%d %d %d", &a, &b, &c); sum = calsum(a, b, c);

printf("Sum = %d\n", sum); getch();

(38)

} calsum(x, y, z) int x, y, z; { int d; d = x + y + z; return(d); }

RETURN VALUES AND THEIR TYPES:

A function may or may not send back any value to the calling function. If it does, it is done through the return statement. While it is possible to pass to the called function any number of values, the called function can only return one value per call, at the most.

The return statement can take one of the following forms: Return ; or return (expression); Example: main() { float a, b, mul(); a = 10.0; b = 3.0; clrscr(); printf("%f\n", mul(a, b)); getch(); } float mul(x, y) float x, y; { return(x*y); }

In this program it returns a floating value.

FUNTIONS RETURNING NOTHING

We have seen earlier that in many occations, functions do not return any value. They perform only some printing. This is made possible by making use of the keyword void.

Example:

main() {

void gospel();

printf(“I want to be your friend\n”); }

void gospel() {

Printf(“What a nice person you are!\n”); }

(39)

NESTING OF FUNCTIONS

C permits nesting functions freely. main can call function1, which calls

function2,

which calls function3, ...

There is in principle no limit as to how deeplly functions can be nested. RECURSION

When a called function in turn calls another function a processng of ‘chaining’ occurs. Recursion is a special case of this process, where a function calls itself. A very simple example of recursion is the evaluation of

factorials of a given number.

The factorial of a number n is expressed as a series of repetitive multiplications as shown below:

factorial of n = n(n-1)(n-2) ...1. A function to evaluate factorial of n is as follows: Factorial(n) int n; { int fact; if(n ==1) return(1); else fact = n*factorial(n-1); return(fact); }

Let us see how the recursion works. Assume n = 3. Since the value of n is not 1, the statement

fact = n * factorial(n-1);

will be executed with n = 3. That is, fact = 3 * factorial(2);

will be evaluated. The expression on the right-hand side includes a call to factorial with n = 2. This call will return the following value:

2 * factorail(1)

Once again, factorial is called with n = 1. This time, the function returns 1. The sequence of operations can be summarized as follows:

fact = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1

= 6

Recursion function can be effectively used to solve problems where the solution is expressed in terms of successively applying the same solution to subsets of the problem. When we write recursive functions, we must have an if statement somewhere to force the function to return without the recursive call being executed.

(40)

The changes made in the formal arguments will not reflect to atual arguments. /* Example for Call by Value */

void main() {

int a,b;

void swap(int,int); clrscr();

printf(“\n enter the 2 integers”); scanf(“%d%d”,&a,&b);

printf(“\n before swapping a=%d \t b=%d”,a,b); swap(a,b);

printf(“\n after swapping a=%d \t =%d “,a,b); getch();

}

void swap(int x, int y) { int temp; temp=x; x=y; y=temp; } CALL BY REFERENCE:

The Changes made in the formal arguments will reflect to actual parameters(arguments).

/* Example for call by reference */

#include<stdio.h> #include<conio.h> void swap(int*,int*); main() { int i,j;

printf("enter the values of i and j :"); scanf("%d %d",&i,&j);

swap(&i,&j);

printf("values of i and j after function call: i=%d j=%d",i,j); return 0;

getch(); }

void swap(int* p,int *q) {

*p=*p+*q; *q=*p-*q; *p=*p-*q;

printf("values of p and q in function : p=%d q=%d",p,q); }

References

Related documents

innovation in payment systems, in particular the infrastructure used to operate payment systems, in the interests of service-users 3.. to ensure that payment systems

Prereq or concur: Honors standing, and English 1110 or equiv, and course work in History at the 3000 level, or permission of instructor.. Repeatable to a maximum of 6

○ If BP elevated, think primary aldosteronism, Cushing’s, renal artery stenosis, ○ If BP normal, think hypomagnesemia, severe hypoK, Bartter’s, NaHCO3,

The BA (Hons) International Culinary Arts programme is designed to enable students to attain a critical understanding of the culinary industry and equip students with the

Keywords: economic model predictive control; nonlinear constraint relaxation; periodic operation; difference-algebraic equations; water distribution

our options. This gives you clear water, so you are not riding the wakes of the other boats, and you get clear air. When it got light and lumpy we had the space to put the bow

Under our weighted log-linear learning rule, actions take a simple form: given a continuous action space and a binary state space, we can express each agent’s action as a

18 Francee Anderson, Sylvia Bremer and Dorothy Cumming received their training, and their start in their profession, at Sydney’s three major schools of elocution, Lawrence Campbell’s