about c programming language - · pdf fileabout c programming language history c was developed...

116
ABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL ( Combined Programming Language ) was developed with the purpose of creating a language that was capable of both high level, machine independent programming and would still allow the programmer to control the behavior of individual bits of information. The one major drawback of CPL was that it was too large for use in many applications. In 1967, BCPL ( Basic CPL ) was created as a scaled down version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell Labs, took this process further by developing the B language. B was a scaled down version of BCPL written specifically for use in systems programming. Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of developing the language we now know as C. C's power and flexibility soon became apparent. Because of this, the Unix operating system which was originally written in assembly language, was almost immediately re-written in C ( only the assembly language code needed to "bootstrap" the C code was kept ). During the rest of the 1970's, C spread throughout many colleges and universities because of it's close ties to Unix and the availability of C compilers. Soon, many different organizations began using their own versions of C causing compatibility problems. In response to this in 1983, the American National Standards Institute ( ANSI ) formed a committee to establish a standard definition of C which became known as ANSI Standard C. The standardization process took six years. The ANSI C standard was finally adopted in December 1989, with the first copies becoming available in early 1990. The standard was also adopted by ISO (International Standards Organization), and the resulting standard was typically referred to as ANSI/ISO Standard C, or simply ANSI/ISO C. Today C is in widespread use with a rich standard library of functions. Significant Language Features C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer. It allows low level access to information and commands while still retaining the portability and syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs. C's power and fast program execution come from it's ability to access low level commands, similar to assembly language, but with high level syntax. 1

Upload: phunghuong

Post on 18-Mar-2018

219 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ABOUT C PROGRAMMING LANGUAGE

History

C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were taken from the earlier language B and B's earlier ancestors BCPL and CPL. CPL ( Combined Programming Language ) was developed with the purpose of creating a language that was capable of both high level, machine independent programming and would still allow the programmer to control the behavior of individual bits of information. The one major drawback of CPL was that it was too large for use in many applications. In 1967, BCPL ( Basic CPL ) was created as a scaled down version of CPL while still retaining its basic features. In 1970, Ken Thompson, while working at Bell Labs, took this process further by developing the B language. B was a scaled down version of BCPL written specifically for use in systems programming. Finally in 1972, a co-worker of Ken Thompson, Dennis Ritchie, returned some of the generality found in BCPL to the B language in the process of developing the language we now know as C.

C's power and flexibility soon became apparent. Because of this, the Unix operating system which was originally written in assembly language, was almost immediately re-written in C ( only the assembly language code needed to "bootstrap" the C code was kept ). During the rest of the 1970's, C spread throughout many colleges and universities because of it's close ties to Unix and the availability of C compilers. Soon, many different organizations began using their own versions of C causing compatibility problems. In response to this in 1983, the American National Standards Institute ( ANSI ) formed a committee to establish a standard definition of C which became known as ANSI Standard C. The standardization process took six years. The ANSI C standard was finally adopted in December 1989, with the first copies becoming available in early 1990. The standard was also adopted by ISO (International Standards Organization), and the resulting standard was typically referred to as ANSI/ISO Standard C, or simply ANSI/ISO C. Today C is in widespread use with a rich standard library of functions.

Significant Language Features

C is a powerful, flexible language that provides fast program execution and imposes few constraints on the programmer. It allows low level access to information and commands while still retaining the portability and syntax of a high level language. These qualities make it a useful language for both systems programming and general purpose programs.

C's power and fast program execution come from it's ability to access low level commands, similar to assembly language, but with high level syntax.

1

Page 2: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

It's flexibility comes from the many ways the programmer has to accomplish the same tasks. C includes bitwise operators along with powerful pointer manipulation capabilities. C imposes few constraints on the programmer. The main area this shows up is in C's lack of type checking. This can be a powerful advantage to an experienced programmer but a dangerous disadvantage to a novice.

Another strong point of C is it's use of modularity. Sections of code can be stored in libraries for re-use in future programs. This concept of modularity also helps with C's portability and execution speed. The core C language leaves out many features included in the core of other languages. These functions are instead stored in the C Standard Library where they can be called on when needed.. An example of this concept would be C's lack of built in I/O capabilities. I/O functions tend to slow down program execution and also be machine independent when running optimally. For these reasons, they are stored in a library separately from the C language and only included when necessary.

C is often called a middle-level computer language. This does not mean that C is less powerful, harder to use, or less developed than a high-level language such as Pascal; nor does it imply that C is similar to, or presents the problems associated with, assembly language. The definition of C as a middle-level language means that it combines elements of high-level languages with the functionalism of assembly language. As a middle-level language, C allows the manipulation of bits, bytes, and addresses—the basic elements with which the computer functions. Despite this fact, C code is surprisingly portable. Portability means that it is possible to adapt software written for one type of computer to another. For example, if a program written for one type of CPU can be moved easily to another, that program is portable. All high-level programming languages support the concept of data types. A data type defines a set of values that a variable can store along with a set of operations that can be performed on that variable. Common data types are integer, character, and real. Although C has several basic built-in data types, it is not a strongly typed language like Pascal or Ada. In fact, C will allow almost all type conversions. For example, character and integer types may be freely intermixed in most expressions. Traditionally C performs no run-time error checking such as array-boundary checking or argument-type compatibility checking. These checks are the responsibility of the programmer. A special feature of C is that it allows the direct manipulation of bits, bytes, words, and pointers. This makes it well suited for system-level programming, where these operations are common. Another important aspect of C is that it has only 32 keywords (5 more were added by C99, but these are not supported by C++), which are the commands that make up the C language. This is far fewer than most other languages. THE FOUNDATION OF C++

2

Page 3: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Standard Library This is a summary of the library defined by the ANSI standard. The standard library is not part of the C language proper, but an environment that supports standard C will provide the function declarations and type and macro definitions of this library. The functions, types and macros of the standard library are declared in standard headers: <assert.h> <float.h> <math.h> <stdarg.h> <stdlib.h> <ctype.h> <limits.h> <setjmp.h> <stddef.h> <string.h> <errno.h> <locale.h> <signal.h> <stdio.h> <time.h> A header can be accessed by #include <header> Headers may be included in any order and any number of times. A header must be included outside of any external declaration or definition and before any use of anything it declares. A header need not be a source file. External identifiers that begin with an underscore are reserved for use by the library, as are all other identifiers that begin with an underscore and an upper-case letter or another underscore. Input and Output: <stdio.h> The input and output functions, types, and macros defined in <stdio.h> represent nearly one third of the library. . When a program begins execution, the three streams stdin, stdout, and stderr are already open. File Operations The following functions deal with operations on files. fopen opens the named file, and returns a stream, or NULL if the attempt fails. Legal values for mode include: "r" open text file for reading "w" create text file for writing; discard previous contents if any "a" append; open or create text file for writing at end of file "r+" open text file for update (i.e., reading and writing) "w+" create text file for update, discard previous contents if any "a+" append; open or create text file for update, writing at end freopen opens the file with the specified mode and associates the stream with it. It

3

Page 4: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

returns stream, or NULL if an error occurs. freopen is normally used to change the files associated with stdin, stdout, or stderr. int fflush(FILE *stream) On an output stream, fflush causes any buffered but unwritten data to be written; on an input stream, the effect is undefined. int fclose(FILE *stream) fclose flushes any unwritten data for stream, discards any unread buffered input, frees any automatically allocated buffer, then closes the stream. It returns EOF if any errors occurred, and zero otherwise. int remove(const char *filename) remove removes the named file, so that a subsequent attempt to open it will fail. It returns non-zero if the attempt fails. int rename(const char *oldname, const char *newname) rename changes the name of a file; it returns non-zero if the attempt fails. Formatted Output The printf functions provide formatted output conversion. int fprintf(FILE *stream, const char *format, ...) fprintf converts and writes output to stream under the control of format. Formatted Input The scanf function deals with formatted input conversion. int fscanf(FILE *stream, const char *format, ...) fscanf reads from stream under control of format, and assigns converted values through subsequent arguments, each of which must be a pointer. Character Input and Output Functions fgetc returns the next character of stream as an unsigned char (converted to an int), or EOF if end of file or error occurs. fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the newline is included in the array, which is terminated by '\0' fputc writes the character c (converted to an unsigend char) on stream. It returns the character written, or EOF for error.

4

Page 5: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

fputs writes the string s (which need not contain \n) on stream; it returns nonnegative, or EOF for an error. getc is equivalent to fgetc except that if it is a macro, it may evaluate stream more than once. Direct Input and Output Functions fread reads from stream into the array ptr at most nobj objects of size size. fread returns the number of objects read; this may be less than the number requested. feof and ferror must be used to determine status. fwrite writes, from the array ptr, nobj objects of size size on stream. It returns the number of objects written, which is less than nobj on error. File Positioning Functions fseek sets the file position for stream; a subsequent read or write will access data beginning at the new position. ftell returns the current file position for stream, or -1 on error. void rewind(FILE *stream) rewind(fp) is equivalent to fseek(fp, 0L, SEEK_SET); clearerr(fp). fgetpos records the current position in stream in *ptr, for subsequent use by fsetpos. Character Class Tests: <ctype.h> The header <ctype.h> declares functions for testing characters. For each function, the argument list is an int, whose value must be EOF or representable as an unsigned char, and the return value is an int. isalnum(c) isalpha(c) or isdigit(c) is true isalpha(c) isupper(c) or islower(c) is true iscntrl(c) control character isdigit(c) decimal digit

5

Page 6: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

isgraph(c) printing character except space islower(c) lower-case letter isprint(c) printing character including space ispunct(c) printing character except space or letter or digit isspace(c) space, formfeed, newline, carriage return, tab, vertical tab isupper(c) upper-case letter isxdigit(c) hexadecimal digit In addition, there are two functions that convert the case of letters: int tolower(c) convert c to lower case int toupper(c) convert c to upper case If c is an upper-case letter, tolower(c) returns the corresponding lower-case letter, toupper(c) returns the corresponding upper-case letter; otherwise it returns c. String Functions: <string.h> These are the groups of string functions defined in the header <string.h>. char *strcpy(s,ct) copy string ct to string s, including '\0'; return s. char *strcat(s,ct) concatenate string ct to end of string s; return s. int strcmp(cs,ct) compare string cs to string ct, return <0 if cs<ct, 0 if cs==ct, or >0 char *strchr(cs,c) return pointer to first occurrence of c in cs or NULL if not present. strspn(cs,ct) return length of prefix of cs consisting of characters in ct. size_t char *strstr(cs,ct) return pointer to first occurrence of string ct in cs, or NULL if not present. strlen(cs) return length of cs. Mathematical Functions: <math.h> The header <math.h> declares mathematical functions and macros. In the following table, x and y are of type double, n is an int, and all functions return double. Angles for trigonometric functions are expressed in radians. sin(x) sine of x cos(x) cosine of x tan(x) tangent of x

6

Page 7: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

asin(x) sin-1(x) in range [-pi/2,pi/2], x in [-1,1]. acos(x) cos-1(x) in range [0,pi], x in [-1,1]. atan(x) tan-1(x) in range [-pi/2,pi/2]. atan2(y,x) tan-1(y/x) in range [-pi,pi]. sinh(x) hyperbolic sine of x cosh(x) hyperbolic cosine of x tanh(x) hyperbolic tangent of x exp(x) exponential function ex log(x) natural logarithm ln(x), x>0. log10(x) base 10 logarithm log10(x), x>0. pow(x,y) xy. A domain error occurs if x=0 and y<=0, or if x<0 and y is not an integer. sqrt(x) sqare root of x, x>=0. ceil(x) smallest integer not less than x, as a double. floor(x) largest integer not greater than x, as a double. fabs(x) absolute value |x| ldexp(x,n) x*2n frexp(x, int *ip) splits x into a normalized fraction in the interval [1/2,1) which is returned, and a power of 2, which is stored in *exp. If x is zero, both parts of the result are zero. modf(x, double *ip) splits x into integral and fractional parts, each with the same sign as x. It stores the integral part in *ip, and returns the fractional part.

7

Page 8: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Utility Functions: <stdlib.h> The header <stdlib.h> declares functions for number conversion, storage allocation, and similar tasks. void *calloc(size_t nobj, size_t size) calloc returns a pointer to space for an array of nobj objects, each of size size, or NULL if the request cannot be satisfied. The space is initialized to zero bytes. void *malloc(size_t size) malloc returns a pointer to space for an object of size size, or NULL if the request cannot be satisfied. The space is uninitialized. Void *realloc(void *p, size_t size) realloc changes the size of the object pointed to by p to size. The contents will be unchanged up to the minimum of the old and new sizes. void free(void *p) free deallocates the space pointed to by p; it does nothing if p is NULL. p must be a pointer to space previously allocated by calloc, malloc, or realloc. void abort(void) abort causes the program to terminate abnormally, as if by raise(SIGABRT).

8

Page 9: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

DATA TYPES IN CC language is rich in data types. The fundamental data types which

can be used in C are integer data types, character data types and floating

point data types. Integer data type is used to represent an integer-valued

number. Character data type represents one single alphabet or a single-digit

integer. Each character type has an equivalent integer representation. Integer

and character data types can be augmented by the use of the data type

qualifiers, short, long, signed and unsigned. The range of values which

belong to each category varies with respect to the qualifiers and so, the

memory requirement.

Floating point data types are used to represent real numbers. Basic

floating point data type offers six digits of precision. Double precision data

type can be used to achieve a precision of 14 digits. To extend the precision

further more, we may use the extended double precision floating point data

type. Each of the above discussed data types and their corresponding

keywords are given in the table below.

DATA TYPES KEYWORD

Character char

Unsigned Character unsigned char

Signed Character signed char

Signed Integer signed int (or int)

Signed Short Integer signed short int (or short int or short)

Signed Long Integer signed long int (or long int or long)

Unsigned Integer unsigned int (or unsigned)

Unsigned Short Integer unsigned short int (or unsigned short)

Unsigned Long Integer unsigned long int (or unsigned long)

Floating Point float

