semester i_paper i_prog in c

Upload: kirtini

Post on 07-Apr-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Semester I_Paper I_Prog in C

    1/106

    Programming with C

    1. Introduction to Problem SolvingFlow charts, Tracing flow charts, Problem solving methods, Need forcomputer Languages, Sample Programs written in C

    2. C Language preliminaries:C character set, Identifiers and keywords, Data types, Declarations,Expressions, statements and symbolic constants

    3. Input-Output:getchar, putchar, scanf, printf, gets, puts, functions.

    4. Pre-processor commands:#include, #define, #ifdef

    5. Preparing and running a complete C program

    6. Operators and expressions:Arithmetic, unary, logical, bit-wise, assignment and conditional operators

    7. Control statements:While, do-while, for statements, nested loops, if else, switch, break, Continue,and goto statements, comma operators

    8. Storage types:

    Automatic, external, register and static variables.

    9. FunctionsDefining and accessing, passing arguments, Function prototypes, Recursion,Library functions, Static functions

    10. Arrays:Defining and processing, Passing arrays to a function, Multi dimensionalarrays.

    11. Strings

    Defining and operations on strings.

    12. PointersDeclarations, Passing pointers to a function, Operations on pointers, PointerArithmetic, Pointers and arrays, Arrays of pointers function pointers.

    13. StructuresDefining and processing, Passing to a function, Unions, typedef, array ofstructure, and pointer to structure

    14. File structures:

    1

  • 8/3/2019 Semester I_Paper I_Prog in C

    2/106

    Definitions, concept of record, file operations: Storing, creating, retrieving,updating Sequential, relative, indexed and random access mode, Files withbinary mode(Low level), performance of Sequential Files, Direct mappingtechniques: Absolute, relative and indexed sequential files (ISAM) concept ofindex, levels of index, overflow of handling.

    15. File Handling:File operation: creation, copy, delete, update, text file, binary file.Syllabus for MCA First Year Semester I (with effect from the academic year2007-2008)

    Term work/ Practical: Each candidate will submit a journal in which at least12 practical assignments based on the above syllabus along with the flowchart and program listing will be submitted with the internal test paper. Testgraded for 10 marks and Practical graded for 15 marks.

    List of Practical

    Two programs based on functions.Two programs based on pointers.Four programs based on Remaining portion eg. Control statements,Structures and Unions etc.

    Three programs based on Different File Operations (File Handling)

    References :

    1. Mastering C by Venugopal, Prasad TMH2. Complete reference with C Tata McGraw Hill3. C programming E.Balagurusamy Tata McGray Hill4. How to solve it by Computer : Dromey, PHI5. Schaums outline of Theory and Problems of programming with C :Gottfried6.The C programming language : Kerninghan and Ritchie7. Programming in ANSI C : Ramkumar Agarwal8. Mastering C by Venugopal, Prasad TMH9. Let Us C by kanetkar10. An introduction to data structures with applications, Jean-Paul Trembly

    and Paul Sorenson, (2nd

    edition), 1884

    2

  • 8/3/2019 Semester I_Paper I_Prog in C

    3/106

    Chapter 1 Introduction to Problem Solving

    Contents

    Flow charts

    Tracing flow charts

    Problem solving methods

    Need for computer Languages

    Sample Programs written in C

    Flow Chart

    A Flow Chart is a diagrammatic representation that gives a step-by-step solution to a given problem.

    A Flowchart is a common type ofdiagram that :

    a. represents an algorithm or process,

    b. showing the steps as boxes of various kinds, and

    c. Shows their order by connecting these with arrows.

    Data is represented in these boxes, and arrows connecting themrepresent flow / direction of flow ofdata.

    A flow chart can therefore be used to:

    1. Define and analyze processes;

    2. Build a step-by-step picture of the process for analysis, discussion,

    or communication; and

    3. Define, standardize or find areas for improvement in a process

    3

    http://en.wikipedia.org/wiki/Knowledge_representation_and_reasoninghttp://en.wikipedia.org/wiki/Problem_solvinghttp://en.wikipedia.org/wiki/Diagramhttp://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Processhttp://en.wikipedia.org/wiki/Datahttp://en.wikipedia.org/wiki/Datahttp://en.wikipedia.org/wiki/Knowledge_representation_and_reasoninghttp://en.wikipedia.org/wiki/Problem_solvinghttp://en.wikipedia.org/wiki/Diagramhttp://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Processhttp://en.wikipedia.org/wiki/Datahttp://en.wikipedia.org/wiki/Data
  • 8/3/2019 Semester I_Paper I_Prog in C

    4/106

    Fig : A simple flowchart representing a process for dealing with anon-functioning TV Remote

    Flowchart Symbols

    Different flow chart symbols have different meanings. The most commonflow chart symbols are:

    1. Terminator: An oval flow chart shape indicating the start or end ofthe process.

    2. Process: A rectangular flow chart shape indicating a normalprocess flow step.

    3. Decision: A diamond flow chart shape indication a branch in theprocess flow.

    4. Connector: A small, labeled, circular flow chart shape used toindicate a jump in the process flow.

    5. Data: A parallelogram that indicates data input or output (I/O) for a

    process.

    4

  • 8/3/2019 Semester I_Paper I_Prog in C

    5/106

    6. Document: used to indicate a document or report (see image insample flow chart below).

    A really simplistic flow chart showing the flow chart symbols describedabove can be seen below:

    NO

    YES

    Need for Programming Languages

    5

    STARTTERMINATOR

    PROCESS

    DECISION

    DATA

    DOCUMENT

    ENDTERMINATOR

  • 8/3/2019 Semester I_Paper I_Prog in C

    6/106

    A programming language is an artificial language designed toexpress computations that can be performed by a machine,particularly a computer.

    Programming languages can be used to create programs that

    control the behavior of a machine, to express algorithms precisely,or as a mode of human communication.

    Many programming languages have some form of writtenspecification of their syntax (form) and semantics (meaning).

    Some languages are defined by a specification document. Forexample, the C programming language is specified by an ISOStandard.

    Other languages, such as Perl, have a dominant implementationthat is used as a reference.

    The earliest programming languages predate the invention of the

    computer, and were used to direct the behavior of machines such asJacquard looms and player pianos.

    Thousands of different programming languages have been created,mainly in the computer field, with many more being created everyyear.

    Most programming languages describe computation in animperative style, i.e., as a sequence of commands, although somelanguages, such as those that support functional programming orlogic programming, use alternative forms of description.

    Sample C Programs

    /*Hello world program*/

    #include#includevoid main(){

    printf(hello world);}

    /* addition of 2 numbers */

    #include#includevoid main(){

    int a, b,c;c=0;

    a=3;b=4;c = a + b:printf(result of addition =

    %d,c);}

    6

    http://en.wikipedia.org/wiki/Languagehttp://en.wikipedia.org/wiki/Computationhttp://en.wikipedia.org/wiki/Machinehttp://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Program_(machine)http://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Syntaxhttp://en.wikipedia.org/wiki/Semanticshttp://en.wikipedia.org/wiki/C_(programming_language)http://en.wikipedia.org/wiki/International_Organization_for_Standardizationhttp://en.wikipedia.org/wiki/Perlhttp://en.wikipedia.org/wiki/Programming_language_implementationhttp://en.wikipedia.org/wiki/History_of_computing_hardwarehttp://en.wikipedia.org/wiki/History_of_computing_hardwarehttp://en.wikipedia.org/wiki/Jacquard_loomhttp://en.wikipedia.org/wiki/Player_pianohttp://en.wikipedia.org/wiki/Imperative_programminghttp://en.wikipedia.org/wiki/Functional_programminghttp://en.wikipedia.org/wiki/Logic_programminghttp://en.wikipedia.org/wiki/Languagehttp://en.wikipedia.org/wiki/Computationhttp://en.wikipedia.org/wiki/Machinehttp://en.wikipedia.org/wiki/Computerhttp://en.wikipedia.org/wiki/Program_(machine)http://en.wikipedia.org/wiki/Algorithmhttp://en.wikipedia.org/wiki/Syntaxhttp://en.wikipedia.org/wiki/Semanticshttp://en.wikipedia.org/wiki/C_(programming_language)http://en.wikipedia.org/wiki/International_Organization_for_Standardizationhttp://en.wikipedia.org/wiki/Perlhttp://en.wikipedia.org/wiki/Programming_language_implementationhttp://en.wikipedia.org/wiki/History_of_computing_hardwarehttp://en.wikipedia.org/wiki/History_of_computing_hardwarehttp://en.wikipedia.org/wiki/Jacquard_loomhttp://en.wikipedia.org/wiki/Player_pianohttp://en.wikipedia.org/wiki/Imperative_programminghttp://en.wikipedia.org/wiki/Functional_programminghttp://en.wikipedia.org/wiki/Logic_programming
  • 8/3/2019 Semester I_Paper I_Prog in C

    7/106

    CHAPTER 2 C LANGUAGE PRELIMINARIES

    CONTENTS

    C character set

    Identifiers and keywords Data types Declarations Expressions Statements Symbolic constants

    C CHARACTER SET

    A character denotes any alphabet, digit or symbols to represent information.

    The character set in C Language can be grouped into the following categories.

    1. Letters2. Digits3. Special Characters4. White Spaces

    White Spaces are ignored by the compiler until they are a part of string constant.

    White Space may be used to separate words, but are strictly prohibited whileusing between characters of keywords or identifiers.

    Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9Alphabets: a, b, .z A, B, ...ZArithmetic Operations: +, -, *, /, %(Mod)Special Characters:

    ( ) { } [ ] < >

    = ! $ ? . , : ;

    & | ^ ~ ` #

    \ blank - _ / * % @

    CONSTANTS & VARIABLES

    7

  • 8/3/2019 Semester I_Paper I_Prog in C

    8/106

    ConstantsA constant value is the one which does not change during the execution of a

    program. C supports several types ofconstants.

    1. Integer Constants2. Real Constants3. Single Character Constants4. String Constants

    Integer Constants

    An integer constant is a sequence of digits. There are 3 types of integers namelydecimal integer, octal integers and hexadecimal integer.

    Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or- sign. Spaces, commas and non digit characters are not permitted betweendigits. Example for valid decimal integer constants are

    123, -3, 0, 562321, + 78Some examples for invalid integer constants are15 750, 20,000, Rs. 1000

    Octal Integers constant consists of any combination of digits from 0 through 7with a O at the beginning. Some examples of octal integers are

    O26, O, O347, O676

    Hexadecimal integerconstant is preceded by OX or Ox, they may containalphabets from A to F or a to f. The alphabets A to F refers to 10 to 15 indecimaldigits. Example of valid hexadecimal integers are

    OX2, OX8C, OXbcd, Ox

    1. Real Constants

    Real Constants consists of a fractional part in their representation. Integerconstants are inadequate to represent quantities that vary continuously. Thesequantities are represented by numbers containing fractional parts like 26.082.Example of realconstants are

    0.0026, -0.97, 435.29, +487.0

    Real Numbers can also be represented by exponential notation. The generalform for exponential notation is mantissa exponent. The mantissa is either a realnumber expressed in decimal notation or an integer. The exponent is an integernumber with an optional plus or minus sign.

    Single Character Constants

    A Single Character constant represent a single character which is enclosed in a

    pair of quotation symbols.Example for character constants are

    8

  • 8/3/2019 Semester I_Paper I_Prog in C

    9/106

    '5', 'x', ';', ' 'All character constants have an equivalent integer value which is called ASCIIValues.

    String Constants

    A string constant is a set of characters enclosed in double quotation marks. Thecharacters in a string constant sequence may be an alphabet, number, specialcharacter and blank space. Example of string constants are

    "VISHAL", "1234", "God Bless", "!.....?"

    Variables

    A variable is a value that can change any time. It is a memory location used tostore a data value. A variable name should be carefully chosen by theprogrammer so that its use is reflected in a useful way in the entire program.Variable names are case sensitive.Example of variable names are

    Sun, number, Salary, Emp_name, average1

    IDENTIFIERS AND KEYWORDS

    Every word in C language is a keyword or an identifier/variable. Keywords in Clanguage cannot be used as a variable name. They are specifically used

    by the compiler for its own purpose and they serve as building blocks ofa c program.

    Identifiers:

    Identifiers are the names given to variables, classes, methods andinterfaces.

    It must be a whole word and starts with either an alphabet or anunderscore.

    They are case sensitive.

    No commas or blanks are allowed in it No special symbol other than an underscore can be used in it.

    Ex.: marksgracesem1_rollnoalpha

    Keywords:

    Keywords are words that have special meaning to the C compiler.

    9

  • 8/3/2019 Semester I_Paper I_Prog in C

    10/106

    An identifier cannot have the same spelling and case as a C keyword. C makes use of only 32 keywords or reserved words which combine with

    the formal syntax to the form the C programming language. All keywords in C are written in lower case. A keyword may not be used as a variable name.

    Ex.:auto double int structbreak else long switch

    case enum register typedef

    char extern return union

    const float short unsigned

    continue for signed void

    default goto sizeof volatile

    do if static while

    Data types & Declarations

    In c, there are three types of data In C language the system has to know before-hand, the type of numbersor characters being used in the program. These are data types. There are many data types in C language. A C programmer has to use appropriate data type as per his requirement. C language data types can be broadly classified as

    a. Primary data typeb. Derived data typec. User-defined data type

    Fig: Data Types in C

    Integer Data Type

    Integers are numbers without decimal point Integers are whole numbers with a range of values, range of values are machine

    dependent.

    10

    DATA

    PRIMARY DATA SECONDARY DATA USER DEFINED

    CHAR

    INTFLOATDOUBLE

    ARRAY

    FUNCTIONPOINTERSTRUCTURE

    TYPEDEF

    ENUM

  • 8/3/2019 Semester I_Paper I_Prog in C

    11/106

    Generally an integer occupies 2 bytes memory space and its value rangelimited to -32768 to +32767 (that is, -215 to +215-1).

    A signed integer use one bit for storing sign and rest 15 bits for number. To control the range of numbers and storage space, C has three classes of

    integer storage namely short int, int and long int.

    All three data types have signed and unsigned forms. A short int requires half the amount of storage than normal integer. Unlike signed integer, unsigned integers are always positive and use all the

    bits for the magnitude of the number. Therefore, the range of an unsigned integer will be from 0 to 65535. The long integers are used to declare a longer range of values and it occupies

    4 bytes of storage space.

    Syntax: int ;

    int num1;short int num2;long int num3;

    Example: 5, 6, 100, 2500.

    Integer Data Type Memory Allocation:

    11

  • 8/3/2019 Semester I_Paper I_Prog in C

    12/106

    Floating Point Data Type

    The float data type is used to store fractional numbers (real numbers) with6 digits of precision.

    Floating point numbers are denoted by the keyword float. When theaccuracy of the floating point number is insufficient, we can use the double todefine the number. The double is same as float but with longer precision and takes doublespace (8 bytes) than float. To extend the precision further we can use long double which occupies 10bytes of memory space.

    Syntax: float ;

    float num1;double num2;long double num3;

    Example: 9.125, 3.1254.

    Floating Point Data Type Memory Allocation:

    Character Data Type

    Character type variable can hold a single character and are declared byusing the keyword char. As there are singed and unsigned int (either short or long), in the sameway there are signed and unsigned chars; both occupy 1 byte each, buthaving different ranges. Unsigned characters have values between 0 and 255, signed charactershave values from 128 to 127.

    Syntax: char ;

    char ch = a;

    Example: a, b, g, S, j.

    12

  • 8/3/2019 Semester I_Paper I_Prog in C

    13/106

    Arithmetic Expressions

    An expression is a combination of variables constants and operators writtenaccording to the syntax of C language.

    In C every expression evaluates to a value i.e., every expression results insome 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 Expression

    a x b c a * b c(m + n) (x + y) (ab / c)

    (m + n) * (x + y) a * b / 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 cy = b / c * az = a b / c + d;

    13

  • 8/3/2019 Semester I_Paper I_Prog in C

    14/106

    Statements

    Each instruction in a C program is written as a separate statement. Therefore acomplete C program would comprise of a series of statements.

    The statements in a program must appear in the same order in which we wish

    them to be executed; unless of course the logic of the problem demands adeliberate jump or transfer of control to a statement, which is out ofsequence.

    Blank spaces may be inserted between two words to improve the readability ofthe statement.

    However, no blank spaces are allowed within a variable, constant or keyword. All statements are entered in small case letters. C has no specific rules for the position at which a statement is to be written.Thats why it is often called a free-form language.

    Every C statement must end with a (semicolon) ; Thus ; acts as a statementterminator.

    Example

    # include # include void main(){

    printf(hello world);}

    printf(hello world); is an statement that ends with a semicolon.

    Symbolic constants

    C allows the definition of symbolic constants - names that will be replacedwith their values when the program is compiled

    Symbolic constants are defined before main(), and the syntax is#define NAMEvalue

    Example :

    #define ANGLE_MIN 0

    #define ANGLE_MAX 360would define ANGLE_MIN and ANGLE_MAX to the values 0 and 360, respectively.

    C distinguishes between lowercase and uppercase letters in variable names. It is customary to use capital letters in defining global constants.

    14

  • 8/3/2019 Semester I_Paper I_Prog in C

    15/106

    CHAPTER 3 INPUT-OUTPUT

    CONTENTS

    getchar() putchar() scanf() printf() gets() puts()

    One of the essential operations performed in a C language programs is toprovide input values to the program and output the data produced by theprogram to a standard output device.

    We can assign values to variable through assignment statements such as

    x = 5 a = 0 ; and so on. Another method is to use the Input then scanfwhich can be used to readdata from a key board.

    For outputting results we have used extensively the function printfwhichsends results out to a terminal.

    There exists several functions in C language that can carry out inputoutput operations. These functions are collectively known as standardInput /Output Library.

    Each program that uses standard input / output function must contain thestatement.

    # include < stdio.h >at the beginning.

    Single character input output

    The basic operation done in input output is to read characters from thestandard input device such as the keyboard and to give output or writing itto the output unit usually the screen.

    The getchar function can be used to read a character from the standardinput device.

    The scanf can also be used to achieve the function.

    The getchar has the following form.Variable name = getchar();

    Variable name is a valid C variable, that has been declared already and thatpossess the type char.

    Example program :

    # include < stdio.h > // assigns stdio-h header file to werprogram

    void main ( ) // Indicates the starting point of theprogram.

    15

  • 8/3/2019 Semester I_Paper I_Prog in C

    16/106

    {char C, // variable declarationprintf (Type one character:) ; // message to userC = getchar () ; // get a character from key board and

    stores it in variable C.

    printf ( The character we typed is = %c, C) ; // output} // Statement which displays value of C on// Standard screen.

    The putchar function which is analogous to getchar function can be used forwriting characters one at a time to the output terminal. The general form is

    putchar (variable name);where variable is a valid C type variable that has already been declared Ex:-

    putchar ( );displays the value stored in variable C to the standard screen.

    Program shows the use of getchar function in an interactive environment.

    Example:

    #include < stdio.h > // Inserts stdio.h header file into the Pgmvoid main ( ) // Beginning of main function.{char in; // character declaration of variable in.printf ( please enter one character); // message to userin = getchar ( ) ; // assign the keyboard input value to in.putchar (in); // output in value to standard screen.}

    String input and output

    The gets function receives the string from standard input device whileputs outputs the string to the standard output device. A string is an arrayor set of characters.

    The function gets accepts the name of the string as a parameter, and fillsthe string with characters that are input from the keyboard till newlinecharacter is encountered. (That is till we press the enter key). At the endfunction gets appends a null terminator as must be done to any string andreturns.

    The puts function displays the contents stored in its parameter on thestandard screen.

    The standard form of the gets function isgets (str) Here "str" is a string variable.

    The standard form for the puts character isputs (str) Where str is a string variable.

    Example:# include < stdio.h >void main ( ){char s [80];printf (Type a string less than 80 characters:);

    16

  • 8/3/2019 Semester I_Paper I_Prog in C

    17/106

    gets (s);printf (The string types is:);puts(s);}

    Formatted Input For scanf:

    The formatted input refers to input data that has been arranged in aparticular format. Input values are generally taken by using the scanffunction.

    The scanf function has the general form.scanf (control string, arg1, arg2, arg3 .argn);

    The format field is specified by the control string and the argumentsarg1, arg2, .argn specifies the address of location where address isto be stored. The control string specifies the field format which includes format

    specifications and optional number specifying field width and theconversioncharacter % and also blanks, tabs and newlines. The Blanks tabs and newlines are ignored by compiler. The conversioncharacter % is followed by the type of data that is to be assigned to variableof the assignment. The field width specifier is optional.

    The general format for reading a integer number is% x d

    Here percent sign (%) denotes that a specifier for conversion follows and xis an integer number which specifies the width of the field of the number thatis being read. The data type character d indicates that the number should beread in integer mode.

    Example :scanf (%3d %4d, &sum1, &sum2);

    If the values input are 175 and 1342 here value 175 is assigned to sum1 and1342 to sum 2.Suppose the input data was follows 1342 and 175.

    The number 134 will be assigned to sum1 and sum2 has the value 2 because of%3d the number 1342 will be cut to 134 and the remaining part is assigned tosecond variable sum2. If floating point numbers are assigned then the decimal orfractional part is skipped by the computer.

    To read the long integer data type we can use conversion specifier % ld & % hd

    for short integer.

    Input specifications for real number

    Field specifications are not to be used while representing a real numbertherefore real numbers are specified in a straight forward manner using %f specifier.

    The general format of specifying a real number input is

    17

  • 8/3/2019 Semester I_Paper I_Prog in C

    18/106

    scanf (% f , &variable);

    Example:scanf (%f %f % f, &a, &b, &c);

    With the input data321.76, 4.321, 678 The values321.76 is assigned to a , 4.321 to b & 678 to C.

    If the number input is a double data type then the format specifier should be % lfinstead of %f.

    Input specifications for a character.

    Single character or strings can be input by using the character specifiers.The general format is

    % xc or %xs

    Where C and S represents character and string respectively and x represents thefield width.

    The address operator need not be specified while we input strings.Example :

    scanf (%C %15C, &ch, nname):Here suppose the input given is a, Robert then a is assigned to ch and name willbe assigned to Robert.

    Printing One Line:

    printf();

    The most simple output statement can be produced in C Language byusing printfstatement.

    It allows we to display information required to the user and also prints thevariables we can also format the output and provide text labels.

    The simple statement such asprintf (Enter 2 numbers);

    prompts the message enclosed in the quotation to be displayed.

    A simple program to illustrate the use of printf statement:-

    #include < stdio.h >main ( ){printf (Hello!);printf (Welcome to the Institute of Distance & Open Learning!);}

    Output: Hello! Welcome to IDOL.

    18

  • 8/3/2019 Semester I_Paper I_Prog in C

    19/106

    Both the messages appear in the output as if a single statement. If we wish toprint the second message to the beginning of next line, a new line charactermust be placed inside the quotation marks.Example :

    printf (Hello!\n);

    OR printf (\n Welcome to the Institute of Distance & OpenLearning);

    Conversion Strings and Specifiers:

    The printf ( ) function is quite flexible. It allows a variable number of arguments,labels and sophisticated formatting of output.

    The general form of the printf ( ) function isprintf (conversion string, variable list);

    The conversion string includes all the text labels, escape character andconversion specifiers required for the desired output. The variable includes allthe variable to be printed in order they are to be printed. There must be aconversion specifies after each variable.Specifier Meaning%c Print a character%d Print a Integer%i Print a Integer%e Print float value in exponential form.%f Print float value%g Print using %e or %f whichever is smaller

    %o Print actual value%s Print a string%x Print a hexadecimal integer (Unsigned) using lower case a F%X Print a hexadecimal integer (Unsigned) using upper case A F%a Print a unsigned integer.%p Print a pointer value%hx hex short%lo octal long%ld long

    19

  • 8/3/2019 Semester I_Paper I_Prog in C

    20/106

    CHAPTER 4 PRE-PROCESSOR COMMANDS

    CONTENTS

    #include

    #define

    #ifdef

    Introduction

    The C preprocessor is exactly what its name implies. It is a programthat processes our source program before it is passed to the compiler.

    Preprocessor commands (often known as directives) form what canalmost be considered a language within C language.

    We can certainly write C programs without knowing anything about the

    preprocessor or its facilities. But preprocessor is such a greatconvenience that virtually all C programmers rely on it. The preprocessor offers several features called preprocessor directives.

    Each of these preprocessor directives begin with a # symbol. The directives can be placed anywhere in a program but are most often

    placed at the beginning of a program, before the first functiondefinition.

    We would learn the following preprocessor directives here:(a) Macro expansion(b) File inclusion(c) Conditional Compilation

    Macro Expansion

    Example:#define UPPER 25main( ){int i ;for ( i = 1 ; i

  • 8/3/2019 Semester I_Paper I_Prog in C

    21/106

    File Inclusion

    The second preprocessor directive well explore in this chapter is fileinclusion. This directive causes one file to be included in another. Thepreprocessor command for file inclusion looks like this:

    #include "filename"and it simply causes the entire contents offilename to be inserted intothe source code at that point in the programIt can be used in two cases:

    (a) If we have a very large program, the code is best divided into severaldifferent files, each containing a set of related functions. It is a goodprogramming practice to keep different sections of a large programseparate. These files are #included at the beginning of main programfile.

    (b) There are some functions and some macro definitions that we needalmost in all programs that we write. These commonly neededfunctions and macro definitions can be stored in a file, and that file canbe included in every program we write, which would add all thestatements in this file to our program as if we have typed them in.

    It is common for the files that are to be included to have a .h extension. This extension stands for header file, possibly because it containsstatements which when included go to the head of our program. Theprototypes of all the library functions are grouped into different categories

    and then stored in different header files. For example prototypes of allmathematics related functions are stored in the header file math.h,prototypes of console input/output functions are stored in the header fileconio.h, and so on.Actually there exist two ways to write #include statement.These are:

    #include "filename"#include

    The meaning of each of these forms is given below:

    #include "goto.c" This command wouldlook for the file goto.cin the current directoryas well as the specifiedlist of directories asmentioned in theinclude search path thatmight have been set up.

    #include This command wouldlook for the file goto.c

    in the specified list ofdirectories only.

    21

  • 8/3/2019 Semester I_Paper I_Prog in C

    22/106

    Conditional Compilation

    We can, if we want, have the compiler skip over part of a source code byinserting the preprocessing commands #ifdef and #endif, which havethe general form:

    #ifdef macronamestatement 1 ;statement 2 ;statement 3 ;#endif

    Ifmacroname has been #defined, the block of code will be processedas usual; otherwise not.

    main( ){#ifdef OKAYstatement 1 ;statement 2 ; /* detects virus */statement 3 ;statement 4 ; /* specific to stone virus */

    #endifstatement 5 ;statement 6 ;statement 7 ;}

    Here, statements 1, 2, 3 and 4 would get compiled only if the macro OKAYhas been defined, and we have purposefully omitted the definition of themacro OKAY. At a later date, if we want that these statements should alsoget compiled all that we are required to do is to delete the #ifdefand#endifstatements.

    Sometimes, instead of#ifdefthe #ifndefdirective is used. The #ifndef(which means if not defined) works exactly opposite to #ifdef. Theabove example if written using #ifndef, would look like this:

    22

  • 8/3/2019 Semester I_Paper I_Prog in C

    23/106

    CHAPTER 5 PREPARING AND RUNNING A COMPLETE CPROGRAM

    Contents

    Planning a C program

    Writing a C program

    Writing a Program into the computer

    Compiling and executing

    Detecting Errors

    Debugging Techniques

    Planning a C Program

    A C program should be written using a top-down approach. It means

    than the overall program strategy should be set first and then proceed

    with the general logic of the program.

    A program outline called pseudocode is made. It contains minimal

    program logic and more of program components such as header files,

    function headings, starting and closing braces, etc.

    Example: Addition of two numbers is given by

    C = A + B

    The steps required to write a program for adding two numbers is as follows:

    1. Declare variables, A, B & C

    2. Read values for A & B

    3. Add A & B, store result in C

    4. Display the value of C

    Here is the program outline in the form of pseudocode/* Addition of two numbers*/

    void main(){

    /* declare variables a, b & c*//* Read values for a & b*//* calculate value of c*//*display the value of c */

    }

    Writing a C program

    23

  • 8/3/2019 Semester I_Paper I_Prog in C

    24/106

    If the program strategy is well planned then this should be a very

    simple straightforward step.

    Caution should be taken to make sure that the sequence of statements

    is correct.

    Example: calculating the value of c before reading the value of a & b

    is a common mistake

    Use proper indentation wherever required because it is the key that will

    help we to understand wer program when it becomes too large.

    Comment wer program wherever possible so that it reflects the

    program logic and makes it more readable

    A C program should not only execute successfully and give we results

    but also be readable and understandable.

    Example:

    /* Addition of two numbers*/

    #include #include

    void main(){

    int a, b, c; /* declare variables a, b &c*/

    c = 0; /* initialize variable c */scanf(%d%d,&a,&b); /* Read values for a & b*/c = a + b; /* calculate value of c*/printf(Result of Addition = %f,c); /*display the value of

    c */}

    Writing a Program into the computer

    Now the next step is to compile and execute the program.

    The process of Compilation and Execution is done in the software / Compiler,

    usually a Borland Turbo C/C++ compiler is widely used.

    The program can the typed and then executed in the compiler or it can be

    written in the compiler itself using its screen editor

    C programs are saved by the .c extension and c++ programs by

    .cpp.

    Example: Filenames could be

    Addition.c, idol.c, bscit.c

    24

  • 8/3/2019 Semester I_Paper I_Prog in C

    25/106

    Compiling and executing

    Now that the program is open in the compiler we are ready to compile

    it.

    Compilation is the process that tests the programs for errors. In our TC

    editor we can either use the keyboard shortcut Ctrl + c, or using the

    mouse directly click Compile in the menu bar.

    If the compilation is successful then, we get a message 0 warnings &

    0 errors, if not then the errors are listed line by line in a sequential

    order with a possible reason or mistake.

    Once the program is successfully compiled and is found to be error free

    the next step is to execute it. It could be done either by using the key

    board shortcut CTRL + r, or using the mouse to directly click on Run in

    the menu bar

    Detecting Errors

    All errors are difficult to be spotted before compiling, and are mostly

    detected when compiled.

    Compiling reveals the presence of syntactical or grammatical errors in aprogram and generates diagnostic messages

    Example: Common errors that are detected during compilation are

    Variable not defined, undefined symbol, function prototype

    missing

    25

  • 8/3/2019 Semester I_Paper I_Prog in C

    26/106

    Chapter 6 Operators and expressions

    Contents

    Arithmetic Unary Logical bit-wise assignment conditional operators

    Operators

    An operatoris a symbol that instructs C to perform some operation, oraction, on one or more operands. An operandis something that anoperator acts on. In C, all operands are expressions.

    C operators fall into several categories: The assignment operator Mathematical operators Relational operators Logical operators

    The Assignment Operator

    The assignment operatoris the equal sign (=). Its use in programming issomewhat different from its use in regular math. If we write

    x = y;in a C program, it doesn't mean "x is equal to y." Instead, it means"assign the value of y to x."

    In a C assignment statement, the right side can be any expression, andthe left side must be a variable name. Thus, the form is as follows:

    variable = expression;When executed, expression is evaluated, and the resulting value isassigned to variable.

    Mathematical Operators

    C's mathematical operators perform mathematical operations such asaddition and subtraction. C has two unary mathematical operators andfive binary mathematical operators.

    The unarymathematical operators are so named because they take asingle operand. C has two unary mathematical operators, listed in Tablebelow

    Table: C's unary mathematical operators.26

  • 8/3/2019 Semester I_Paper I_Prog in C

    27/106

    Operator Symbol Action Examples

    Increment ++ Increments theoperand by one

    ++x, x++

    Decrement -- Decrements theoperand by one

    --x, x--

    The increment and decrement operators can be used only with variables,not with constants. The operation performed is to add one to or subtractone from the operand. In other words, the statements++x;--y;are the equivalent of these statements:x = x + 1;y = y - 1;

    we should note from above Table that either unary operator can be placedbefore its operand (prefixmode) or after its operand (postfixmode).These two modes are not equivalent. They differ in terms of when theincrement or decrement is performed:

    When used in prefix mode, the increment and decrementoperators modify their operand before it's used.

    When used in postfix mode, the increment and decrementoperators modify their operand after it's usedAn example should make this clearer. Look at these two statements:

    x = 10;y = x++;

    After these statements are executed, x has the value 11, and y has thevalue 10. The value of x was assigned toy, and then x was incremented. Incontrast, the following statements result in both y and x having the value11.x is incremented, and then its value is assigned to y.

    x = 10;y = ++x;

    Remember that = is the assignment operator, not a statement of equality.As an analogy, think of = as the "photocopy" operator. The statement y =x means to copy x into y. Subsequent changes to x, after the copy hasbeen made, have no effect on y.

    Binary Mathematical OperatorsC's binary operators take two operands. The binary operators, whichinclude the common mathematical operations found on a calculator, arelisted in Table below.

    27

  • 8/3/2019 Semester I_Paper I_Prog in C

    28/106

    Table: C's binary mathematical operators.

    Operator Symbol

    Action Example

    Addition + Adds two operands x + y

    Subtraction - Subtracts the secondoperand from the firstoperand

    x - y

    Multiplication * Multiplies two operands x * yDivision / Divides the first operand

    by the second operandx / y

    Modulus % Gives the remainder whenthe first operand isdivided by the secondoperand

    x % y

    Relational OperatorsC's relational operators are used to compare expressions, askingquestions such as, "Is x greater than 100?" or "Is y equal to 0?" Anexpression containing a relational operator evaluates to either true (1) orfalse (0).C's six relational operators are listed in Table below

    Operator Symbol

    Question Asked Example

    Equal == Is operand 1 equal tooperand 2?

    x == y

    Greater than > Is operand 1 greater thanoperand 2?

    x > y

    Less than < Is operand 1 less thanoperand 2?

    x < y

    Greater than orequal to

    >= Is operand 1 greater thanor equal to operand 2?

    x >= y

    Less than orequal to

  • 8/3/2019 Semester I_Paper I_Prog in C

    29/106

    Table: C's logical operators.Operator Symbol Example

    AND && exp1 && exp2OR || exp1 || exp2NOT ! !exp1

    Table: C's logical operators in use.Expression What It Evaluates To(exp1 && exp2) True (1) only if both exp1 and exp2 are true; false (0)

    otherwise

    (exp1 || exp2) True (1) if either exp1 or exp2 is true; false (0) only ifboth are false(!exp1) False (0) if exp1 is true; true (1) ifexp1 is false

    We can see that expressions that use the logical operators evaluate toeither true or false, depending on the true/false value of their operand(s).Table below shows some actual code examples.

    Table: Code examples of C's logical operators.

    Expression What It Evaluates To(5 == 5) && (6 !=2)

    True (1), because both operands are true

    (5 > 1) || (6 < 1) True (1), because one operand is true(2 == 1) && (5 ==5)

    False (0), because one operand is false

    !(5 == 4) True (1), because the operand is false

    Compound Assignment Operators

    C's compound assignment operators provide a shorthand method forcombining a binary mathematical operation with an assignment operation.For example, say we want to increase the value of x by 5, or, in otherwords, add 5 to x and assign the result to x. We could write

    x = x + 5;Using a compound assignment operator, which we can think of as ashorthand method of assignment, we would write

    x += 5;In more general notation, the compound assignment operators have thefollowing syntax (where op represents a binary operator):

    exp1 op= exp2

    This is equivalent to writingexp1 = exp1 op exp2;

    29

  • 8/3/2019 Semester I_Paper I_Prog in C

    30/106

    We can create compound assignment operators using the five binarymathematical operators

    Table: Examples of compound assignment operators.

    When We Write This... It Is Equivalent To Thisx *= y x = x * y

    y -= z + 1 y = y - z + 1a /= b a = a / b

    x += y / 8 x = x + y / 8y %= 3 y = y % 3

    The Conditional Operator

    The conditional operator is C's only ternaryoperator, meaning that ittakes three operands. Its syntax is

    exp1 ? exp2 : exp3;

    Ifexp1 evaluates to true (that is, nonzero), the entire expressionevaluates to the value ofexp2. Ifexp1 evaluates to false (that is, zero),the entire expression evaluates as the value ofexp3. For example, thefollowing statement assigns the value 1 to x if y is true and assigns 100 to

    x if y is false:

    x = y ? 1 : 100;

    Likewise, to make z equal to the larger of x and y, we could write

    z = (x > y) ? x : y;

    Perhaps we've noticed that the conditional operator functions somewhatlike an if statement. The preceding statement could also be written likethis:

    if (x > y)z = x;elsez = y;

    The conditional operator can't be used in all situations in place of anif...else construction, but the conditional operator is more concise. Theconditional operator can also be used in places we can't use an ifstatement, such as inside a single printf() statement:

    printf( "The larger value is %d", ((x > y) ? x : y) );

    30

  • 8/3/2019 Semester I_Paper I_Prog in C

    31/106

    Bitwise Operators

    One of Cs powerful features is a set of bit manipulation operators. Thesepermit the programmer to access and manipulate individual bits within a

    piece of data.

    Operator Meaning~ Ones Complement Operator>> Right Shift Operator

  • 8/3/2019 Semester I_Paper I_Prog in C

    32/106

    Right Shift Operator

    The right shift operator is represented by >>. It needs two operands. Itshifts each bit in its left operand to the right. The number of places the

    bits are shifted depends on the number following the operator (i.e. itsright operand).

    Thus, ch >> 3 would shift all bits in ch three places to the right.

    Similarly, ch >> 5 would shift all bits 5 places to the right.

    For example, if the variable ch contains the bit pattern 11010111, then,ch >> 1 would give 01101011 and ch >> 2 would give 00110101.

    As the bits are shifted to the right, blanks are created on the left. These

    blanks must be filled somehow. They are always filled with zeros.

    main( ){

    int i = 5225, j, k ;printf ( "\nDecimal %d is same as binary ", i ) ;showbits ( i ) ;for ( j = 0 ; j >j ;

    printf ( "\n%d right shift %d gives ", i, j ) ;showbits ( k ) ;}}

    The output of the above program would be...Decimal 5225 is same as binary 00010100011010015225 right shift 0 gives 00010100011010015225 right shift 1 gives 00001010001101005225 right shift 2 gives 00000101000110105225 right shift 3 gives 00000010100011015225 right shift 4 gives 00000001010001105225 right shift 5 gives 0000000010100011

    Left Shift Operator

    This is similar to the right shift operator, the only difference being that thebits are shifted to the left, and for each bit shifted, a 0 is added to the

    right of the number.

    32

  • 8/3/2019 Semester I_Paper I_Prog in C

    33/106

    main( ){int i = 5225, j, k ;printf ( "\nDecimal %d is same as ", i ) ;showbits ( i ) ;

    for ( j = 0 ; j

  • 8/3/2019 Semester I_Paper I_Prog in C

    34/106

    Another important bitwise operator is the OR operator which isrepresented as |. The rules that govern the value of the resulting bitobtained after ORing of two bits is shown in the truth table below.

    First bit Second bit Resultant bit0 0 00 1 11 0 11 1 1

    Using the Truth table confirm the result obtained on ORing the twooperands as shown below.

    11010000 Original bit pattern00000111 OR mask-------------11010111 Resulting bit pattern

    Bitwise XOR Operator

    The XOR operator is represented as ^ and is also called an Exclusive OROperator. The OR operator returns 1, when any one of the two bits or boththe bits are 1, whereas XOR returns 1 only if one of the two bits is 1.

    The truth table for the XOR operator is given below

    First bit Second bit Resultant bit0 0 11 1 0

    XOR operator is used to toggle a bit ON or OFF. A number XORed withanother number twice gives the original number

    34

  • 8/3/2019 Semester I_Paper I_Prog in C

    35/106

    Chapter 7 Control statements

    Contents

    While do-while for statements nested loops if else, switch break, continue and goto statements comma operators

    The while Statement

    The while statement, also called the while loop, executes a block ofstatements as long as a specified condition is true. The while statement has thefollowing form:

    while (condition)statement

    conditionis any C expression, and statementis a single or compound Cstatement. When programexecution reaches a while statement, the following events occur:

    1.The expression conditionis evaluated.2. Ifconditionevaluates to false (that is, zero), the while statement terminates,and execution

    passes to the first statement following statement3. Ifconditionevaluates to true (that is, nonzero), the while statement

    terminates, and execution passes to the first statement following statement.4. Execution returns to step 1

    Figure.The operation of a while statement.

    35

  • 8/3/2019 Semester I_Paper I_Prog in C

    36/106

    /* Demonstrates a simple while statement */

    #include int count;

    int main(){/* Print the numbers 1 through 20 */count = 1;while (count

  • 8/3/2019 Semester I_Paper I_Prog in C

    37/106

    The statements associated with a do...while loop are always executed at leastonce. This is because the test condition is evaluated at the end, instead of thebeginning, of the loop. In contrast, for loops and while loops evaluate the testcondition at the start of the loop, so the associated statements are not executedat all if the test condition is initially false.

    Example:

    /* Demonstrates a simple do...while statement */#include int get_menu_choice( void );main(){int choice;choice = get_menu_choice();printf("We chose Menu Option %d\n", choice );return 0;}int get_menu_choice( void )

    {int selection = 0;do{printf("\n" );printf("\n1 - Add a Record" );printf("\n2 - Change a record");printf("\n3 - Delete a record");printf("\n4 - Quit");printf("\n" );printf("\nEnter a selection: " );scanf("%d", &selection );

    }while ( selection < 1 || selection > 4 );return selection;

    37

  • 8/3/2019 Semester I_Paper I_Prog in C

    38/106

    }1 - Add a Record2 - Change a record3 - Delete a record4 Quit

    Enter a selection: 81 - Add a Record2 - Change a record3 - Delete a record4 - QuitEnter a selection: 4We chose Menu Option 4

    The for Statement

    for (initial; condition; increment)statement(s);

    initial is any valid C expression. It is usually an assignment statement that setsa variable to a particular value condition is any valid C expression. It is usually arelational expression. When condition evaluates to false (zero), the for statementterminates, and execution passes to the first statement following statement(s);otherwise, the C statement(s) in statement(s) are executed.

    increment is any valid C expression. It is usually an expression that incrementsa variable initialized bythe initial expression. Statement(s) are the C statementsthat are executed as long as the condition remains true.A for statement is a looping statement. It can have an initialization, testcondition, and increment as parts of its command.

    The for statement executes the initial expression first. It then checks thecondition.If the condition is true, the statements execute. Once the statements arecompleted, the increment expression is evaluated.

    The for statement then rechecks the condition and continues to loop until thecondition is false.Example:/* Prints the value of x as it counts from 0 to 9 */int x;for (x = 0; x

  • 8/3/2019 Semester I_Paper I_Prog in C

    39/106

    /* entered, the loop stops */int value[10];int ctr,nbr=0;for (ctr = 0; ctr < 10 && nbr != 99; ctr++){

    puts("Enter a number, 99 to quit ");scanf("%d", &nbr);value[ctr] = nbr;}

    Nesting for StatementsA for statement can be executed within another for statement. This is callednesting.

    Nested for statements./* Demonstrates nesting two for statements */

    #include void draw_box( int, int);main(){draw_box( 8, 35 );return 0;}void draw_box( int row, int column ){int col;for ( ; row > 0; row--){for (col = column; col > 0; col--)printf("X");printf("\n");}}

    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    When we run this program, 280 Xs are printed on-screen, forming an 8*35square. The program has only one command to print an X, but it is nested in twoloops.

    In this listing, a function prototype for draw_box() is declared. This function takestwo type intvariables, row and column, which contain the dimensions of the boxof Xs to be drawn. main() calls draw_box() and passes the value 8 as the row andthe value 35 as the column.

    Looking closely at the draw_box() function, we might see a couple things wedon't readily understand. The first is why the local variable col was declared. The

    39

  • 8/3/2019 Semester I_Paper I_Prog in C

    40/106

    second is why the second printf() was used. Both of these will become clearerafter we look at the two for loops.

    The if Statement

    Relational operators are used mainly to construct the relationalexpressions used in if and while statements, how relational operators areused to makeprogram control statements.

    Statements in a C program normally execute from top to bottom, in thesame order as they appear in wer source code file.

    A program control statement modifies the order of statement execution.Program control statements can cause other program statements toexecute multiple times or to not execute at all, depending on thecircumstances.

    The if statement is one of C's program control statements. In its basic form, the if statement evaluates an expression and directs

    program execution depending on the result of that evaluation. The form ofan if statement is as follows:

    if (expression)statement;

    Ifexpression evaluates to true, statementis executed. Ifexpressionevaluates to false, statementis not executed.

    In either case, execution then passes to whatever code follows the ifstatement. We could say that execution ofstatementdepends on theresult ofexpression. Note that both the line if (expression) and the linestatement; are considered to comprise the complete if statement; they are

    not separate statements. An if statement can control the execution of multiple statements through

    the use of a compound statement, or block. As defined earlier in thischapter, a block is a group of two or more statements enclosed in braces.

    A block can be used anywhere a single statement can be used. Therefore,we could write an if statement as follows:

    if (expression){statement1;statement2;/* additional code goes here */statementn

    ;}

    Example: Demonstrates if statements./* Demonstrates the use of if statements */

    #include

    40

  • 8/3/2019 Semester I_Paper I_Prog in C

    41/106

  • 8/3/2019 Semester I_Paper I_Prog in C

    42/106

    printf("x is equal to y\n");elseif (x > y)printf("x is greater than y\n");else

    printf("x is smaller than y\n");return 0;}

    Input an integer value for x: 99Input an integer value for y: 8x is greater than yInput an integer value for x: 8Input an integer value for y: 99x is smaller than yInput an integer value for x: 99Input an integer value for y: 99x is equal to y

    The if Statement : Different formsForm 1

    if( expression )statement1;next_statement;

    This is the if statement in its simplest form. Ifexpression is true, statement1 isexecuted. Ifexpression is not true, statement1 is ignored.Form 2

    if( expression )statement1;elsestatement2;next_statement;

    This is the most common form of the if statement. Ifexpression is true,statement1 is executed; otherwise, statement2 is executed.Form 3

    if( expression1 )statement1;else if( expression2 )statement2;else

    statement3;next_statement;This is a nested if. If the first expression, expression1, is true, statement1 isexecuted before the program continues with the next_statement. If the firstexpression is not true, the second expression, expression2, is checked. If the firstexpression is not true, and the second is true, statement2 is executed. If bothexpressions are false, statement3 is executed. Only one of the three statementsis executed.

    Example 1if( salary > 45,0000 )tax = .30;

    elsetax = .25;

    42

  • 8/3/2019 Semester I_Paper I_Prog in C

    43/106

    Example 2if( age < 18 )printf("Minor");else if( age < 65 )

    printf("Adult");elseprintf( "Senior Citizen");

    The switch Statement

    C's most flexible program control statement is the switch statement, which letswer program execute different statements based on an expression that can havemore than two values.Earlier control statements, such as if, were limited to evaluating an expressionthat could have only two values: true or false. To control program flow based on

    more than two values, we had to use multiple nested if statements, as shown inListing 13.4. The switch statement makes such nesting unnecessary.

    The general form of the switch statement is as follows:switch (expression){case template_1: statement(s);case template_2: statement(s);...case template_n: statement(s);default: statement(s);}

    In this statement, expression is any expression that evaluates to an integervalue: type long, int, or char.

    The switch statement evaluates expression and compares the value against thetemplates following each case label, and then one of the following happens:If a match is found between expression and one of the templates, execution istransferred to the statement that follows the case label.If no match is found, execution is transferred to the statement following theoptional default label.If no match is found and there is no default label, execution passes to the firststatement following the switch statement's closing brace.

    Using the switch statement./* Demonstrates the switch statement. */

    #include main(){int reply;puts("Enter a number between 1 and 5:");scanf("%d", &reply);switch (reply){

    case 1:puts("We entered 1.");

    43

  • 8/3/2019 Semester I_Paper I_Prog in C

    44/106

    case 2:puts("We entered 2.");case 3:puts("We entered 3.");case 4:

    puts("We entered 4.");case 5:puts("We entered 5.");default:puts("Out of range, try again.");}return 0;}

    Enter a number between 1 and 5:2We entered 2.We entered 3.

    We entered 4.We entered 5.Out of range, try again.

    It looks as though the switch statement finds the first matching template andthen executes everything that follows (not just the statements associated withthe template). That's exactly what does happen, though. That's how switch issupposed to work.In effect, it performs a goto to the matching template. To ensure that only thestatements associated with the matching template are executed, include a breakstatement where needed. Listing 13.6 shows the program rewritten with breakstatements. Now it functions properly.

    Correct use of switch, including break statements as needed./* Demonstrates the switch statement correctly. */

    #include main(){int reply;puts("\nEnter a number between 1 and 5:");scanf("%d", &reply);switch (reply)

    {case 0:break;case 1:{puts("We entered 1.\n");break;}case 2:{puts("We entered 2.\n");break;

    }case 3:

    44

  • 8/3/2019 Semester I_Paper I_Prog in C

    45/106

    {puts("We entered 3.\n");break;}case 4:

    {puts("We entered 4.\n");break;}case 5:{puts("We entered 5.\n");break;}default:{puts("Out of range, try again.\n");

    }} /* End of switch */}

    Enter a number between 1 and 5:1We entered 1.Enter a number between 1 and 5:6Out of range, try again.

    The break Statement

    The break statement can be placed only in the body of a for loop, while loop, ordo...while loop. (It's valid in a switch statement too, but that topic isn't covereduntil later in this chapter.) When a break statement is encountered, execution

    exits the loop. The following is an example:for ( count = 0; count < 10; count++ ){if ( count == 5 )break;}

    Left to itself, the for loop would execute 10 times. On the sixth iteration,however, count is equal to 5, and the break statement executes, causing the forloop to terminate. Execution then passes to the statement immediately followingthe for loop's closing brace. When a break statement is encountered inside anested loop, it causes the program to exit the innermost loop only.

    Example: Using the break statement./* Demonstrates the break statement. */

    45

  • 8/3/2019 Semester I_Paper I_Prog in C

    46/106

    #include char s[] = "This is a test string. It contains two sentences.";main(){

    int count;

    printf("\nOriginal string: %s", s);for (count = 0; s[count]!='\0'; count++){if (s[count] == `.'){s[count+1] = `\0';break;}}printf("\nModified string: %s\n", s);

    return 0;}

    Original string: This is a test string. It contains two sentences.Modified string: This is a test string.

    The continue Statement

    Like the break statement, the continue statement can be placed only in the bodyof a for loop, a whileloop, or a do...while loop. When a continue statement executes, the nextiteration of the enclosing loopbegins immediately. The statements between the continue statement and theend of the loop aren'texecuted. The operation of continue is also shown in Figure 13.1. Notice how thisdiffers from theoperation of a break statement.Following example uses the continue statement. This program accepts a line ofinput from the keyboard and then displays it with all lowercase vowels removed.Example: Using the continue statement.

    1: /* Demonstrates the continue statement. */2:3: #include

    4:5: main()6: {7: /* Declare a buffer for input and a counter variable. */8:9: char buffer[81];10: int ctr;11:12: /* Input a line of text. */13:14: puts("Enter a line of text:");15: gets(buffer);

    16:17: /* Go through the string, displaying only those */

    46

  • 8/3/2019 Semester I_Paper I_Prog in C

    47/106

    18: /* characters that are not lowercase vowels. */19:20: for (ctr = 0; buffer[ctr] !='\0'; ctr++)21: {22:

    23: /* If the character is a lowercase vowel, loop back */24: /* without displaying it. */25:26: if (buffer[ctr] == `a' || buffer[ctr] == `e'27: || buffer[ctr] == `i' || buffer[ctr] == `o'28: || buffer[ctr] == `u')29: continue;30:31: /* If not a vowel, display it. */32:33: putchar(buffer[ctr]);34: }

    35: return 0;36: }

    Enter a line of text:This is a line of text

    Ths s ln f txtAlthough this isn't the most practical program, it does use a continue statementeffectively.Lines 9 and 10 declare the program's variables. buffer[] holds the string that theuser enters in line 15. The other variable, ctr, increments through the elementsof the array buffer[], while the for loop in lines 20 through 34 searches forvowels. For each letter in the loop, an if statement in lines 26 through 28 checksthe letter against lowercase vowels. If there is a match, a continue statementexecutes, sending control back to line 20, the for statement. If the letter isn't avowel, control passes to the if statement, and line 33 is executed. Line 33contains a new library function, putchar(), which displays a single character on-screen.

    The continue Statementcontinue;

    continue is used inside a loop. It causes the control of a program to skip the restof the current iteration of a loop and start the next iteration.

    Example

    int x;printf("Printing only the even numbers from 1 to 10\n");for( x = 1; x

  • 8/3/2019 Semester I_Paper I_Prog in C

    48/106

    The goto statement is one of C's unconditional jump, or branching, statements.When program execution reaches a goto statement, execution immediately

    jumps, or branches, to the location specified by the goto statement. Thisstatement is unconditional because execution always branches when a gotostatement is encountered; the branch doesn't depend on any program conditions

    (unlike if statements, for example).A goto statement and its target must be in the same function, but they can be indifferent blocks. Take alook at Listing 13.3, a simple program that uses a goto statement.

    Example: Using the goto statement.1: /* Demonstrates the goto statement */2:3: #include 4:5: main()6: {

    7: int n;8:9: start: ;10:11: puts("Enter a number between 0 and 10: ");12: scanf("%d", &n);13:14: if (n < 0 ||n > 10 )15: goto start;16: else if (n == 0)17: goto location0;18: else if (n == 1)19: goto location1;20: else21: goto location2;22:23: location0: ;24: puts("We entered 0.\n");25: goto end;26:27: location1: ;28: puts("We entered 1.\n");29: goto end;

    30:31: location2: ;32: puts("We entered something between 2 and 10.\n");33:34: end: ;35: return 0;36: }

    Enter a number between 0 and 10:1We entered 1.Enter a number between 0 and 10:9

    We entered something between 2 and 10.

    48

  • 8/3/2019 Semester I_Paper I_Prog in C

    49/106

    This is a simple program that accepts a number between 0 and 10. If the numberisn't between 0 and 10, the program uses a goto statement on line 15 to go tostart, which is on line 9. Otherwise, the program checks on line 16 to seewhether the number equals 0. If it does, a goto statement on line 17 sendscontrol to location0 (line 23), which prints a statement on line 24 and executes

    anothergoto. The goto on line 25 sends control to end at the end of the program. Theprogram executes the same logic for the value of 1 and all values between 2 and10 as a whole.

    The target of a goto statement can come either before or after that statement inthe code. The only restriction, as mentioned earlier, is that both the goto and thetarget must be in the same function. They can be in different blocks, however.We can use goto to transfer execution both into and out of loops, such as a forstatement, but we should never do this. In fact, I strongly recommend that wenever use the goto statement anywhere in wer programs. There are tworeasons:We don't need it. No programming task requires the goto statement. We

    can always write the needed code using C's other branching statements.

    The goto Statementgoto location;

    location is a label statement that identifies the program location where executionis to branch. A label statementconsists of an identifier followed by a colon and aC statement:location: a C statement;If we want the label by itself on a line, we can follow it with the null statement (asemicolon by itself):location: ;

    The Comma Operator

    The comma is frequently used in C as a simple punctuation mark, serving toseparate variable declarations, function arguments, and so on. In certainsituations, the comma acts as an operator rather than just as a separator. Wecan form an expression by separating two subexpressions with a comma. Theresult is as follows:Both expressions are evaluated, with the left expression being evaluated first.

    The entire expression evaluates to the value of the right expression.For example, the following statement assigns the value of b to x, thenincrements a, and then increments b:x = (a++ , b++);Because the ++ operator is used in postfix mode, the value of b--before it isincremented--is assigned to x. Using parentheses is necessary because thecomma operator has low precedence, even lower than the assignment operator.As we'll learn in the next chapter, the most common use of the comma operatoris in for statements.DO use (expression == 0) instead of (!expression). When compiled, these twoexpressions evaluatethe same; however, the first is more readable.

    DO use the logical operators && and || instead of nesting if statements.DON'T confuse the assignment operator (=) with the equal to (==) operator.

    49

  • 8/3/2019 Semester I_Paper I_Prog in C

    50/106

    50

  • 8/3/2019 Semester I_Paper I_Prog in C

    51/106

    Chapter 8 Storage types

    Contents: Automatic, external, register and static variables.

    From C compilers point of view, a variable name identifies some physicallocation within the computer where the string of bits representing the variablesvalue is stored. There are basically two kinds of locations in a computer wheresuch a value may be kept Memory and CPU registers. It is the variablesstorage class that determines in which of these two locations the value is stored.Moreover, a variables storage class tells us:

    (a) Where the variable would be stored.

    (b) What will be the initial value of the variable, if initial value is not specificallyassigned.(i.e. the default initial value).

    (c) What is the scope of the variable; i.e. in which functions the value of thevariable would be available.

    (d) What is the life of the variable; i.e. how long would the variable exist.

    There are four storage classes in C:

    (a) Automatic storage class(b) Register storage class(c) Static storage class

    (d) External storage class

    Let us examine these storage classes one by one.

    Automatic Storage ClassThe features of a variable defined to have an automatic storage class are asunder:Storage Memory.

    Default initial value An unpredictable value,which is often called agarbage value.

    Scope Local to the block inwhich the variable isdefined.

    Life Till the control remainswithin the block in whichthe variable is defined.

    51

  • 8/3/2019 Semester I_Paper I_Prog in C

    52/106

    Scope and life of an automatic variable is illustrated in the following program.main( ){auto int i = 1 ;{

    {{printf ( "\n%d ", i ) ;}printf ( "%d ", i ) ;}printf ( "%d", i ) ;}}

    The output of the above program is:1 1 1

    Register Storage Class

    The features of a variable defined to be ofregister storage class are as under:Storage CPU registers.

    Default initial value Garbage value.

    Scope Local to the block inwhich the variable isdefined.

    Life Till the control remainswithin the block in whichthe variable is defined.

    A value stored in a CPU register can always be accessed faster than the one thatis stored in memory. Therefore, if a variable is used at many places in a programit is better to declare its storage class as register. A good example of frequentlyused variables is loop counters. We can name their storage class as register.

    main( )

    {register int i ;for ( i = 1 ; i

  • 8/3/2019 Semester I_Paper I_Prog in C

    53/106

    For example, if the microprocessor has 16-bit registers then they cannot hold afloat value or a double value, which require 4 and 8 bytes respectively.However, if we use the register storage class for a float or a double variablewe wont get any error messages. All that would happen is the compiler wouldtreat the variables to be ofauto storage class.

    Static Storage Class

    The features of a variable defined to have a static storage class are as under:

    Storage Memory.

    Default initial value Zero.

    Scope Local to the block inwhich the variable is

    defined.

    Life Value of the variablepersists betweendifferent function calls.

    Example:

    main(){increment( ) ;increment( ) ;increment( ) ;}increment( ) { static int i = 1 ;printf ( "%d\n", i ) ;i = i + 1 ;}

    Like auto variables, static variables are also local to the block in which they aredeclared. The difference between them is that static variables dont disappearwhen the function is no longer active. Their values persist. If the control comesback to the same function again the static variables have the same values they

    had last time around.

    In the above example, i is static, it is initialized to 1 only once. It is neverinitialized again. During the first call to increment( ), i is incremented to 2.Because i is static, this value persists. The next time increment( ) is called, i isnot re-initialized to 1; on the contrary its old value 2 is still available. This currentvalue ofi (i.e. 2) gets printed and then i = i + 1 adds 1 to i to get a value of 3.When increment( ) is called the third time, the current value ofi (i.e. 3) getsprinted and once again i is incremented. In short, if the storage class is staticthen the statement static int i = 1 is executed only once, irrespective of howmany times the same function is called.

    In the above

    53

  • 8/3/2019 Semester I_Paper I_Prog in C

    54/106

    External Storage Class

    The features of a variable whose storage class has been defined as external areas follows:

    Storage Memory.

    Default initial value Zero.

    Scope Global.

    Life As long as theprograms executiondoesnt come to an end.

    that their scope is global, not local. External variables are declared outside allfunctions, yet are available to all functions that care to use them.Example:

    int i ;main( ){printf ( "\ni = %d", i ) ;increment( ) ;increment( ) ;decrement( ) ;decrement( ) ;}

    increment( ){i = i + 1 ;printf ( "\non incrementing i = %d", i ) ;}decrement( ){i = i - 1 ;printf ( "\non decrementing i = %d", i ) ;}

    The output would be:i = 0on incrementing i = 1on incrementing i = 2on decrementing i = 1on decrementing i = 0

    As is obvious from the above output, the value ofi is available to the functionsincrement( ) and decrement( ) since i has been declared outside all functions.

    We can make a few ground rules for usage of different storage classes in

    different programming situations with a view to:

    54

  • 8/3/2019 Semester I_Paper I_Prog in C

    55/106

    (a) economise the memory space consumed by the variables

    (b) improve the speed of execution of the program

    The rules are as under:

    Use static storage class only if we want the value of a variable to persistbetween different function calls.

    Use register storage class for only those variables that are being usedvery often in a program. Reason is, there are very few CPU registers at ourdisposal and many of them might be busy doing something else. Makecareful utilization of the scarce resources. A typical application ofregisterstorage class is loop counters, which get used a number of times in aprogram.

    Use extern storage class for only those variables that are being used byalmost all the functions in the program. This would avoid unnecessarypassing of these variables as arguments when making a function call.Declaring all the variables as extern would amount to a lot of wastage ofmemory space because these variables would remain active throughoutthe life of the program.

    If we dont have any of the express needs mentioned above, then use theauto storage class. In fact most of the times we end up using the autovariables, because often it so happens that once we have used thevariables in a function we dont mind loosing them.

    55

  • 8/3/2019 Semester I_Paper I_Prog in C

    56/106

    Chapter 9 Functions

    Contents

    Defining and accessing

    Passing arguments Function prototypes Recursion Library functions

    Function:

    A function is a self-contained block of statements that perform a coherenttask of some kind. Every C program can be thought of as a collection of thesefunctions.Using a function is something like hiring a person to do a specific job.

    Sometimes the interaction with this person is very simple; sometimes itscomplex.

    Example:main(){message( ) ;printf ( "\nCry, and we stop the monotony!" ) ;}message( ){

    printf ( "\nSmile, and the world smiles with we..." ) ;}

    And heres the output...

    Smile, and the world smiles with we...Cry, and we stop the monotony!

    Here, main( ) itself is a function and through it we are calling the functionmessage( ).when we say that main( ) calls the function message( ), We mean that the

    control passes to the function message( ).The activity ofmain( ) is temporarily suspended; it falls asleep while themessage( ) function wakes up and goes to work.When the message( ) function runs out of statements to execute, thecontrol returns to main( ), which comes to life again and begins executing itscode at the exact point where it left off.

    Thus, main( ) becomes the calling function, whereas message( ) becomesthe called function.

    56

  • 8/3/2019 Semester I_Paper I_Prog in C

    57/106

    From this program a number of conclusions can be drawn:

    Any C program contains at least one function.

    If a program contains only one function, it must be main( ).

    If a C program contains more than one function, then one (and only one) ofthese functions must be main( ), because program execution alwaysbegins with main( ).

    There is no limit on the number of functions that might be present in a Cprogram.

    Each function in a program is called in the sequence specified by thefunction calls in main( ).

    After each function has done its thing, control returns to main( ).Whenmain( ) runs out of function calls, the program ends.

    Passing Arguments

    The mechanism used to convey information to the function is the

    argument. We have unknowingly used the arguments in the printf( ) andscanf( ) functions; the format string and the list of variables used inside theparentheses in these functions are arguments. The arguments are sometimesalso called parameters.

    Consider the following program. In this program, in main( ) we receive thevalues ofa, b and c through the keyboard and then output the sum ofa, band c. However, the calculation of sum is done in a different function calledcalsum( ). If sum is to be calculated in calsum( ) and values ofa, b and care received in main( ), then we must pass on these values to calsum( ),and once calsum( ) calculates the sum we must return it from calsum( )

    back to main( ).

    /* Sending and receiving values between functions */main( ){int a, b, c, sum ;printf ( "\nEnter any three numbers " ) ;scanf ( "%d %d %d", &a, &b, &c ) ;sum = calsum ( a, b, c ) ;printf ( "\nSum = %d", sum ) ;}calsum ( x, y, z )

    int x, y, z ;{

    57

  • 8/3/2019 Semester I_Paper I_Prog in C

    58/106

    int d ;d = x + y + z ;return ( d ) ;}And here is the output...

    Enter any three numbers 10 20 30Sum = 60

    There are a number of things to note about this program:

    (a) In this program, from the function main( ) the values ofa, b and c arepassed on to the function calsum( ), by making a call to the functioncalsum( ) and mentioning a, b and c in the parentheses:

    sum = calsum ( a, b, c ) ;In the calsum( ) function these values get collected in three variables x, yand z:

    calsum ( x, y, z )int x, y, z ;

    (b) The variables a, b and c are called actual arguments, whereas thevariables x, y and z are called formal arguments. Any number ofarguments can be passed to a function being called. However, the type,order and number of the actual and formal arguments must always besame.

    (c) The return statement serves two purposes:

    (1) On executing the return statement it immediately transfers thecontrol back to the calling program.

    (2) It returns the value present in the parentheses after return, to th3ecalling program. In the above program the value of sum of threenumbers is being returned.

    Function Declaration and Prototypes

    main(){

    float square ( float ) ; // function prototypefloat a, b ;printf ( "\nEnter any number " ) ;scanf ( "%f", &a ) ;b = square ( a ) ; // function callprintf ( "\nSquare of %f is %f", a, b ) ;}float square ( float x ) // function definition{float y ;y = x * x ;return ( y ) ;

    }And here is the output...

    58

  • 8/3/2019 Semester I_Paper I_Prog in C

    59/106

    Enter any number 1.5Square of 1.5 is 2.250000Enter any number 2.5Square of 2.5 is 6.250000

    The function square( ) must be declared in main( ) asfloat square ( float ) ;

    This statement is often called the prototype declaration of the square( )function.It means square( ) is a function that receives a float and returns a float.We have done the prototype declaration in main( ) because we have called itfrom main( ).

    Recursion

    In C, it is possible for the functions to call themselves. A function is calledrecursive if a statement within the body of a function calls the samefunction. Sometimes called circular definition, recursion is thus the processof defining something in terms of itself.

    Example:Suppose we want to calculate the factorial value of an integer. As we know,the and that number. For example, 4 factorial is 4 * 3 * 2 * 1. This can alsobe expressed as 4! = 4 * 3! where ! stands for factorial. Thus factorial of anumber can be expressed in the form of itself. Hence this can be

    programmed using recursion. However, before we try to write a recursivefunction for calculating factorial let us take a look at the non-recursivefunction for calculating the factorial value of an integer.

    main( ){int a, fact ;printf ( "\nEnter any number " ) ;scanf ( "%d", &a ) ;fact = factorial ( a ) ;printf ( "Factorial value = %d", fact ) ;}

    factorial ( int x ){int f = 1, i ;for ( i = x ; i >= 1 ; i-- )f = f * i ;return ( f ) ;}And here is the output...Enter any number 3Factorial value = 6

    59

  • 8/3/2019 Semester I_Paper I_Prog in C

    60/106

    Library Functions

    A library function is a function that can be called by a program to perform sometask, but it is not part of the program itself.

    Typically library functions are collected together into libraries, which comprisesuites of functions that are loosely related in some way.

    An example might be a collection of functions that deal with dates and times andhow they can be formatted or represented.

    Libraries save programmers the bother of writing code to do the same taskstime and time again; in short, libraries encourage code reuse.

    Example : printf(), scanf();

    60

  • 8/3/2019 Semester I_Paper I_Prog in C

    61/106

    Chapter 10 Arrays

    Contents

    Defining and processing Passing arrays to a function Multi-dimensional arrays.

    The C language provides a capability that enables the user to define a set of

    ordered data items known as an array.

    Suppose we had a set of grades that we wished to read into the computer andsuppose we wished to perform some operations on these grades, we will quicklyrealize that we cannot perform such an operation until each and every grade hasbeen entered since it would be quite a tedious task to declare each and every

    student grade as a variable especially since there may be a very large number.

    In C we can define variable called grades, which represent not a single value ofgrade but a entire set of grades. Each element of the set can then be referencedby means of a number called as index number or subscript.

    Declaration of arrays:

    Like any other variable arrays must be declared before they are used. Thegeneral form of declaration is:

    type variable-name[50];

    The type specifies the type of the elements that will be contained in the array,such as int float or char and the size indicates the maximum number of elementsthat can be stored inside the array for ex:

    float height[50];

    Declares the height to be an array containing 50 real elements. Any subscripts 0

    to 49 are valid. In C the array elements index or subscript begins with numberzero. So height [0] refers to the first element of the array. (For this reason, it iseasier to think of it as referring to element number zero, rather than as referringto the first element).

    As individual array element can be used anywhere that a normal variable with astatement such as

    g = grade [50];The statement assigns the value stored in the 50th index of the array to thevariable g.More generally if I is declared to be an integer variable, then the statementg=grades [I];

    Will take the value contained in the element number I of the grades array to

    61

  • 8/3/2019 Semester I_Paper I_Prog in C

    62/106

    assign it to g. so if I were equal to 7 when the above statement is executed, thenthe value of grades [7] would get assigned to g.

    A value stored into an element in the array simply by specifying the arrayelement on the left hand side of the equals sign. In the statement

    grades [100]=95;

    The value 95 is stored into the element number 100 of the grades array.The ability to represent a collection of related data items by a single arrayenables us to develop concise and efficient programs. For example we can veryeasily sequence through the elements in the array by varying the value of thevariable that is used as a subscript into the array. So the for loop

    for(i=0;i < 100;++i);sum = sum + grades [i];

    Will sequence through the first 100 elements of the array grades (elements 0 to99) and will add the values of each grade into sum. When the for loop is finished,the variable sum will then contain the total of first 100 values of the grades array(Assuming sum were set to zero before the loop was entered)

    In addition to integer constants, integer valued expressions can also be insidethe brackets to reference a particular element of the array. So if low and highwere defined as integer variables, then the statement

    next_value=sorted_data[(low+high)/2];would assign to the variable next_value indexed by evaluating the expression(low+high)/2. If low is equal to 1 and high were equal to 9, then the value ofsorted_data[5] would be assigned to the next_value and if low were equal to 1and high were equal to 10 then the value of sorted_data[5] would also bereferenced.

    Just as variables arrays must also be declared before they are used. Thedeclaration of an array involves the type of the element that will be contained inthe array such as int, float, char as well as maximum number ofelements thatwill be stored inside the array. The C system needs this latter information inorder to determine how much memory space to reserve for the particular array.

    The declaration int values[10]; would reserve enough space for an array calledvalues that could hold up to 10 integers. Refer to the below given picture to

    conceptualize the reserved storage space.

    62

  • 8/3/2019 Semester I_Paper I_Prog in C

    63/106

    values[0]

    values[1]

    values[2]

    values[3]

    values[4]

    values[5]

    values[6]

    values[7]

    values[8]

    values[9]

    The array values stored in the memory.

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

    type array_name[size]={list of values};

    The values in the list care separated by commas, for example the statementint number[3]={0,0,0};

    Will declare the array size as a array of size 3 and will assign zero to eachelement if the number of values in the list is less than the number of elements,then only that many elements are initialized. The remaining elements will be setto zero automatically.

    In the declaration of an array the size may be omitted, in such cases thecompiler allocates enough space for all initialized elements. For example the

    statement int counter[]={1,1,1,1};

    Will declare the array to contain four elements with initial values 1. Thisapproach works fine as long as we initialize every element in the array.

    The initialization of arrays in c suffers two draw backs1. There is no convenient way to initialize only selected elements.2. There is no shortcut method to initialize large number of elements.

    /* Program to count the no of positive and negative numbers*/

    #include< stdio.h >void main( )

    63

  • 8/3/2019 Semester I_Paper I_Prog in C

    64/106

    {int a[50],n,count_neg=0,count_pos=0,I;printf(Enter the size of the arrayn);scanf(%d,&n);printf(Enter the elements of the arrayn);

    for I=0;I < n;I++)scanf(%d,&a[I]);for(I=0;I < n;I++){if(a[I] < 0)count_neg++;elsecount_pos++;}printf(There are %d negative numbers in thearrayn,count_neg);printf(There are %d positive numbers in the

    arrayn,count_pos);}

    Multi dimensional Arrays

    Often there is a need