Double Precision Floating Point double

Extended Double Precision

Floating Point

long double

9

Page 10: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

A schematic representation of the various data types in C is given below

Floating Point Type

float double long double

Integer Type

int unsigned int short unsigned short int long int unsigned long int

Character Type

signed char unsigned char

FUNDAMENTAL DATA TYPES

In the table below, the memory size required by each data type in

bits and the range of values they can posses are listed.

DATA TYPE SIZE in BITS RANGE

char or signed char 8 -128 to 127.

unsigned char 8 0 to 255.

int or signed int 16 -32768 to 32767.

unsigned int 16 0 to 65535.

short int or signed short int 8 -128 to 127.

unsigned short int 8 0 to 255.

long int or signed long int 32 -2,147,483,648 to

2,147,483,647.

unsigned long int 32 0 to 4,294,967,295.

float 32 3.4e-38 to 3.4e+38.

double 64 1.7e-308 to 1.7e+308.

long double 80 3.4e-4932 to 3.4e+4932.

10

Page 11: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

The syntax of the declaration of variables using data type is,

data-type vname-1, vname-2,…..vname-n;

where vname-1, vname-2, vname-n are

variable names. Some examples for the variable declaration are given

below.

int number;

char a;

long double big-number;

11

Page 12: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

EXPRESSIONS

Expressions in C are classified according to the operators used in

them. The classifications are,

• Relational expression.

• Logical expression.

• Arithmetic expression.

1. Relational expression.

An expression containing a relational operator is termed as

relational expression. The list of all relational operators is given below

OPERATOR MEANING

< Is less than.

<= Is less than or equal to.

> Is greater than.

>= Is greater than or equal to.

== Is equal to.

!= Is not equal to.

Format of a relation expression:

(a-expression-1) relational-operator (a-expression-2)

Where a-expression-1 and a-expression-2 are arithmetic expressions.

A relational expression always will have a value one or zero. The

value of the relational expression will be one if the specified relation is true

and zero if the relation is false. Relational operators are used in decision

statements such as ‘if’, and ‘while’ to decide the course of action of a

running program. When arithmetic expressions are used on either side of a

12

Page 13: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

relational operator, the arithmetic expressions will be evaluated first and

then the results are compared.

2. Logical expression.

Logical expressions are the expressions where logical operators

are used to combine more than one relational expression. Logical

expressions are also called compound relational expressions. The logical

operators used in C are && (logical AND), || (logical OR), and ! (logical

NOT). Logical expressions also yields a value of one or zero, and used in

decision statements.

Format of a logical expression:

(rel-expression-1) logical operator (rel-expression-2)

Where rel-expression-1 and rel-expression-2 are relational

expressions. The values of the above statement when different logical

operators are used is given below

Operator Value of rel-

expression-1

Value of rel-

expression-2

Value of the

statement

0 0 0

0 1 0

1 0 0

&&

1 1 1

0 0 0

0 1 1

1 0 1

|

1 1 1

13

Page 14: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ARITHMETIC EXPRESSIONS

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

Algebraic Expression C Expressiona x b – c a * b – c (m + n) (x + y) (m + n) * (x + y) (a x b / c) a * b / c 3x2 +2x + 1 3*x*x+2*x+1 (x / y) + c x / y + c

Evaluation of Expressions

Expressions are evaluated using an assignment statement of the form

Variable = expression;

Variable is any valid C variable name. When the statement is encountered, the expression is evaluated first and then replaces the previous value of the variable on the left hand side. All variables used in the expression must be assigned values before evaluation is attempted. Example of evaluation statements are

x = a * b – c; y = b / c * a; z = a – b / c + d;

Precedence in Arithmetic Operators

An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in C.

High priority * / % Low priority + -

14

Page 15: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Rules for evaluation of expression

• First parenthesized sub expression left to right are evaluated.

• If parentheses are nested, the evaluation begins with the innermost sub expression.

• The precedence rule is applied in determining the order of application of operators in evaluating sub expressions.

• The associability rule is applied when two or more operators of the same precedence level appear in the sub expression.

• Arithmetic expressions are evaluated from left to right using the rules of precedence.

• When Parenthesis are used, the expressions within parenthesis assume highest priority.

Type conversions in expressions

Implicit type conversion:

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

During evaluation it adheres to very strict rules and type conversion. If the operands are of different types the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type. The following rules apply during evaluating expressions:

All short and char are automatically converted to int then

1. If one operand is long double, the other will be converted to long double and result will be long double.

2. If one operand is double, the other will be converted to double and result will be double.

3. If one operand is float, the other will be converted to float and result will be float.

15

Page 16: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

4. If one of the operand is unsigned long int, the other will be converted into unsigned long int and result will be unsigned long int.

5. If one operand is long int and other is unsigned int then

a. If unsigned int can be converted to long int, then unsigned int operand will be converted as such and the result will be long int.

b. Else both operands will be converted to unsigned long int and the result will be unsigned long int.

6. If one of the operand is long int, the other will be converted to long int and the result will be long int.

7. If one operand is unsigned int the other will be converted to unsigned int and the result will be unsigned int.

Explicit Conversion:

Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion.

Consider for example the calculation of number of female and male students in a class.

Female students Ratio = ___________________ Male students

Since if female students and male students are declared as integers, the decimal part will be rounded off and its ratio will represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below.

Ratio = (float) female students / male students;

The operator float converts the female students to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed by floating point mode, thus retaining the fractional part of the result. The process of such a local conversion is known as explicit conversion or coasting a value. The general form is,

(type_name) expression

16

Page 17: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Operator precedence and associativity.

Each operator in C has a precedence associated with it. The precedence is used to determine how an expression involving more than one operator is evaluated. There are distinct levels of precedence and an operator may belong to one of these levels. The operators of higher precedence are evaluated first.

The operators of same precedence are evaluated from right to left or from left to right depending on the level. This is known as associativity property of an operator.

The table given below gives the precedence of each operator.

Order Category Operator Operation Associativity1 Highest

precedence ( ) [ ] →

Function call L → R Left to Right

2 Unary ! ~ + - ++ - - & * Size of

Logical negation (NOT) Bitwise 1’s complement Unary plus Unary minus Pre or post increment Pre or post decrement Address Indirection Size of operant in bytes

R → L Right -> Left

3 Member Access .* →*

Dereference Dereference

L → R

4 Multiplication * / %

Multiply Divide Modulus

L → R

5 Additive + -

Binary Plus Binary Minus

L → R

6 Shift << >>

Shift Left Shift Right

L → R

7 Relational < <= >

Less than Less than or equal to

L → R

17

Page 18: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

>= Greater than Greater than or equal to

8 Equality == !=

Equal to Not Equal to

L → R

9 Bitwise AAND & Bitwise AND L → R 10 Bitwise XOR ^ Bitwise XOR L → R 11 Bitwise OR | Bitwise OR L → R 12 Logical AND && Logical AND L → R 14 Conditional ? : Ternary Operator R → L 15 Assignment =

*= %= /= += -= &= ^= |= <<= >>=

Assignment Assign product Assign reminder Assign quotient Assign sum Assign difference Assign bitwise AND Assign bitwise XOR Assign bitwise OR Assign left shift Assign right shift

R → L

16 Comma , Evaluate L → R VALUES TO VARIABLES

In C, there are two different methods through which a variable can

be assigned values. They are, 1. Through assignment statements. 2. Using built-in functions.

ASSIGNMENT STATEMENTS Assignment statements are the simple means by which variables are

assigned values. The syntax is given below.

variable-name=expression;

Consider the below assignment statement. a=b*c; Here, the product of ‘b’, and ’c’ is calculated

and it is stored in ‘a’.

18

Page 19: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

USING BUILT-IN FUNCTIONS.

Built-in functions like ‘scanf’, ‘gets’, ‘getch’, ‘getchar’, ‘getc’ are used to assign values to variables. The functions ‘gets’, ‘getch’, ‘getchar’, ‘getc’ can be used to assign value to one variable and ‘scanf’ can be used to assign values to more than one variables. Syntaxes are given below.

scanf: scanf(“control-strings”, &variable-names); In the syntax of scanf statement, control strings

denote the data types of the variable-names. Using scanf, any number of variables can be assigned values.

getc(), getch(), getchar(), gets(): These functions are used to assign value to only one variable

at a time. The syntaxes of all these are the same except the function name. Syntax: variable-name = function-name(); The ‘getc’ function reads a character from a file pointer. Consider

the following example. c = getc(fp2); This statement reads the character from the file pointer, ‘fp2’ and

assigns that value to ‘c’. The ‘getch’ and ‘getchar’ functions assign values from the keyboard

to a variable. The ‘getch’ function assigns the value and immediately transfers the control to the next line of the program. But ‘getchar’ function waits for a key press to pass the control. The ‘gets’ function assign a string value to a variable. Some examples are given below.

a = getch(); b = gets(); c = getchar(); Here the variables ‘a’ and ‘c’ should be character variables

and ‘b’ should be a character array.

19

Page 20: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

IF_ELSE

This lesson will show you how to:

• Use an if statement • Use an else statement • Use an else if statement

If Statement

The if statement is used to conditionally execute a block of code based on whether a test condition is true. If the condition is true the block of code is executed, otherwise it is skipped.

SYNTAX if (condition) { true_statements ; } OR if (condition) true_statement ; OR if (condition) { true_statements ; } else { false_statements ; }

PROGRAM FLOW

1. First, the boolean expression condition is evaluated. 2. If condition evaluates to true, the true_statement(s) are executed. 3. If condition evaluates to false and an else clause exists, the

false_statement(s) are executed. 4. Flow exits the if-else structure.

20

Page 21: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

EXAMPLE

#include <stdio.h>

int main(void) {

int number = 75; int mark;

printf("Your examination mark\n"); printf("Enter your score, please\n"); scanf("%d",&mark); if (mark >= number) { printf("Incredible, you passed with a merit\n"); }

return 0; }

The "==" is called a relational operator. Relational operators, ==, !=, >, >=, <, and <=, are used to compare two values.

Else Statement

The else statement provides a way to execute one block of code if a condition is true, another if it is false.

Example:

#include <stdio.h>

int main(void) {

int number = 75; int mark;

printf("Your examination mark\n"); printf("Enter your score, please\n"); scanf("%d",&mark); if (mark >= number) {

21

Page 22: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

printf("Incredible, you have passed with a merit\n"); } else { printf("You failed, unlucky\n"); }

return 0; }

COMMON ERRORS Make sure that if you want to test equality in the condition to use the boolean operator == and not the assignment operator =. Consider the following bad piece of code. double x=0; if(x=1) { System.out.println("x is 0"); } else { System.out.println("x is not 0. x is "+x); } The output will be x is not 0. x is 1since x is assigned to 1 in the condition.

22

Page 23: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

FOR LOOP SYNTAX for (initialization ; test ; increment) { statements ; } OR for (initialization ; test ; increment) statement ;

PROGRAM FLOW

1. The initialization is first executed. This is typically something like int i=0, which creates a new variable with initial value 0, to act as a counter. Variables that you declare in this part of the for loop cease to exist after the execution of the loop is completed. Multiple, comma separated, expressions are allowed in the initialization section. But declaration expressions may not be mixed with other expressions.

2. The boolean expression test is then evaluated. This is typically something like i<10. Multiple, comma separated, expressions are not allowed. If test evaluates to true, flow contiues to step 3. Otherwise the loop exits.

3. The statement(s) are executed. 4. Then the statement increment is executed. It is typically something

like i++ , which increments i by one or i+=2 , which increments i by two. Multiple, comma separated, expressions are allowed in the increment section.

5. Flow returns to step 2.

EXAMPLE

The following code will print hello ten times:

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

printf("Hello\n");

23

Page 24: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

WHILE STATEMENT The simplest of all the c looping structures in C is the while statement . The while statement 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 the 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 is continued until the test condition becomes false and the control is transferred out of the loop. On exit the program is continued with the statement 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. The format of while statement is while (test condition) { body of the loop } Example of while statement /*******************************************************/ /* Program to compute x to the power n using while loop */ /*******************************************************/ # include<stdio.h> main() { int count,n; float x,y; printf(“Enter the values of x and n:”); scanf(“%f %d”, &x, &n); y= 1.0; count = 1; /* LOOP BEGINS*/ while(count<= n) { y = y * n; count ++; } /*End of loop*/ printf(“ x = %f ; n = %d ; to power n = %f n “, x , n, y); }

24

Page 25: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

DO STATEMENT In while statement there is a chance of skipping the entire loop without execution if the value is not satisfying the condition . To avoid such a condition we use do while statement. In do .. while statement the body of the loop will be executed at least once . On reaching the do statement , the program proceeds to evaluate the body first . At the end of the loop the test condition in the 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 of the program goes to the statement that appears after the while statement . Since the test-condition is evaluated at the bottom of the loop , the do construct provides an exit-controlled loop and therefore the body of the loop is always executed once. The format of do while statement is as follows do { body of the loop } while (test condition); Example for do while statement /*******************************************************/ /* Printing of multiplication table */ /*******************************************************/ #define colmax 10 #define rowmax 12 main() { int row,column,y; row = 1; printf(“ MULTIPLICATION TABLE \n”); printf(“_________________________________\n”); /* OUTER LOOP BEGINS */ do

25

Page 26: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

{ column = 1; /* INNER LOOP BEGINS */ do { column = 1; /* do { y = row * column; printf(“%4d”,y); column = column +1; } while (column <= COLMAX); /* INNER LOOP BEGINS */ printf(“\n”); row = row + 1; } while( row <=ROWMAX); /* OUTER LOOP ENDS */ printf(“_______________________________________”) }

26

Page 27: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SWITCH STATEMENT The switch statement is another form of the multi way decision. It is well structured, but can only be used in certain cases where;

●Only one variable is tested, All branches must depend on the value of that variable. The variable must be an integral type.(int long, short or char). ●Each possible value of the variable can control a single branch. A final ,catch all default branch may optionally be used to trap all unspecified cases.

Syntax Switch(expression) { case value-1: block-1 break; case value-2: block-2 break; default: default-block break; } Hopefully an example will clarify things. This is a program which accepts four mathematical symbols + , - , * , / .Then the program accepts two integers a & b & displays the output as the value of a + b , a – b , a * b or a / b depending upon the symbol entered. #include<stdio.h> main() { int a,b; char c; printf(“Enter the symbol \n”); scanf(“%c”,&c); switch(c)

27

Page 28: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

{ case ‘+’ : printf(“Enter the values for a & b\n”);

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

printf(“a + b = %d\n”,a+b);

break;

case ‘-’ : printf(“Enter the values for a & b\n”);

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

printf(“a - b = %d\n”,a-b);

break;

case ‘*’ : printf(“Enter the values for a & b\n”);

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

printf(“a * b = %d\n”,a*b);

break;

case ‘/’ : printf(“Enter the values for a & b\n”);

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

printf(“a / b = %d\n”,a/b);

break;

default : printf(“Invalid operator\n”);

}

}

Here, each interesting case is listed with a corresponding action. The control

passes to the statement whose ‘case constant- expression’ matches the value

of switch (expression). The switch statement can include any number of

case instances, but no two case constants within the same switch statement

can have the same value. Execution of the statement body begins at the at

the selected statement and proceeds until the end of the body or until a

28

Page 29: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

break statement transfers control out of the body. The break statement

prevents any further statements from being executed by leaving the switch.

The default statement is executed if no case constant-expression is equal

to the value of switch(expression). If the default statement is omitted and

no case match is found, none of the statements in the switch body are

executed. There can be at most one default statement. The default statement need not come at the end, it can appear anywhere in the body of

the switch statement. A case or default label can only appear inside a

switch statement. Switch statement can be nested. A single statement can

carry multiple case labels as the following example shows:

case ‘a’ :

case ‘b’ :

case ‘c’ :

case ‘d’ :

case ‘e’ :

case ‘f’ : printf(“HELLO”);

In this example, if switch(expression) equals any letter between ‘a’ and ‘f’,

HELLO will be printed.

Microsoft C does not limit the number of case values in a switch statement.

The number is limited only by the available memory. ANSI C requires at

least 257 case labels be allowed in a switch statement.

29

Page 30: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ARRAYS

Introduction

An array is a group of related data items that share a common name. For instance, we can define an array name salary to represent a set of salaries 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]

represents the salary of the 10th employee. While the complete set of values is referred to as an array, the individual values are called elements. Arrays can be of any variable type.

The ability to use a single name to represent a collection of items and to refer to an item by specifying the item number enables us to develop concise and efficient programs.

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 a one dimensional array. In mathematics, we often deal with variables that are single subscripted. For instance, we use the equation.

To calculate the average of n values of x. The subscripted variable xi refers to the ith element of x. In C, single- subscripted variable xi can be expressed as

x[1], x[2], x[3], ……………….. x[n]

The subscript can begin with number 0. That is

x [0]

is allowed

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

30

Page 31: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

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

Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid. Similarly,

Int group [10];

Declares the group as an array to contain a maximum of 10 integer contents.

The C language treats character strings simply as arrays 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 be hold maximum of 10 characters.

Initialization of Arrays

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

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

Will initialized the first three elements to 0.0, 15.75, and -10.0 and the remaining two elements to zero.

Initialization of arrays in C suffers two drawbacks.

31

Page 32: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

1. There is no convenient way to initialize only selected elements.

2. There is no shortcut method for initializing a large number of array elements like the one available in FORTRAN.

Program

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

/* PROGRAM SHOWING ONE DIMENSIONAL ARRAY */

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

Main ( )

{

Int I;

Float x [10], value, total;

/*…………………Reading values into array………………*/

Print f(“ENTER 10 REAL NUMBERS\n”);

For (I = 0 ; I < 10; I + +)

{

Scan f (“% f”, & value);

X[i] = value;

}

/* ……………..COMPUTATION OF TOTAL ……………….*/

Total = 0.0;

For (I = 0; I < 10; I + + )

Total = total + x[i] * x[i]

/* ……………PRINTING OF x[i] VALUES AND TOTAL ………*/

Print f (“\n”);

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

Print f ( “x [ % 2d] = % 5.2f\n”, I +1, x[i]);

32

Page 33: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Print f (“\ntotal = % 2f\n”, total);

}

Output

Enter 10 real numbers

1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10. 10

X[1] = 1.10

X[2] = 2.20

X[3] = 3.30

X[4] = 4.40

X[5] = 5.50

X[6] = 6.60

X[7] = 7.70

X[8] = 8.80

X[9] = 9.90

X[10] = 10.10

Total = 446.86

TWO DIMENSIONAL ARRAYS

So far we have discussed the array variable that can store a list of values. There will be situations where a table of values will have to be stored. Consider the following data table, which shows the value of sales of three items by four salesgirls:

Item 1 Item2 Item3

33

Page 34: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Salesgirl # 1 310 275 365

Salesgirl # 2 210 190 325

Salesgirl # 3 405 235 240

Salesgirl # 4 260 300 380

The table contains a total of 12 values, three in each line. We can think of this table as a matrix consisting of four rows and three columns. Each row represents the values of sales by a particular salesgirl and each column represents the values of sales of a particular item.

In mathematics, we represent a particular value in a matrix by using two subscripts such as Vij. Here v denotes the entire matrix and vij refers to the value in the ith row and j the column. For example, in the above table v23 refers to the value 325.

C allows us to define such tables of items by using two dimensional arrays. The table discussed above can be defined in C as

V [4] [3]

Two dimensional arrays are declared as follows:

Static type array- name [row - size] [column – size];

Note that unlike most other languages, which use one pair of parentheses with commas to separate array sizes, C places each size in its own set of brackets.

/* PROGRAM SHOWING TWO DIMENSIONAL ARRAY */

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

# define MAXGIRLS 4

# define MAXITEMS 3

Main ( )

{

Int value [MAXGIRLS] [MAXITEMS];

Int girl – total [MAXGIRLS], item – total [MAXITEMS];

34

Page 35: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Int I,j, grand – total;

/*………READING VALUES AND COMPUTING girl – total ………………*/

Print f(“Input data\n”);

Printf (“Enter values, one at a time, row – wise \ n\n”);

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

{ Girl – total [i] = 0;

For(j = 0; j< MAXITEMS ; j + +)

}

Scan f (“% d”, & value [i] [j];

Girl-total [i] = girl – total [i] + value [i] [j];

}

}

/* ……………..COMPUTING item- total ……………….*/

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

item-total [j] = 0;

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

item-total[j] = item-total[j]+ value [i] [j];

/* ……………COMPUTING grand- total………… ………*/

grand-total [j] = 0;

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

grand-total= grand-total + girl- total [i] ;

/*……………PRINTING OF RESULTS………………..*/

printf(“\n GIRLS TOTALS\n\n”);

for (I = 0; I < MAXGIRLS; i + +)

printf (“Salesgirl [%d] = %d\n”, I + 1, girl – total [i]);

35

Page 36: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

printf (“\n ITEM TOTALS\n\”);

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

printf(“item[%d\n”, j+1, item-total [j]);

printf (“\n Grand total = %d\n”, grand – total);

}

Output

Input data

Enter values, one at a time, row- wise

310 257 365

210 190 325

405 235 240

260 300 380

GIRLS TOTALS

Sales girl [1] = 950

Sales girl [2] = 725

Sales girl [3] = 880

Sales girl [4] = 940

ITEM TOTALS

Item [1] = 1185

Item [2] = 1000

Item [3] = 1310

Grand Total = 3495

INITIALIZING TWO DIMENSIONAL ARRAYS

Like the one dimensional arrays, two dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. For example,

36

Page 37: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Static int table [2] [3] = {0, 0, 0, 1, 1,1};

Initializes the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can be equivalently written as

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 a matrix as shown below:

Static int table [2] [3] = {

{ 0,0,0},

{1, 1,1}

};

Note the syntax of the above statements. Commas are required after each brace that closes off a row, except in the case of the last row.

If the values are missing in an initializer, they are automatically set to zero, for instance, the statement

Static int table [2] [3] = {

{0, 0, 0},

{1,1,1}

};

Note the syntax of the above statements. Commas are required after each brace that closes off a row, except in the case of the last row.

If the values are missing in an initializer, they are automatically set to zero. For instance, the statement

Static int table [2], [3] = {

{1,1},

{2}

};

37

Page 38: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Will initialize the first two elements of the first row tone, the first element of the second row to two, and all other elements to zero.

When all the elements are to be initialized to zero, the following short cut method may be used.

Static int m [3] [5] = { {0}, {0}, {0}};

The first element of each row is explicitly initialized to zero while other elements are automatically initialized to zero.

MULTIDIMENSIONAL ARRAYS

C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The general form of a multidimensional array is

Type array – name [s1] [s2] [s3] ……… [sm]

Where si is the size of the ith dimension. Some examples are

Int survey [3] [5] [12];

Float table [5] [4] [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.

Type array survey may represent a survey data of rainfall during the last three years from January to December in five cities.

Remember that a three dimensional array can be represented as a series of two dimensional arrays as shown below:

Year 1

38

Page 39: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Month city

1 2 …………….. 12

1

.

.

5

Year 2

Month city

1 2 …………….. 12

1

.

.

5

39

Page 40: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

FUNCTIONS IN C What Is a Function? This chapter approaches the question "What is a function?" in two ways. First, it tells you what functions are, and then it shows you how they're used. "Scope and Storage Classes in C," you might have noticed that a function definition is always given first, before the function is called from a main() function. In fact, you can put a function definition anywhere you want, as long as you keep the function declaration at the first place before the function is called. You'll learn about many function features from the following topics covered in this lesson:

• Function declarations • Prototyping • Values returned from functions • Arguments to functions

In addition, several C library functions and macros, such as time(), localtime(), asctime(), va_start(), va_arg(), and va_end() are introduced in this hour. Declaring Functions As you know, you have to declare or define a variable before you can use it. This is also true for functions. In C, you have to declare or define a function before you can call it. How a Function Works A C program doesn't execute the statements in a function until the function is called by another part of the program. When a function is called, the program can send the function information in the form of one or more arguments. An argument is program data needed by the function to perform its task. The statements in the function then execute, performing whatever task each was designed to do. When the function's statements have finished, execution passes back to the same location in the program that called the function. Functions can send information back to the program in the form of a return value.

40

Page 41: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Declaration Versus Definition According to the ANSI standard, the declaration of a variable or function specifies the interpretation and attributes of a set of identifiers. The definition, on the other hand, requires the C compiler to reserve storage for a variable or function named by an identifier. A variable declaration is a definition, but a function declaration is not. A function declaration alludes to a function that is defined elsewhere and specifies what kind of value is returned by the function. A function definition defines what the function does, as well as gives the number and type of arguments passed to the function. A function declaration is not a function definition. If a function definition is placed in your source file before the function is first called, you don't need to make the function declaration. Otherwise, the declaration of a function must be made before the function is invoked. For example, the printf() function is used in almost every sample program in this book. Each time, it include a header file, stdio.h, because the header file contains the declaration of printf(), which indicates to the compiler the return type and prototype of the function. The definition of the printf() function is placed somewhere else. In C, the definition of this function is saved in a library file that is invoked during the linking states. Specifying Return Types A function can be declared to return any data type, except an array or function. The return statement used in a function definition returns a single value whose type should match the one declared in the function declaration. By default, the return type of a function is int, if no explicit data type is specified for the function. A data type specifier is placed prior to the name of a function like this: data_type_specifier function_name(); Here data_type_specifier specifies the data type that the function should return. function_name is the function name that should follow the rule of naming in C.

41

Page 42: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

In fact, this declaration form represents the traditional function declaration form before the ANSI standard was created. After setting up the ANSI standard, the function prototype is added to the function declaration. Using Prototypes Before the ANSI standard was created, a function declaration only included the return type of the function. With the ANSI standard, the number and types of arguments passed to a function are allowed to be added into the function declaration. The number and types of an argument are called the function prototype. The general form of a function declaration, including its prototype, is as follows: data_type_specifier function_name( data_type_specifier argument_name1, data_type_specifier argument_name2, data_type_specifier argument_name3, . . . data_type_specifier argument_nameN, ); The purpose of using a function prototype is to help the compiler check whether the data types of arguments passed to a function match what the function expects. The compiler issues an error message if the data types do not match. Although argument names, such as argument_name1, argument_name2, and so on, are optional, it is recommended that you include them so that the compiler can identify any mismatches of argument names. Making Function Calls When a function call is made, the program execution jumps to the function and finishes the task assigned to the function. Then the program execution resumes after the called function returns. A function call is an expression that can be used as a single statement or within other statements. An example of declaring and defining functions, as well as making function calls is given below

42

Page 43: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Prototyping Functions In the following subsections, we're going to study three cases regarding arguments passed to functions. The first case is a function that takes no argument; the second one is a function that takes a fixed number of arguments; the third case is a function that takes a variable number of arguments. Functions with No Arguments The first case is a function that takes no argument. For instance, the C library function getchar() does not need any arguments. It can be used in a program like this: int c; c = getchar(); As you can see, the second statement is left blank between the parentheses (( and )) when the function is called. In C, the declaration of the getchar() function can be something like this: int getchar(void); Note that the keyword void is used in the declaration to indicate to the compiler that no argument is needed by this function. The compiler will issue an error message if somehow there is an argument passed to getchar() later in a program when this function is called. Therefore, for a function with no argument, the void data type is used as the prototype in the function declaration. Using void in function declarations. 1: /* Functions with no arguments */ 2: #include <stdio.h> 3: #include <time.h> 4: 5: void GetDateTime(void); 6: 7: main() 8: { 9: printf("Before the GetDateTime() function is called.\n"); 10: GetDateTime();

43

Page 44: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

11: printf("After the GetDateTime() function is called.\n"); 12: return 0; 13: } 14: /* GetDateTime() definition */ 15: void GetDateTime(void) 16: { 17: time_t now; 18: 19: printf("Within GetDateTime().\n"); 20: time(&now); 21: printf("Current date and time is: %s\n", 22: asctime(localtime(&now))); 23: } OUTPUT The following output will be obtained when the above program is run Before the GetDateTime() function is called. Within GetDateTime(). Current date and time is: Sat Apr 05 11:50:10 1997 After the GetDateTime() function is called. Functions with a Fixed Number of Arguments int function_1(int x, int y); contains the prototype of two arguments, x and y. To declare a function with a fixed number of arguments, you need to specify the data type of each argument. Also, it's recommended to indicate the argument names so that the compiler can have a check to make sure that the argument types and names declared in a function declaration match the implementation in the function definition. Prototyping a Variable Number of Arguments The syntax of the printf() function is int printf(const char *format[, argument, ...]); Here the ellipsis token ... (that is, three dots) represents a variable number of arguments. In other words, besides the first argument that is a character

44

Page 45: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

string, the printf() function can take an unspecified number of additional arguments, as many as the compiler allows. The brackets ([ and ]) indicate that the unspecified arguments are optional. The following is a general form to declare a function with a variable number of arguments: data_type_specifier function_name( data_type_specifier argument_name1, ... ); Note that the first argument name is followed by the ellipsis (...) that represents the rest of unspecified arguments. For instance, to declare the printf() function, you can have something like this: int printf(const char *format, ...); Recursion The term recursion refers to a situation in which a function calls itself either directly or indirectly. Indirect recursion occurs when one function calls another function that then calls the first function. C allows recursive functions, and they can be useful in some situations. For example, recursion can be used to calculate the factorial of a number. The factorial of a number x is written x! and is calculated as follows: x! = x * (x-1) * (x-2) * (x-3) * ... * (2) * 1 However, you can also calculate x! like this: x! = x * (x-1)! Going one step further, you can calculate (x-1)! using the same procedure: (x-1)! = (x-1) * (x-2)! You can continue calculating recursively until you're down to a value of 1, in which case you're finished. The following program uses a recursive function to calculate factorials. Because the program uses unsigned integers, it's limited to an input value of 8; the factorial of 9 and larger values are outside the allowed range for integers.

45

Page 46: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

This is Using a recursive function to calculate factorials. 1: /* Demonstrates function recursion. Calculates the */ 2: /* factorial of a number. */ 3: 4: #include <stdio.h> 5: 6: unsigned int f, x; 7: unsigned int factorial(unsigned int a); 8: 9: main() 10: { 11: puts("Enter an integer value between 1 and 8: "); 12: scanf("%d", &x); 13: 14: if( x > 8 || x < 1) 15: { 16: printf("Only values from 1 to 8 are acceptable!"); 17: } 18: else 19: { 20: f = factorial(x); 21: printf("%u factorial equals %u\n", x, f); 22: } 23: 24: return 0; 25: } 26: 27: unsigned int factorial(unsigned int a) 28: { 29: if (a == 1) 30: return 1; 31: else 32: { 33: a *= factorial(a-1); 34: return a; 35: } 36: } Out Put:- Enter an integer value between 1 and 8: 6 6 factorial equals 720

46

Page 47: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ANALYSIS: The first half of this program is like many of the other programs you have worked with so far. It starts with comments on lines 1 and 2. On line 4, the appropriate header file is included for the input/output routines. Line 6 declares a couple of unsigned integer values. Line 7 is a function prototype for the factorial function. Notice that it takes an unsigned int as its parameter and returns an unsigned int. Lines 9 through 25 are the main() function. Lines 11 and 12 print a message asking for a value from 1 to 8 and then accept an entered value. Lines 14 through 22 show an interesting if statement. Because a value greater than 8 causes a problem, this if statement checks the value. If it's greater than 8, an error message is printed; otherwise, the program figures the factorial on line 20 and prints the result on line 21. When you know there could be a problem, such as a limit on the size of a number, add code to detect the problem and prevent it. The recursive function, factorial(), is located on lines 27 through 36. The value passed is assigned to a. On line 29, the value of a is checked. If it's 1, the program returns the value of 1. If the value isn't 1, a is set equal to itself times the value of factorial(a-1). The program calls the factorial function again, but this time the value of a is (a-1). If (a-1) isn't equal to 1, factorial() is called again with ((a-1)-1), which is the same as (a-2). This process continues until the if statement on line 29 is true. If the value of the factorial is 3, the factorial is evaluated to the following: 3 * (3-1) * ((3-1)-1) DON'T use recursion if there will be several iterations. (An iteration is the repetition of a program statement.) Recursion uses many resources, because the function has to remember where it is. Where the Functions BelongYou might be wondering where in your source code you should place your function definitions. For now, they should go in the same source code file as main You can keep your user-defined functions in a separate source-code file, apart from main(). This technique is useful with large programs and when you want to use the same set of functions in more than one program. This technique is discussed on Day 21, "Advanced Compiler Use."

47

Page 48: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Summary A function declaration alludes to a function that is defined elsewhere, and specifies what type of arguments and values are passed to and returned from the function as well. A function definition reserves the memory space and defines what the function does, as well as the number and type of arguments passed to the function. A function can be declared to return any data type, except an array or a function. The return statement used in a function definition returns a single value whose type must be matched with the one declared in the function declaration. A function call is an expression that can be used as a single statement or within other expressions or statements. The void data type is needed in the declaration of a function that takes no argument. To declare a function that takes a variable number of arguments, you have to specify at least the first argument, and use an ellipsis (...) to represent the rest of the arguments passed to the function. va_start(), va_arg(), and va_end(), all included in stdarg.h, are needed in processing a variable number of arguments passed to a function. time(), localtime(), and asctime() are three time functions provided by C. They can be used together to obtain a character string that contains information of local date and time based on the calendar time.

PARAMETR PASSING BETWEEN FUNCTIONS The mechanism used to convey information to the function is called argument or parameter. The format string and the list of variables used inside the parameter in these functions are arguments. These are of two types. 1.Call by value 2.Call by reference.

48

Page 49: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Call by value In this method the value of the actual arguments in the calling functions are copied in to corresponding formal arguments of called function. With this method the changes made to to the formal arguments in called function have no effect on the values of actual arguments in calling function. Consider the following program , /*Sending and receiving values between function*/ main( ) { int a b product; printf(“Enter two numbers”); scanf(“%d%d”,&a,&b); product=calproduct(a,b); printf(“\n %d %d product=%d”,a,b product); /here values of a &b remains unchanged/ } int calproduct( int x , int y) { int d; d=x*y; return (d); } In this program, in main( ) we receive the values of a , b through the keyboard and then output the product of a,b .However the calculation of product is done in a different function called calproduct( ).The variables a ,b are called ‘actual argument’, whereas the variables x,y are called formal arguments. Any number of arguments can be passed to a function being called . However the type, order and number of the actual and formal arguments must always be same. Instead of using different variable names x ,y ,we could have used the same variable names a,b. But the compiler would still treat them as different variables. So if the value of a formal argument is changed in called function, the corresponding changes do not take place in the calling function. A function can return only one value so return(a,b) is invalid statement. There are two methods of declaring the formal arguments . calproduct( x,y) int x,y; Another methode is , calproduct(int x,int y)

49

Page 50: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Call by reference In call by reference method we are passing the address of the data as argument. This means that using these address we would have an access to actual argument and hence we would able to manipulate them. The following program illustrate this fact main( ) { int a=10,b=20; swapr(&a,&b); printf(“\na=%d b = %d”,a,b); } swapr(int *x,int *y) { int t ; t =*x ; *x =*y ; *y=t ; } the output of this program would be a=20 b=10 Function with arrays We can pass array also as a argument to the function. To pass an array to a called function it is sufficient to list name of the array without any subscript and the size of the array as argument. When we deal with array arguments we should remember that if a function changes the values of an array these changes will be made to the original array that passed to the original array that passed to the function /*Program to find smallest number in array*/ #include<stdio.h> int smallest(int *arr) ; main ( ) { int arr [10] , i ; clrscr( ); printf(“Enter 10 elements of an array\n”); for(i=0;i<=9;i++) scanf(“%d”,&arr[i]); n=smallest(arr); printf(“%d”,n); } int smallest(int *arr) ;

50

Page 51: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

{ int n=*arr for(i=o;i<=9;i++) { if (*arr+i)< n) n=*(arr+i) } Return statement. Return statement returns control back to the main program .It serves two purposes: (1). On executing the return statement it immediately transfers the control back to the calling program. (2) it returns the value present in the parentheses after return to the calling program. A function, depending on whether arguments are present or not and whether a value is returned or not may belong to one of the following categories. 1.Function with no arguments and no return value. 2. Function with argument and no return values. 3. Function with arguments and return values.

If we want that a called function should not return any value, in that case, we must mention so by using keyword void.

51

Page 52: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

POINTERS Every variable when declared in occupies certain memory location. In C it is possible to access and display the address of the memory location of variable using & operator with variable name. The pointer variable is needed to store the memory address of any variable. The pointer is denoted by asterisk(*) symbol. A pointer basically is a memory variable that stores a memory address .Pointer can have any name that is legal for other variables and is declared in the same fashion like other variable but it is always denoted by * operator. Features of pointers

- Pointer saves memory space. - Execution time with pointer is fast because data is manipulated with

address - Memory is accessed efficiently with pointers. - Pointers are useful for representing two dimensional and multi

dimensional arrays Pointer declaration

Pointer variable can be declared as follows Int *x; Char *y; Float *f;

The first statement is an integer pointer- it holds an address of an integer variable The second statement is an character pointer- it holds an address of a character variable The third statement is an float pointer- it holds an address of a floating point variable Accessing pointers ‘*’is used to access the value at address and ‘&’ is used to access the address of the variable %u is used with printf statement to print the address of a variable. Address of any type of variable is whole number. Given below is a program which use pointer to print address and value of a variable. #include<stdio.h> main() { int n,*k; printf(“Enter a number”); scanf(“%d”,&n); k=&n; printf(“Address of n is %u”,k); printf(“Value of n is %d”,*k);

52

Page 53: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Output Enter a number 25 Address of n is 4072 Value of n is 25 In the above example address of variable n is assigned to pointer variable k. Hence k is pointing to n. Value of the variable n is displayed using the pointer *k. Pointers and arrays Array name by itself is an address pointer. it points to the address of the first element. The element of the array together with their address can be displayed by using array name itself. Array elements are always stored in continuous memory location. No separate pointer variable is needed to access the address of the array variable. For a two dimensional array the first argument is taken as row number and second argument is taken as column number. To display the elements of two dimensional array it is essential to have’&’ operator as pre fix with an array name followed by element numbers. Pointer to pointer. Pointer is known as variable containing address of another variable. The pointer variable also have an address. The pointer variable containing address of another variable is called a pointer to pointer. This chain can be continued to any extend. To represent pointer to pointer we declare the variable with two asterisks. Example. Int **q; Void pointers Pointers can also be declared as void type. Void type cannot be differenced without explicit type conversion. This is because being void compiler cannot determine the size of the object that pointer points to. Though void pointer declaration is possible, void variable declaration is not allowed. Pointer as reference parameter Call by reference In call by reference method we are passing the address of the data as argument. This means that using these address we would have an access to actual argument and hence we would able to manipulate them.the following program illustriate this fact

main( ) { int a=10,b=20; swapr(&a,&b); printf(“\na=%d b = %d”,a,b);

} swapr(int *x,int *y)

53

Page 54: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

{ int t ; t =*x ; *x =*y ; *y=t ;

} Output a=20 b=10

Structures and pointers A structure is a collection of one or more variables of different

data types grouped together under a single name. By using structures we can make a group of variables arrays pointers etc.

Pointers and structures We know that pointer is a variable that holds the address of

another data variable. The variable may be of any data type , Ie. Int, float or char. In the same way we can also define pointer to structures. Here starting address of the member variables can be accessed. Thus such pointers are called structure pointer.

Example:-

Struct book { char name[25] ; char author[25]; int pages; }; struct book *pt;

in the above example*ptr is the pointer to the structure ‘book’. The syntax for using pointer with member is as given below.

1) ptr name 2)ptr author 3)ptr pages. By executing these three statements starting address of each member is

estimated.

Dynamic memory allocation

Dynamic memory allocation is a technique in which programs determine as they are running where to store some information. You need dynamic allocation when the amount of memory you need, or how long you continue to need it, depends on factors that are not known before the program runs.

For example, you may need a block to store a line read from an input file; since there is no limit to how long a line can be, you must

54

Page 55: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

allocate the memory dynamically and make it dynamically larger as you read more of the line.

Or, you may need a block for each record or each definition in the input data; since you can't know in advance how many there will be, you must allocate a new block for each record or definition as you read it.

When you use dynamic allocation, the allocation of a block of memory is an action that the program requests explicitly. You call a function or macro when you want to allocate space, and specify the size with an argument. If you want to free the space, you do so by calling another function or macro. You can do these things whenever you want, as often as you want.

Dynamic allocation is not supported by C variables; there is no storage class “dynamic”, and there can never be a C variable whose value is stored in dynamically allocated space. The only way to get dynamically allocated memory is via a system call (which is generally via a GNU C library function call), and the only way to refer to dynamically allocated space is through a pointer. Because it is less convenient, and because the actual process of dynamic allocation requires more computation time, programmers generally use dynamic allocation only when neither static nor automatic allocation will serve.

For example, if you want to allocate dynamically some space to hold a struct foobar, you cannot declare a variable of type struct foobar whose contents are the dynamically allocated space. But you can declare a variable of pointer type struct foobar * and assign it the address of the space. Then you can use the operators `*' and `->' on this pointer variable to refer to the contents of the space:

{ struct foobar *ptr = (struct foobar *) malloc (sizeof (struct foobar)); ptr->name = x; ptr->next = current_foobar; current_foobar = ptr; }

55

Page 56: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

STRUCTURES AND UNIONS IN C STRUCTURE A structure is a collection of one or more variables, possibly of different types, grouped together under a single name. It is a convenient tool for handling a group of logically related data items. Structure Definition A structure definition creates a format that may be used to declare structure variables. Let us use an example to illustrate the process of structure definition and the creation of structure variables. Consider a book database consisting of book name, author, number of pages, and price. We can define a structure to hold this information as follows: struct book_bank { char titile[20]; char author[15]; int pages; float price; }; The keyword struct declares a structure to hold the details of four fields, namely titile, author, pages, and price. These fields are called structure elements or members. Each member may belong to a different type of data. book_bank is the name of the structure and is called the structure tag. The tag name used subsequently to declare variables that have the tag’s structure. The general format of a structure definition is as follows: struct tag_name { data_type member 1; data_type member 2; ………. ……….. ………. ……….. }; Declaring a structure We can declare structure variable using the tag name anywhere in the program.For example the variables b1, b2, b3 can be declared to be of the type struct book_bank, as struct book_bank b1, b2, b3; Each one of these variables has four members as specified by the template.The complete declaration might look like this: struct book_bank

56

Page 57: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

{ char titile[20]; char author[15]; int pages; float price; }; struct book_bank b1,b2,b3 Remember that the members of a structure themselves are not variables. They do not occupy any memory until they are associated with the structure variables such as b1. In defining a structure you may note the following syntax:

1. The template is terminated with a semicolon. 2. While the entire declaration is considered as a statement, each member

is declared independently for its name and type in a separate statement inside the template.

3. The tag name such as book_bank can be used to declare structure variable of its type, later in program.

Accessing Structure Element Having declared the structure type and the structure variable. Let us see the element of the structure can be accessed. In arrays we can access individual element of an array using a subscript. Structure use a different scheme. They use a dot(.) operator. So refer to pages of the structure defined in above example we have to use b1.pages similarly to refer to price we would use, b1.price. Note that before the dot there must always be a structure variable and after the dot there must always be a structure element. For example, main( ) { struct book_bank { char name[15]; float price; int pages; }; struct book_bank b1,b2,b3 printf(“ Enter names, prices & no. of pages of 3 books\n”); scanf(“%c %f %d”,&b1.name,&b1.price,&b1.pages); scanf(“%c %f %d”,&b2.name,&b2.price,&b2.pages); scanf(“%c %f %d”,&b3.name,&b3.price,&b3.pages); printf(“ Details You Entered\n”); printf(“\n%c %f %d”,b1.name,b1.price,b1.pages);

57

Page 58: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

printf(“\n%c %f %d”,b2.name,b2.price,b2.pages); printf(“\n%c %f %d”,b3.name,b3.price,b3.pages); } Sample Input and Out put, Enter names, prices & no. of pages of 3 books A 100.00 345 B 256.50 682 K 233.70 512 Details You Entered A 100.00 345 B 256.50 682 K 233.70 512 How Structure Elements are Stored Whatever be the elements of a structure, they are always stored in contiguous memory location. main( ) { struct book_bank { char name[15]; float price; int pages; }; struct book_bank b1={‘B’,130.00,550}; printf(“ \nAddress of name=%u”,&b1.name); printf(“ \nAddress of price=%u”,&b1.price); printf(“ \nAddress of page=%u”,&b1.page); } Output: Address of name = 65518 Address of price = 65519 Address of pages = 65523 Arrays of Structures We use structures to describe the format of a number of related variables.We can declare an array of structures, each element of the array representing a structure variable. For example, struct class student[100]; defines an array called student, that consist of 100 elements. Each element is defined to be of the type struct class. Consider the following declaration.

58

Page 59: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

struct marks { int subject 1; int subject 2; int subject 3; }; main( ) { static struct marks student[3] = {{45,68,46},{65,83,92},{75,83,39}}; This declares the student as an array of three element student[0], student[1], and student[2] and initializes their members as follows: student[0].subject1 = 45; student[0].subject1 = 68; ………. ………. student[2].subject1 = 39; Additional Features of Structure Following are the major additional features of structure, 1. The value of a structure variable can be assigned to another structure variable of the same type using the assignment operator. 2. One structure can be nested within another structure. 3. Like an ordinary variable, a structure variable can also be passed to a function. 4. Pointer can be used in structure. Such pointers are known as ‘structure pointers’. UNIONS Unions are a concept borrowed from structures and therefore follow the same syntax as structures. However, there is major distinction between them in terms of storage. In structures, each member has its own storage location,whereas all the members of a union use the same location. This implies that, although a union may contain many members of different types, it can handle only one member at a time. Like structures, a union can be declared using the keyword union as follow: union item { int m; float x; char c; } code; This declares a variable code of type union item. The union contain three members, each with a different data type. However we can use only one at a

59

Page 60: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

time. This is due to the fact that only one location is allocated for a union variable, irrespective of its size. The compiler allocates a piece of storage that is large enough to hold the largest variable type in the union. To access a union member, we can use the same syntax that we use for structure members. That is code.m code.x code.c are all valid member variables. During accessing, we should make sure that we are accessing the member whose value is currently stored. For example, the statement such as code.m = 379; code.x = 786.63 printf(“%d”,code.m); would produce erroneous output. In effect, a union creates a storage location that can be used by any one of its members at a time. When a different member is assigned a new value supercedes the previous member’s value. Unions may be used in all places where a structure is allowed.

60

Page 61: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

FILES

Many applications require that information be written to or read from any auxiliary memory device. Such information is stored on the memory device is in the form of a data file. Thus, data files allow us to store information permanently, and to access and alter that information whenever necessary .There are two different types of data files, called stream-oriented data files ,and system oriented data files.

Stream oriented data files can be subdivided into two categories. In the first category are text files consisting of consecutive characters. These characters can be interpreted as individual data items, or as components of strings or numbers. The second category of stream-oriented data files, often referred to as unformatted data files, organizes data in to blocks containing contiguous bytes of information. These blocks represent more complex data structures, such as arrays and structures. System oriented data files are more closely related to the computer’s operating system than stream oriented data files. They are some what more complicated to work with ,though their use may be more efficient for certain kinds of applications. Different file operations in C programming are as follows-

• Open a file • Read the file or write the data in the file • Close the file.

OPENING OF A FILE When we store a record in the file then at first we need a temporary area in the memory where we store the data/records then we transfer it to file.For storing these records in the memory, we use the pointer which points the starting address where this data/record is stored. We write this as- FILE *p; Here p is a pointer of file type. For declaring any variable to file type pointer ,it is necessary to write FILE in capital and then pointer variable name. For opening a file we use library function fopen().First we declare pointer variable and fopen() as file type pointer.We write this as – FILE *p,*fopen();

Then p=fopen(“filename”,mode); Here filename is the name of data file where data/record is stored. Mode decides which operation(read,write or append ) is to be performed with the data file. MODES 1·write(w) This mode open a new file for writing a record, if the filename already exists then using this mode, the previous data/records are erased and the new data/record entered is written in to the file. Ex-

61

Page 62: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

p=fopen(“rec.dat”,”w”); Here rec.dat is the filename and w is the mode. 2·append(a) This mode open a file for appending a data/record. If the file does not exist then the work of this mode is same as “w” mode. Ex- p=fopen(“rec.dat”,”a”); Here rec.dat is the filename and can be already exist or a new file. 3·read(r) This mode is used for opening a file for reading purpose only. Ex- p=fopen(“rec.dat”,”r”); If the file rec.dat does not exist then compiler return NULL to the file pointer. 4·write+read(w+) This mode is used both for reading and writing purpose.This is same as the “w” mode but can also read the record which is stored in the file. Ex- p=fopen(“rec.dat”,”w+”); 5·append+read(a+) This mode is used both for reading and appending purpose. This is same as the “a” mode but can also read the record which is stored in the file. Ex- p=fopen(“rec.dat”,”a+”); 6·read+write(r+) This mode is used both for reading and writing purpose.We can read the record and also write the record in the file. Ex- p=fopen(“rec.dat”,”r+”); CLOSING A FILE The files which are opened from the fopen() function must be closed at end of the program.this is written as-

fclose(p); if the opening file is more than one then we close all the file. fclose(p1); fclose(p2); etc…

62

Page 63: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

FILE INPUT –OUTPUT FUNCTIONS 1·fprintf() This function is same as the printf() function but it writes the data into the file,so it has one more parameter that is the file pointer. Syntax- fprintf(fptr,”contol character”,variable-names); /* program to understand the use of fprintf() */

main() { FILE *fopen(),*p; char name[10]; p=fopen(“rec.dat”,”w+”); printf(“Enter your name”); scanf(“%s”,name);

fprintf(p,“My Name is %s ”,name); fclose(p);

} 2·fscanf() This function is same as the scanf() function but this reads the data from the file ,so this has one or more parameter that is the file pointer. Syntax- fscanf(fptr,”control character”,&variable-names); /*Program to understand the use of fscanf() */

main() { FILE *fopen(),*p; char name[10];int sal; p=fopen(“rec.dat”,”r”); fscanf(p,”%s %d”,name,&sal);

printf(“NAME\t SALARY\n”); while(! feof (p)) { printf(“%s\t%d\n”,name,sal); fscanf(p,”%s%d”,name,&sal); } fclose(p);

}

63

Page 64: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

3·fgetc() This function is same as the getc() function.It also read a single character from a given file and increments the file pointer position. It returns EOF,If the end of the of the file is reached or it encounters an error. Syntax-

fgetc(fptr); ch=fgetc(fptr); where fptr is a file pointer

/*Program to understand the use of fgetc() function */ main()

{ FILE *fopen(),*p;

int ch; if((p=fopen(“rec.dat”,”r”))!=NULL) {while((ch=fgetc(p))!=EOF) printf(“%c”,ch);

} fclose(p);

} 4·fputc() This function writes the character to the specified stream at the current file position and increments the file position indicator. Syntax-fputc(ch,fptr);

where fptr is a file pointer and ch is a variable written to the file which is pointed by the file pointer. /*Program to understand the use of fputc() function */ main()

{ FILE *fopen(),*fptr,*fptr1;

char name[10],ch; printf(“Enter the file name”); scanf(“%s”,name); if((fptr=fopen(name,”r”))!=NULL) { fptr1=fopen(“rec.txt”,”w”);

while(ch=fgetc(fptr)!=EOF) fputc(ch,fptr1);

} fclose(fptr); fclose(fptr1);

}

64

Page 65: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

5·fgets() This function is used to read a string from a given file and copies the string to a memory location which is referenced by an array. Syntax-fgets(sptr,max,fptr) ; When sptr is a string pointer,which points to an array,max is the length of the array and fptr is a file pointer which points to a given file. /*program to understand the use of fgets() */ main()

{

FILE *fopen(),*fptr; char name[10],arr[50]; int i=0; printf(“Enter the file name”); scanf(“%s”,name); if((fptr=fopen(name,”r”))!=NULL) { if(fgets(arr,50,fptr)!=NULL)

while(arr[i]!=’\0’){ putchar(arr[i]); i++;}

} fclose(fptr);

}

6·fputs() This function is used to write a string to a given file. Syntax-fputs(sptr,fptr) Where sptr is a string pointer,which points to an array and fptr is a file pointer which points to a given file. /*program to understand the use of fputs() */

main() {

FILE *fopen(),*fptr; char name[10],arr[50]; printf(“Enter the file name”); scanf(“%s”,name); if((fptr=fopen(name,”w”))!=NULL) {

printf(“The string is”); gets (arr); fputs(arr,fptr);

} fclose(fptr);

}

65

Page 66: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Block read/write It is useful to store the block of data in to the file rather than individual elements. Each block has some fixed size,it may be structure or of an array.It is possible that a data file has one or more structures or arrays .So it is easy to read the entire block from file or write entire block to the file .there are two useful function for this purpose-: fread() This function is used to read an entire block from a given file. Syntax-fread(ptr,size,nst,fptr); Where ptr is a pointer which points to the array which receives the structure ,size is the size of the structure,nst is the number of structure and fptr is a file pointer. /*program to understand the use of fread() */ main() { struct rec{ int code;char name[20];

}person[10]; FILE *fptr; int i=0,j; char str[15];

printf(“Enter the file name”); scanf(“%s”,str); if((fptr=fopen(str,”r))!=NULL) {

while(!feof(fptr)) {fread(&person,sizeof(person),1,fptr); i++;}

} for(j=0;j<I;j++) { printf(“Code %d\t”,person[j].code); printf(“Name %s\t”,person[j].name); } close( fptr);

fwrite() This function is used for writing an entire block to a given file. Syntax-fwrite(ptr,size,nst,fptr);

66

Page 67: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Where ptr is a pointer which points to the array of structure in which data is written, size is the size of the structure.nst is the number of structure and fptr is the file pointer. /* Program to understand the use of fwrite() */

main() {

struct rec{ int code;char name[20];

}person[10]; FILE *fptr; int i,j=0,n; char str[15];

printf(“Enter the file name”); scanf(“%s”,str); if((fptr=fopen(str,”w”)!=NULL) { printf(“How many records”);

scanf(“%d”,&n); for(i=0;i<n;i++) {printf(“code”); scanf(“%d”,&person[i].code); printf(“Name”); scanf(“%s”,&person[i].name);} while(j<n) {

fwrite(&person,sizeof(person),1,fptr); j++; }

} fclose(fptr);

} OTHER FILE FUNCTIONS feof() The macro feof() is used for detecting whether the file pointer is at the end of file or not.It returns nonzero if the file pointer is at the end of file, otherwise it returns zero. ferror() The macro ferror() is used for detecting whether an error occur in the file on file pointer or not. It returns the value nonzero if an error,otherwise it returns zero. Syntax-ferror(fptr);

67

Page 68: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

/*Program to understand the use of ferror() */ main() {

FILE *fptr; char name[15],ch;

printf(“Enter the file name”); scanf(“%s”,name); if((fptr=fopen(name,”r”)!=NULL) while((ch=getc(fptr))!=EOF) { printf(“%c”,ch); if(ferror(fptr)) { printf(“Errorin file”); exit(1); } } fclose(fptr); }

unlink() This function is used for deleting the file from the directory. Syntax-unlink(filename); Ex-

if((fptr=fopen(name,”r”)!=NULL) unlink(name);

RADOM ACCESS TO THE FILE There is no need to read each record sequentially,if we want to access a particular record. C supports these functions for random access file processing-

-fseek() -ftell() -rewind()

fseek() This function is used for setting the pointer position in the file at the specified byte Syntax-fseek(file pointer,displacement,pointer position); File pointer Here file pointer is the pointer which points to the file Displacement Displacement is positive or negative.This is the number of bytes which are skipped backward (if negative) or forward (if positive) from current position Ex- fseek(p,10L,0) 0 means pointer position is beginning of the file ,from this statement pointer position is skipped 5 bytes forward from the current position.

68

Page 69: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ftell() This function returns the value of the current pointer position in the file.The value is count from the beginning of the file. Ex- p=fopen(“text”,”r”); fseek(p,38L,0);

c=fget(p); while(!feof(p)) {printf(”%c”,c); printf(“%d”,ftell(p)); c=fgetc(p); }fclose(p);

rewind() This function is used to move the file pointer to the beginning of the given file.This can be written as Syntax-rewind(fptr); Ex- p=fopen(“text”,”r”); fseek(p,2L,0);

rewind(p); c=fgetc(p); while(!feof(p)) {printf(”%c”,c); c=fgetc(p); }fclose(p)

69

Page 70: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Usage of Enumerated data type Aim To write an algorithm to find the number of students in each colour

house(red,green,blue,yellow) and to print the details of each student . Input -Output specifications The input values are name(char) ,roll(int) . The output values are number of students in each colour house. Algorithm [This algorithm finds the number of students in each colour houses (red, green, blue, yellow) of a school by using enumerated data types. Here colour is the name of the enumerations and blue, red, green, yellow represents the individual members and roll is a enumeration variables of type colour. n contains the number of students. r, g, y, b stores the count of students in each houses.student is a structure which contains name, roll and house as its members and s is a variable of type student ] Step 1: Start. Step 2: Define a enumerated type color which contains blue,red,green,yellow as its members and roll is a variable of type color.[syntax for enumerations is: enum color{red,green,yellow,blue}roll;] Step 3: Define a structure student which contains name,roll,house as its members and s is an array of 100 elements of type color Step 4: [Reading the number of students] Read n. Step 5: Repeat steps 6 to 20 for i= 0 to n-1. Step 6: [Reading the rollnumber and name of each student] Read s[i].roll.

70

Page 71: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Step 7: Read s[i].name. Step 8 :[Finding the colour house of each student] roll=s[i].roll mod 4. Step 9 :[Finding the number of students in each house] if roll=red then goto step 10 else goto step 12. Step 10 :r=r+1. Step 11 :Copy ‘red’ to house. Step 12 :if roll=green then goto step 13 else goto step 15. Step 13 :g=g+1. Step 14 :Copy ‘green’ to house. Step 15:if roll=yellow then goto step 16 else goto Step 18. Step 16 :y=y+1. Step 17 :Copy ‘yellow’ to house. Step 18 :if roll=blue then goto step 19 . Step 19 :b=b+1. Step 20 :Copy ‘blue’ to house. Step 21:[Printing the number of students in each colour house] Print r,g,y,b. Step 22:[Printing the name,rollnumber and colour house of each student] Repeat step 23 for i= 0 to n-1. Step 23 :Print s[i].roll,s[i].name,s[i].house. Step 24:Stop.

71

Page 72: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

FACTORIAL Aim: To find the factorial of a given number Input: The number whose factorial is to be found Output: The factorial of the given number Flowchart No Yes No Yes

72

Display” Enter the number”

Fact 1

Read n

IS n ≥ 0

I 1 Display “No Factorial exists “

IS i ≤ n

Fact fact *

i i + 1

Display “Factorial “, fact

Stop

Start

Page 73: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

LARGEST NUMBER Aim : To find the largest of given n positive integers Input : Given n numbers Output: Largest among given numbers Flowchart Start No Yes Yes No

73

Display “Enter the number of numbers “

Read n

IS i < n

Display “ Enter the number “

Read num

IS Large < num

large num

i i +1

Large 0 ; i 0

Stop

Display large

Page 74: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SUM OF DIGITS OF A NUMBER

Aim: To find the sum of digits of a given number Input : Number whose sum of digits is to be find out Output: Sum of digits of given number Flowchart No Yes

Display “ Enter Number”

Read num

sum 0

sum = sum + num1

num1 = num % 10

num = num / 10

IS num ≠ 0

Stop

Display sum

Start

74

Page 75: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

GCD AND LCM

1.

Read n1,n2

If n1>n2

Num1=n1 Num2=n2

Rem=num1/num2

While Rem!=0

Num1=num2 Num2=rem Rem=num1/num2

Print gcd=num2

Lcm=(n1*n2)/num2

Print lcm

Start

Aim: To find the GCD and LCM of two numbers Input Specification: It takes two numbers as input Output Specification: It produce GCD and LCM as output

FLOWCHART

NO If n1>n2

YES Num1=n2 Num2=n1

NO

YES

Stop

75

Page 76: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

NUMBER PATTERN

Aim

To write an algorithm to print numbers from 1 to 100 in the order 1, 100, 2, 99, 3, 98, …… Input-output specification

The output values of the algorithm are i (int) and j (int). Algorithm : Printing number pattern

[This algorithm prints the numbers from 1 to 100 in the order 1, 100, 2, 99, 3, 98, ……. i is the variable to increment numbers from 1 to 50 and j is the variable to decrement numbers from 100 to 51.]

1.Start. 2. [printing the numbers]

Repeat step 3 for i=1 to 50 step1 & j=100 to 51 step -1 3. Print i,j. 4. Stop

76

Page 77: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

PATTERN

Aim

To write an algorithm that prints the following pattern. * * * * * * * * * * * * * * * Input-output Specification

The input value to the algorithm is n (int). Algorithm : Printing Pattern

[This algorithm prints the following pattern. * * * * * * * * * * * * * * * n is the variable to store the number of lines.]

1. Start. 2. [Reading the number of lines in the pattern]

Read n. 3. [Printing the pattern]

Repeat step 4 to 8 for i=0 to n-1. 4. Repeat step 5 for j = 1 to n-1. 5. Print “ “. 6. Repeat step 7 for k =0 to i 7. Print “* “. 8. Print “\n”. 9. Stop.

77

Page 78: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

GRADE OF THE STUDENT Aim To write an algorithm to display the grade of the student using if........else ladder. Input-output specification Input values are maximum marks and marks secured by the student. output is the grade of the student. Algorithm -Grade This algorithm displays the grade of the student .Input variables are maximum-marks and marks-secured.

1 Start. 2 Read maximum-marks. 3 Read marks-secured. 4 Percentage = (marks-secured / maximum-marks) * 100. 5 If percentage>80 go to step 6 else go to step7. [ Checking percentage ] 6 Display student passed with A grade, stop 7 If percentage>70 go to step 8 else go to step 9. 8 Display student passed with B grade and stop 9 If percentage >60 go to step 10 else go to step11. 10 Display student passed with C grade and stop 11 If percentage >40 go to step 12else go to step13. 12 Display student passed with D grade

and stop 13 If percentage< 40 go to step 14 else go to 15 14 Display student failed. 15 Stop

78

Page 79: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Simple Programs to Illustrate ‘while & do-while’ loops

I . Decimal to Binary Conversion :

Aim : Write an algorithm to convert a given decimal number to it’s binary equivalent ,using ‘ while ’ loop Inputs : All digits can be entered as a number as the input of this algorithm Output : The output of this algorithm is the binary equivalent of the entered decimal number Algorithm :

1. Start. 2. i 0, bin 0. 3. Display “ Enter The Decimal Number : ”. 4. Read num. 5. n num. 6. Repeat steps 7 to 10, while n != 0. 7. r n % 2. 8. n n / 2. 9. bin bin + ( 10 ^ i ) * r. 10. i = i +1. 11. Display “ Binary Equivalent of ” num “ is ” bin. 12. Stop.

79

Page 80: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

II. Program to print Fibonacci series upto given number using ‘Do-while ‘ loop :

Aim :

Write an algorithm to print fibonacci elements upto a given number , using ‘ do-while ’ loop

Inputs :

All digits can be entered as a number as the input of this algorithm

Output :

The output of this algorithm is in the form of fibonacci series upto the entered number

Algorithm:

1. Start. 2. value 0 , pre1 0 , pre2 1 . 3. Display “Enter The Upper Limit : “ . 4. Read lim . 5. Display “ The Fibonacci Series Upto ” lim “ is : ” . 6. Display value . 7. value pre1 + pre2 . 8. pre2 pre1 . 9. pre1 value . 10. Repeat steps 6 to 9 , while value <= lim . 11. Stop.

80

Page 81: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

III. Program to find factorial of a given number using ‘while or do-while’ using menu :

Aim :

Write an algorithm to find the factorial of a given number using ‘while’ or do-while ’ as the choice of the user

Inputs :

All digits can be entered as a non-negative number as the input of this algorithm

Output :

The output of this algorithm is the factorial of the entered number

Algorithm :

1. Start. 2. i 1 , fact 1. 3. Read choice . 4. Display “ Enter the number ” . 5. Read num . 6. n num . 7. if num < 0 , Display “ This number has no factorial

” , go to step 19 , else go to step 8 . 8. if choice = 1 , go to step 9 , else go to 12 . 9. Repeat steps 10 & 11 , while n != 0 . 10. fact fact * n . 11. n n – 1 . 12. if choice = 2 , go to step 13 , else go to step 17 . 13. fact fact * i . 14. i i + 1 . 15. Repeat steps 13 & 14 , while i <= n . 16. Go to step 18 . 17. Display “ Invalid choice ” and stop 18. Display “ Factorial of ” num “ is ” fact . 19. Stop .

81

Page 82: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

COUNT OF ODD AND EVEN NUMBERS Aim

To write an algorithm that finds the number of odd and even numbers in an array. Input-Output Specification

The input values to the algorithm are n (int), a[100] (int) and the output values are counte (int), counto (int). Algorithm : Count of odd and even numbers

[This algorithm counts the number of odd numbers and even numbers in an array. n is the variable to store the number of elements in the array and a is the array to store numbers. counto and counte are the variables to store count of odd and even numbers respectively.]

1. Start. 2. [Reading the elements of the limit of the array.]

Read n. 3. [reading the elements of the array.]

Repeat step 4 for i=0 to n-1. 4. Read a[i] 5. counte=0, counto=0. 6. [Counting even and odd numbers]

Repeat step 7, for i=0 to n-1. 7. If (a[i] % 2 = 0) then counte=counte+1 , else counto=counto+1 8.. [Printing the result]

Print counte , counto. 9. Stop.

82

Page 83: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

CHECK FOR VOWEL AIM (This algorithm is to check whether an input alphabet is a vowel using switch-case. chr is the variable that stores the value of the character.) INPUT-OUTPUT SPECIFICATIONS The input variable is a character type. This program will display the type of the alphabet int. ALGORITHM VOWEL Step 1 : Start Step 2 : [Reading the character] Read chr Step 3 : [Checking against a set of values] Switch (chr) Case a : display”The given alphabet is a vowel” goto step 4 Case e : display”The given alphabet is a vowel” goto step 4 Case i : display”The given alphabet is a vowel” goto step 4 Case o : display”The given alphabet is a vowel” goto step 4 Case u : display”The given alphabet is a vowel” goto step 4 Default : display” Consonants or other special character” Step 4 : Stop.

83

Page 84: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ARITHMETIC OPERATIONS USING SWITCH-CASE AIM (This algorithm is to do an arithmetic operation according to the choices given in the menu. c is the variable that stores the result of the arithmetic operation and cno is the variable that stores the number of the choice.) INPUT-OUTPUT SPECIFICATIONS Here the input variables a, b, cno are of integer type and the output variable c is of integer type. ALGORITHM ARITHMETIC Step 1 : Start Step 2 : [Reading two numbers] Read a, b Step 3 : [Reading choice number] Read cno Step 4 : [Checking against a set of values] Switch (cno) Case 1 : c=a+b display ”Total is “,c goto step 5 Case 2 : c=a-b display ”Difference is ”,c goto step 5 Case 3 : c=a*b display ”Product is ”,c goto step 5 Case 4 : if (b!=0) c=a/b display ”Quotient is ”,c else display ”Division by Zero ” goto step 5 Default : Display ”Error in switch” Step 5 : Stop

84

Page 85: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

STUDENT GRADE USING SWITCH-CASE AIM (This algorithm is to find the class of a student. tot is the variable that stores the total marks of a student, per is the variable that stores the percentage of marks, based on that determine the class of student.) INPUT OUTPUT SPECIFICATIONS Here the input variables are of integer type. ALGORITHM CLASS Step 1 : Start Step 2 : [Reading marks] Read m1,m2,m3,m4,m5,m6 Step 3 : [Calculate total marks] tot=m1+m2+m3+m4+m5+m6 Step 4 : [Calculate percentage] per=tot/6 Step 5 : [Checking percentage] If (per>=80) i=1 Step 6 : if (per>=60 and < 80) i=2 Step 7 : if (per>=50 and < 60) i=3 Step 8 : if (per>=40 and < 50) i=4 Step 9 : if (per<40) i=5 Step 10 : [Checking against a set of values] Switch(i) Case 1 : display “passed with distinction” goto step 11 Case 2 : display ”passed with first class” goto step 11 Case 3 :

display “passed with second class” goto step 11

85

Page 86: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Case 4 : display “passed with third class”

goto step 11 Case 5 :

display “failed” goto step 11 Default : display “Error in switch” Step 11 : Stop

86

Page 87: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SUM OF ARRAY VALUES

Aim

The aim of the algorithm is to find the sum of numbers stored in an

array.

Input-output specification

‘n’ integer values are entered into the array and the sum of all the

values entered is found out.

Algorithm sum

[This algorithm finds the sum of an array of numbers. ‘a’ is the array to

store the elements and ‘Res’ contains the sum.]

1. Start.

2. [Reading the limit of an array]

Read n.

3. [Reading the values of the array]

Repeat step 4 for i=1 to n.

4. Read a[i].

5. Res=0.

6. [Finding out the sum]

Repeat step 7 for i=1 to n.

7. Res = Res + a[i].

8. [Printing the answer]

Write Res

9. Stop.

87

Page 88: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

LARGEST NUMBER IN AN ARRAY Aim

The aim of the algorithm is to find the largest of all numbers stored

in the array.

Input-output specification.

‘n’ integer values are entered into an array and the largest of all the

values entered is found out.

Algorithm largest [This algorithm finds the largest number among an array of numbers. ‘a’ is

the array to store the elements and and ‘large’ contains the largest element.]

1. Start.

2. [Reading the limit of an array]

Read n.

3. [Reading the values of the array]

Repeat step 4 for i=1 to n.

4. Read a[i].

5. Initialize large = a[1].

6. [Finding out the largest element]

Repeat step 7 for i = 1 to n.

7. If a[i] > large , assign large = a[i].

8. [Printing the answer]

Write large.

9. Stop.

88

Page 89: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

LENGTH OF A STRING Aim

The aim of the algorithm is to find out the length of a given string.

Input-output specification

A string is entered as a character array and the length of the string is

found out by counting the total numbers of characters in the string.

Algorithm strlength [This algorithm finds the length of a string. ‘String’ is the character array

used to store the string and ‘count’ contains the number of characters in it]

1. Start.

2. [Reading the string]

Read string.

3. Initialize i=0, count=0.

4. [Counting the number of characters]

Repeat step 5 and step6 while string[i] not = ‘\0’.

5. count = count + 1.

6. i = i + 1.

7. [Printing the result]

Write count.

8. Stop .

89

Page 90: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

ARRAY REVERSAL

AIM

To reverse elements of an array without using a temporary array.

INPUT-OUTPUT SPECIFICATIONS.

The size of the array and it’s elements are entered as the input. The

reversed array is obtained as the output.

ALGORITHM: REVERSE.

[This algorithm reverses the elements of an array. A is the array used to

store the elements and the same array is used to output the reversed array. N

is the variable used to store the size of array.]

1. Start.

2. [Reading the size of the array.]

Read N.

3. [Reading the elements]

Repeat step 4 for i = 0 to N-1.

4. Read A[i].

5. [Reversing the elements of array].

Repeat step 6 for i = 0 to N/2.

6. i. A[i] = A[i] + A[N-1-i]

ii. A[N-1-i] = A[i] – A[N-1-i].

iii. A[i] = A[i] – A[N-1-i].

7. [Printing the reversed array]

Repeat step 8 for i = 0 to N-1

8. Print A[i].

9. Stop.

90

Page 91: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

COMPARING TWO NAMES

AIM :-

To compare two names and arrange them in alphabetical order.

INPUT OUTPUT SPECIFICATION :-

Two different names are entered into two different arrays

The names are compared and the greater one is stored in the first

array and the smaller one is stored in the second array.

ALGORITHM :-

Step 1 : Start.

Step 2 : Read the names.

[Names are read into str11 and str2]

Step 3 :Do steps 4, 5 & 6, If(( strcmp (str1,str2) > 0).

[Strcmp compares the first string (str1) with the second string

(str 2)].

Step 4 : strcpy (tmp[],str1).

[tmp is a temporary array].

[Strcpy copies the second string (str1) to the first string (tmp)

]

Step 5 : strcpy (str1,str2).

Step 6 : strcpy (str2,tmp).

Step 7 : Write str1 & str2.

Step 8 : Stop.

91

Page 92: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

APPENDING FIVE WORDS

AIM :-

To append five words and store in an array.

INPUT OUTPUT SPECIFICATIONS:-

Five words are entered from the keyboard.

Each of the words is concatenated to another string forming a single

string.

The length of the concatenated string is also found out.

ALGORITHM :-

Step 1 : Start.

Step 2 : Repeat steps 3, 4 & 5 ,for i=1 to i=5.

Step 3 : Read str2.

[str2 is the array which gets the string] .

Step 4 : strcat (str2,str1).

[str2 is the array to which the concatenated string is stored].

Step 5 : strcat(str2,” ”)

[A space is entered after each word].

Step 6 : Write str2.

[Appended string is printed out].

Step 7 : length=strlen(str2).

[strlen finds the length of the string str2 and stores in length].

Step 8 : Write length.

Step 9 : Stop.

92

Page 93: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

CONCATENATION OF TWO STRINGS Aim: Write an algorithm to concatenate two given strings without using any library functions. Inputs All printable ASCII characters are allowed to enter, in the form of two strings. Output The final result will be a concatenated string , of the first two source strings. Algorithm.

Step 1. Start Step 2. k 0 Step 3. Display “Enter how many words you want to enter “ Step 4. Read n Step 5. For i 0 to n-1 repeat steps 6 to 9 , 13,14 Step 6. Display “ Enter the word “ i+1 “ : “ Step 7. Read a Step 8. j 0 Step 9. Repeat steps 10 to 12 until a[j] != ‘\0’ Step 10. b[k] a[j] Step 11. j j+1 Step 12. k k+1 Step 13. b[k] ’ ’ Step 14. k k+1 Step 15. b[k] ‘\0’ Step 16. Display “ The concatenated string is ..." Step 17. Display b Step 18. Stop

93

Page 94: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

STRING COPY

Aim: Write an algorithm to copy a given string to another one without using any library functions. Inputs All printable ASCII characters are allowed to enter, in the form of a string. Output The output is also the same as the input , but displayed via another variable. Algorithm.

1. Start 2. i 0 3. Display “ Enter a word (string a) :” 4. Read a 5. Repeat steps 6 & 7 until a[i]=’\0’ 6. b[i] a[i] 7. i i + 1. 8. Display “ The copied string is (string b) : “ b 9. Display “ The first string is (string a) : “ a 10. Stop

94

Page 95: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

STRING COMPARISON Aim: Write an algorithm to compare two given strings without using any library functions. Inputs All printable ASCII characters are allowed to enter, in the form of two strings. Output The output is a formal statement, which have three possible meanings 1) The two strings are same , 2) The first string is larger than the second , 3) second string is greater than the first. Algorithm. ( main ( ) )

1. Start 2. Display “ Enter the first word “ 3. Read a 4. Display “ Enter the second word “ 5. Read b 6. Call k scp( a,b) 7. if k=0 , Display “ Both strings are same “ , go to 10, else go to 8 8. if k>=1, Display “ The first string is larger than the second “, go to

10, else go to 9 9. Display “ The second string is greater than the first “ 10. Stop

Algorithm. (scp (*x,*y) )

1. Start 2. Repeat step 3 for i 0 , until x[i]=y[i] , increment i by 1 3. if(x[i]=’\0’) then return 0, go to 5. 4. return x[i]-y[i] 5. Stop

95

Page 96: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

STRING LENGTH Aim: Write an algorithm to find the length of a given string without using any library functions. . Inputs All printable ASCII characters are allowed to enter, as a single string. Output The output will be in integer form, and the output will be the number of characters in the entered string.. Algorithm.

1. Start 2. Display “ Enter a string to find its length “ 3. Read a 4. i 0 5. Repeat step 6 till a[i] ≠ ‘\0’ 6. i i + 1 7. Display “ The length of the string is “ , i 8. Stop

96

Page 97: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

INSERTION INTO ARRAY Aim To write an algorithm to insert an element to the array. ALGORITHM:INSERTION. [This algorithm inserts a number in the specified position in an array. limit is the variable to store number of elements in an array and array is the variable to store the elements in the array. The variable num store the element which is to be insert and pos is the variable to store desired position.] Step 1: Start. Step 2: [Reading the number of elements in the array.] Read limit. Step 3: [Reading the elements of the array.] Repeat step 4 for i = 0 to i= limit-1 . Step 4: Read array[i]. Step 5: [Reading the element and position.] Read num, pos. Step 6: [Inserting the element in the array.] temp1=array [pos-1]. Step 7: array [pos-1] =num. Step 8: Repeat step 9 to 11 for i=pos to i=limit. Step 9: temp2=array [i]. Step 10: array [i]=temp1. Step 11: temp1=temp2. Step 12: [Printing the modified array.] Repeat step 13 for i=0 to i= limit. Step 13: Print array [i]. Step 14: Stop.

97

Page 98: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

DELETION FROM ARRAY AIM: To delete an element from an array from the position indicated by the user. INPUT-OUTPUT SPECIFICATIONS: The size of array, array elements and the position from which the element is to be deleted are entered as inputs. The modified array is obtained as the output. ALGORITHM:DELETION. [This algorithm will delete the element of an array from the position specified by the user. A is the array that stores elements, the same array is used for output. N is the variable that stores the size of array and P indicates the position from which the element is to be deleted] 1. Start. 2. [Reading the size of array and the position from which the element is to be deleted] Read N, P. 3. [Reading the elements]

Repeat step 4 for i = 0 to N-1. 4. Read A[i]. 5. [Deleting the element in the position P]

Repeat step 6 for i = P to N-1 6. A[i] = A[i+1]. 7. [Printing the new array.]

Repeat step 8 for i = 0 to N-2. 8. Print A[i]. 9. Stop.

98

Page 99: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

DEVIATION FROM AVERAGE AIM: To find the deviation of each number from average of the elements of the array INPUT-OUTPUT SPECIFICATIONS: The size of integer array and the array are entered as inputs and we get the output in another integer array. ALGORITHM: DEVIATIONS [This algorithm finds the deviation of each number from the average of array elements .A is the array used to store the integer elements, S is the variable to store sum of elements , N is the variable to store size of the array , Avg is the variable tom store the average of elements, D is the array to store deviations of each elements from average]

1. Start. 2. [Reading the size of the array]

Read N. 3. [Initializing the sum of elements to 0]

S=0. 4. [Reading the elements]

Repeat step 5 for i = 0 to N-1. 5. Read A[i]. 6. [Calculating the sum].

S=S+A[i]. 7. [Calculating the average]

Avg = S/N. 8. [Calculating deviations and storing to array D]

Repeat step 9 for i = 0 to N-1 9. D[i] = Avg – D[i]. 10. [Printing the deviations].

Repeat step 11 for i = 0 to N-1. 11. Print D[i]. 12. Stop.

99

Page 100: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

MATRIX TRANSPOSE

Aim:

Write an algorithm to find the transpose of a matrix. Inputs

Inputs are 1.) Size of matrix. 2.) Elements of the matrix.

Output Output may be displaying the original matrix and it’s transpose. Algorithm:

1. Start 2. Declare 2 matrix of size 100 X 100 with name mti, mto. 3. Input m, n.

[Inputting the size of matrix.] 4. For i 0 to m repeat step 5 to step 8 5. For j 0 to n repeat step 6 to step 7 6. Input mti(i, j)

[Inputting the elements of matrix] 7. Increment j by 1 8. Increment i by 1 9. For i 0 to m repeat step 10 to step 13 10. For j 0 to n repeat step 11 to step 12 11. Let mto(i, j) mti(j,i)

[Matrix transpose is creating] 12. Increment j by 1 13. Increment i by 1

[Output required] 14. For i 0 to m repeat step 15 to step 18 15. For j 0 to n repeat step 16 to step 17 16. Display mti(i, j)

[Original Matrix ] 17. Increment j by 1 18. Increment i by 1 19. For i 0 to m repeat step 20 to step 23 20. For j 0 to n repeat step 21 to step 22 21. Display mto(i, j)

[Matrix transpose required] 22. Increment j by 1 23. Increment i by 1 24. Stop

100

Page 101: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

MATRIX ADDITION AND SUBTRACTION Aim:

Write an algorithm to find sum and difference of a two matrices. Inputs

Inputs are 1.) Size of matrix. 2.) Elements of two matrices.

Output Output may be displaying the sum & difference of matrices. Algorithm:

Step 1. Start Step 2. Declare 4 matrix of size 100 X 100 each with name mta, mtb,

mts, mtd. Step 3. Input m, n.

[Inputting the size of matrix.] Step 4. For i 0 to m repeat step 5 to step 8 Step 5. For j 0 to n repeat step 6 to step 7 Step 6. Input mta(i, j)

[Inputting the elements of first matrix] Step 7. Increment j by 1 Step 8. Increment i by 1 Step 9. For i 0 to m repeat step 10 to step 13 Step 10. For j 0 to n repeat step 11 to step 12 Step 11. Input mtb(i, j)

[Inputting the elements of second matrix] Step 12. Increment j by 1 Step 13. Increment i by 1 Step 14. For i 0 to m repeat step 15 to step 19 Step 15. For j 0 to n repeat step 16 to step 18 Step 16. Let mts(i, j) mta(i, j) + mtb(i, j)

[Matrices sum is finding] Step 17. Let mtd(i, j) mta(i, j) - mtb(i, j) Step 18. Increment j by 1 Step 19. Increment i by 1

[Output required] Step 20. For i 0 to m repeat step 21 to step 24 Step 21. For j 0 to n repeat step 22 to step 23 Step 22. Display mts(i, j)

[Sum of matrices is displaying] Step 23. Increment j by 1 Step 24. Increment i by 1 Step 25. For i 0 to m repeat step 26 to step 29

101

Page 102: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Step 26. For j 0 to n repeat step 27 to step 28 Step 27. Display mtd(i, j)

[Difference of matrices is displaying] Step 28. Increment j by 1 Step 29. Increment i by 1 Step 30. stop

102

Page 103: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

MATRIX MULTIPLICATION Aim:

Write an algorithm to find product of a two matrices. Inputs

Inputs are 1.) Size of two matrices. 2.) Elements of two matrices.

Output Output may be displaying the product of matrices entered. Algorithm:

Step 1. Start Step 2. Declare 3 matrix of size 100 X 100 each with name mta, mtb,

mtp. Step 3. Input m1, n1.

[Inputting the size of first matrix.] Step 4. For i 0 to m1 repeat step 5 to step 8 Step 5. For j 0 to n1 repeat step 6 to step 7 Step 6. Input mta(i, j)

[Inputting the elements of first matrix] Step 7. Increment j by 1 Step 8. Increment i by 1 Step 9. Input m2, n2.

[Inputting the size of second matrix.] Step 10. For i 0 to m2 repeat step 11 to step 14 Step 11. For j 0 to n2 repeat step 12 to step 13 Step 12. Input mtb(i, j)

[Inputting the elements of second matrix] Step 13. Increment j by 1 Step 14. Increment i by 1 Step 15. If n1 not = m2 then

Display “Error condition” Goto step 29

Step 16. For i 0 to m1 repeat step 17 to step 23 Step 17. Let mtp(i,j) 0

[Initialize first element to 0] Step 18. For j 0 to n2 repeat step 19 to step 22 Step 19. For k 0 to n1 repeat step 20 to step 21 Step 20. Let mtp(i,j) mtp(i, j) + mta(i, k) * mtb(k, i)

[adding row and column elements] Step 21. Increment k by 1 Step 22. Increment j by 1 Step 23. Increment i by 1

103

Page 104: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

[Output required]

Step 24. For i 0 to m1 repeat step 21 to step 24 Step 25. For j 0 to n2 repeat step 22 to step 23 Step 26. Display mtp(i,j)

[Product of matrices is displaying] Step 27. Increment j by 1 Step 28. Increment i by 1 Step 29. stop

104

Page 105: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SQUARE OF A NUMBER [Using function with no arguments but return a

value] Aim The aim of the algorithm is to find the square of a number

using function. Input-output Specifications An integer number is input to ‘a’. Square of the

number is printed out using the variable ‘b’. This uses the function ‘square’.

Algorithm square [This is the algorithm of the function named ‘square’. ‘a’

represents the number whose square is to be determined and ‘b’ represents the square] 1. Start 2. [Reading the number]

Read a. 3. [Finding the square]

b = a * a. 4. [Returning the value]

Return(b). Algorithm main [This algorithm of main function calls the function ‘square’

and prints the result ] 1. Start 2. [Calling the function]

int m = square( ) 3. [Printing the result]

Print m 4. Stop.

105

Page 106: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SWAP TWO NUMBERS

[Using function having arguments with no return value]

Aim The aim of the algorithm is to interchange the value of two

numbers using function(without using third variable) Input-output Specifications Two numbers are input to ‘a’ & ‘b’. The interchanged

values are printed out using ‘x’ & ‘y’. This uses the function ‘swap’.

Algorithm swap [ ‘x’ & ‘y’ are two variables which receive values of ‘a’ & ‘b’

from the main function] 1. Start 2. [Steps 2,3&4 swap the value of ‘a’ & ‘b’] y = y – x 3. x = x + y 4. y = x – y 5. [Printing the values of ‘a’ & ’b’ after swapping] Print x , y.

Algorithm main. [This algorithm of main function reads two numbers and calls

the function ‘swap’] 1. Start. 2. [Reading two numbers]

Read a , b 3. [Function calling]

swap(a , b) 4. Stop.

106

Page 107: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SUM OF THE DIGITS OF A NUMBER [Using function having arguments with return value] Aim The aim of the algorithm is to find the sum of the digits of an

integer using function. Input-output Specifications An integer number is input to ‘num’. Sum of the digits

of the integer is printed out using the variable ‘sum’. This uses the function ‘digit’.

Algorithm digit. [This is the algorithm of the function named digit. Here ‘s’

represents the sum and ‘n’ represents the number] 1. Start. 2. [Initialising s to zero]

s = 0. 3. [Finding the sum]

while n > 0 repeat steps 4,5&6 4. temp = n % 10 5. s = s + temp 6. n = n / 10 7. [Returning the value]

Return(s). Algorithm main. [This algorithm of main function calls the function ‘sum’ &

prints the result ] 1. Start. 2. [Reading the number]

Read num. 3.[Function calling]

sum = digit(num) 4. [Printing the sum]

Print sum 5. Stop.

107

Page 108: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SWAP TWO NUMBERS USING FUNCTION AND POINTERS

Aim Algorithm to swap the values of two variables using function and pointers Input-Output Specification Values of two variables are accepting through the keyboard and output displayed to the screen after the swap function. Algorithm Function-swap() Step1:Accept the addresses of the variables to *a and *b Step2:Declare a temporary variable temp for swapping the values Step3:Assign temp=*a Step4:Assign *a=*b Step5:Assign *b=temp Step6:Return the control to main function main-Function Step1:Start Step2:Declare the variables x and y for accepting the values Step3:Accept the values to x and y Step4:Display “Values Before swap function” Step5:Display “x = ”,x ,”and “,”y = “,y Step6:swap(x,y) Step7:Display “Values after swap function” Step8:Display “x = ”,x ,”and “,”y = “,y Step9:Stop

108

Page 109: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

SUM OF ARRAYS USING FUNCTION AND POINTERS Aim Algorithm to find the sum of two arrays using the function and pointers Input-Output Specification Two arrays which are to be added given as input and the sum array as output Algorithm Function-arraysum [This function accepts the address of the two arrays and return the address of the sum array to the main function] Step1:Declare the pointers *a and *b for accepting the address of the input arrays and the sum array as c[100] Step2:Declare the integer variable size to accept the size of the arrays Step3:Initializes the loop control variable i to zero Step4:If i<size Then Goto Step5 Else Goto Step8 Step5:Compute c[i] = a[i] + b[i] Step6:Compute i = i + 1 Step7:Goto Step4 Step8:Return c Main Function Step1:Declare the arrays x[100] and y[100] for accepting the values Step2:Declare the pointer *z for accepting the value from function Step3:Accept the size of the arrays to variable n Step4:If n<=0 Then Goto Step5 Else Goto Step7 Step5:Display “Invalid Data” Step6:Goto Step23 Step7:Initialises the loop control variable i to zero Step8:Display “Enter the elements to array one” Step9:If i < n Then Goto Step10 Else Goto Step12 Step10:Read the value to a[i] Step11:Goto Step9 Step12:Initialises the loop control variable i to zero Step13:Display “Enter the elements to array two” Step14:If i < n Then Goto Step15 Else Goto Step17 Step15:Read the value to a[i] Step16:Goto Step14 Step17:Compute z = arraysum(x,y,n) Step18:Display “Array Sum Is” Step19: Initialises the loop control variable i to zero Step20:If i < n Then Goto Step21 Else Goto Step23 Step21:Display z[i] Step22:Goto Step20 Step23:Stop

109

Page 110: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

REVERSE OF A STRING Aim Algorithm to write a function to reverse a string and return using pointer Input-Output Specification String is accepted through keyboard and reverse is obtained from the function is displayed to the screen Algorithm Function-revstr() Step1:Accept the string from the main function to *str Step2:Declare the character array s1[100] to store reverse of the string and an integer Variable length for storing the length of the string Step3:Initialises the loop control variable i to zero Step4:If *(str + i) = ‘\0’ Then Goto Step7 Else Goto Step5 Step5:Compute i = i + 1 Step6:Goto Step4 Step7:Assign length = i - 1 Step8:Initialises the loop control variable i to zero and j to length Step9:If j >= 0 Then Goto Step10 Else Goto Step14 Step10:Assign *(s1 + i) = *(str + j) Step11:Compute i = i + 1 Step12:Compute j = j - 1 Step13:Goto Step9 Step14:*(s1+i)=’\0’ Step15:Return the reverse s1 to main function main Function Step1:Start Step2:Declare the character array st[100] for input string and *revst for output string Step3:Accept the string to character array st[100] Step4:revst = revstr(st) Step5:Display “the reverse of the string is”,revst Step6:Stop

110

Page 111: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

COUNTING THE NUMBER OF VOWELS,CONSONANTS AND OTHER PRINTABLE CHARACTERS IN A LINE OF

TEXT [ Using function with arrays & pointers]

Aim This algorithm counts the number of vowels, consonants & other printable characters in a line of text. Input-output Specifications A line of characters is read using the variable ‘line’. The function ‘stm’ is used to calculate the counts. The counts are printed using ‘*p’. Algorithm stm [This algorithm receives the characters in the ‘line’ to ‘*s’. The results are returned through ‘*k’.]

1. Start 2. Initialise *k to zero 3. Receive *s from main 4. Repeat step 5 for i=0 until s(i)!= ‘\0’ 5. If s(i)== ‘a’ || ‘e’ || ‘i’ || ‘o’ || ‘u’ *k++ 6. If s(i) > ‘a’ && s(i) < ‘Z’ *(k+1)+1 7. Else *(k+2)+1 8. Return(k) Algorithm main [This algorithm reads a line of text using the character array ‘line’. ‘*p’ is a pointer variable which calls the function ‘stm’ and the results are printed using ‘*p’] 1. Start 2. [Reading a line of text] Read line 3. [Function calling] 4. p = stm(line) 5. [Printing the number of vowels] 6. Print *p 7. [Printing the number of consonants] 8. Print *(p+1) 9. [Printing the number of other printable characters] 10. Print *(p+2) 11. Stop

111

Page 112: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

COPYING ONE FILE TO ANOTHER Aim To write an algorithm to copy one file to another Input-Output Specification Contents of an existing file is taken as input and a new file is created and copy the file content to this new file Algorithm Step1:Start Step2:Declare the file pointers fp and ff for opening the files Step3:Declare the character variable c for accepting characters from the file Step4:Open the existing file in read mode with file pointer fp Step5:Open the new file in write mode with file pointer ff Step6:If fp = NULL Then Goto Step7 Else Goto Step9 Step7:Display “File Opening Error” Step8:Goto Step14 Step9:Get a character from file to c Step10:If c != EOF Step11:Write the character to the new file Step12:Display “File Is Successfully Copied” Step13:Close the files Step14:Stop

112

Page 113: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

PREPARE RANKLIST USING STRUCTURES Aim

To write an algorithm to prepare the rank list of given students.

Input-Output Specification

The input values to the algorithm are name (String), roll number

(int), marks of three subjects (int) of n students and the output is the rank list

of the students.

Algorithm Ranklist

[ This algorithm is to prepare rank list of n student’s. Here Student is

declared as a structure type with the following elements.

Name-denotes name of student

Roll-denote roll number of a student

m1-denote mark of English

m2-denote mark of Mathematic

m3-denote mark of Computer Science.

st is an array of 100 elements of the type student. temp is another

student

type variable.]

Step 1: Start

Step 2: [ Reading number of students whose rank list to be prepared]

Read n.

Step 3: [Reading details of n students in to array of structures]

Repeat Step 4 for i=0 to n-1.

Step 4: [Reading values to array elements]

(i) Read st[i].name

(ii) Read st[i].roll

(iii) Read st[i].m1

(iv) Read st[i].m2

(v) Read st[i].m3

Step 5: [Find total mark of each student]

Repeat Step 6 for i=0 to n-1

113

Page 114: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

Step 6: st[i].total=st[i].m1+st[i].m2+st[i].m3

Step 7: [Sorting the student record based on mark]

Repeat Step 8 for i=0 to n-1

Step 8: Repeat Step 9 for j = i to n-1

Step 9: if(st[j].total<st[j+1].total)

(i) temp = st[j]

(ii) st[j] = st[j+1]

(iii) st[j+1] = temp

Step 10: For i = 0 to n-1,

st[i].rank=i+1

Step 11: [Print Student's Details]

Repeat Step 12 for i = 0 to n-1

Step 12: (i) Display "Name : " , st[i].name

(ii) Display "Roll No : ", st[i].roll

(iii) Display "English : ", st[i].m1

(iv) Display "Mathematics : ", st[i].m2

(v) Display "Computer Science : ", st[i].m3

(vi) Display "Total : ", st[i].total

(vii) Display "Rank : ", st[i].rank

Step 13: Stop

114

Page 115: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

BINARY FILE Aim To write an algorithm to open a file in binary mode and perform reading and writing. Input-Output Specification A file is opened in binary mode. A structure is defined to accept the name, age and salary of the employees and to write to the file in binary mode. Algorithm Step1:Start Step2:Declare the file pointer fp for opening of file in binary mode Step3:Define the structure with elements character array name,two integer variables age and bs Step4:Declare the structure variable e to accept data Step5:Open the file in binary write mode Step6:Display “Enter the details of the employees” Step7:Accept the name of the employee to e.name Step8:Accept the age of the employee to e.age Step9:Accept the salary of the employee to e.bs Step10:Write these details to the file Step11:Display “Do you want to enter another one?” Step12:Accept to character variable c Step13:If c!=’n’ Then Goto Step6 Else Goto Step14 Step14:Close the file Step15:Open the file in binary read mode Step16:Display “File Details” Step17:Read the file details to the structure variable e Step18:Display “Name-:”,e.name Step19:Display “Age-:”,e.age Step20:Display “Salary-:”,e.salary Step21:If the file pointer reaches at EOF Then Goto Step22 Else Goto Step17 Step22:Close the file Step23:Stop

115

Page 116: ABOUT C PROGRAMMING LANGUAGE - · PDF fileABOUT C PROGRAMMING LANGUAGE History C was developed at Bell Laboratories in 1972 by Dennis Ritchie. Many of its principles and ideas were

APPENDING DATA TO THE EXISTING FILE

Aim To write an algorithm to append the data with the existing file Input-Output Specification An existing file is opened in append mode and the contents to append are read through the keyboard into string variable up to typing the word EOF Algorithm Step1:Start Step2:Declare the file pointer fp for opening the file Step3:Declare the variables for input and output Step4:Open the file in append mode Step5:If fp = NULL Then Goto step6 Else Goto step8 Step6:Display “Error in opening the file” Step7:Goto Step 15 Step8:Display “Enter the data to append with the file and type EOF to finish” Step9:Read the data into string Str Step10:If Str != “EOF” Then Step11 Else Step13 Step11:Write the data in the Str to the file using file pointer fp Step12:Goto Step9 Step13:Display “File Is Appended Successfully” Step!4:Close the file Step15:Stop

116