introduction to programming using c2

Upload: clifford-eli-afedoh

Post on 29-May-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 Introduction to Programming Using C2

    1/56

    Introduction to Programming Using C

    1.1 What is C

    The C programming language is generally referred to as a middle-level as opposed to a higher-level

    language. This is because it successfully combines the structure of a high-level language with thepower and efficiency of assembly language.

    Initially, C was primarily used for writing system softwares like operating systems, compilers editorsetc. C has gained considerable popularity over the years; it is now used as a general purposeprogramming language; meaning it is used for application programming as well as system

    programming.

    1.2 Components of a Standard C Program

    All standard C programs share essential components and traits. The elements of a standard C

    program are:

    Functions

    Headers

    Preprocessors

    Comments.

    1

  • 8/8/2019 Introduction to Programming Using C2

    2/56

    Let us consider each of these components in some detail.

    1.2.1 Functions

    Functions are the main building blocks of any C program. Each of these functions contains one ormore statements which specifies a program instruction or an action to be executed. All C statementsend with a semi-colon; which means that there are no constraints on the position of statements withina line. Infact two or more statements can be on a single line. In C, functions are named subroutinesthat can be called by other parts of the program. The simplest form of a C function is:

    function-name()

    {

    statement1;

    statement2;

    .

    .

    statementn;

    }

    where function-name is the name of the function. In C, all function-names must include () and thefunction must open with a { and end with a }. Note also C recognises the difference between upperand lower case letters. For example Myfunc and myfunc are entirely different names to C

    The main() Function

    2

  • 8/8/2019 Introduction to Programming Using C2

    3/56

    Although a C program may contain several functions, the only function that it must have is the main()

    function. Themain()

    function is the function at which aC

    program execution begins. It is thereforenormally the first function of the program. The main() function requires a stdio.h header file(seebelow for definition of a header file). The general format is:

    #include

    main()

    { .body of program

    .

    }

    Types of FunctionsThere are 2 main types of functions in C. (i) the standard library functions normally supplied with theC compiler and (ii) the user-written functions; these are functions programmed by the user orprogrammer. The standard library functions falls into the following categories:

    I/O functions

    String and character functions

    Mathematics functions

    Time and data functions

    Dynamic allocation functions

    3

  • 8/8/2019 Introduction to Programming Using C2

    4/56

    Miscellaneous functions

    To make use of these functions within your own program it must be in some way access. These isdone in C by including a library function header in the program.

    1.2.2 Headers

    In C information about the standard library functions are contain is special files called header files.These files all has a .h extension and there is a file for each of the category of library functions listedabove. The C compiler uses the information in the header files to handle the library functionsproperly. The name of the header file corresponding to each of the category of library function are asfollows:

    ----------------------------------------------------------------------------Category Header File Name

    ----------------------------------------------------------------------------I/O functions stdio.h

    String string.h

    Character functions ctype.h

    Mathematics functions math.h

    Time and data functions time.h

    Dynamic allocation functions stdlib.h

    Miscellaneous functions

    ----------------------------------------------------------------------------------

    4

  • 8/8/2019 Introduction to Programming Using C2

    5/56

    1.2.4 Preprocessors

    All C compilers use as their first phase of compilation a preprocessor which performs variousmanipulation on the C program source file before it is actually compiled. Preprocessor directives arenot actually part of the C language but rather instructions from you the program writer to the Ccompiler.

    One of these directives is to ask the compiler to include a specific header file in your program so thatyou can be able the program can be able to access a corresponding library function.

    For example supposing your program calls a specific I/O library function, the information has to becommunicated to the compiler through an appropriate preprocessor directive that a stdio.h headerfile should be included in the program before compilation. In C, this information is communicated byusing the #include preprocessor directive. The general format is:

    #include"header-file"or

    #include

    For example: #include

    In general all preprocessor directives are preceded with #. Other types of preprocessors are:

    #define

    5

  • 8/8/2019 Introduction to Programming Using C2

    6/56

    #if

    #else

    #endif

    #ifdef

    #ifndef

    In this course we shall concentrate on #include and #define

    1.2.5 CommentsIn C comments are enclosed in /* */. The general format is:

    /*place your comments here*/

    1.3 Outline of a C Program

    With the components of a C program presented in section 1.2, we present below an outline of anystandard C program:

    /*program heading*//* main program*/

    preprocessors

    main()

    {

    function1()

    6

  • 8/8/2019 Introduction to Programming Using C2

    7/56

    function2()

    function3()

    .

    functionk()

    }

    /*called functions*/

    function1()

    {

    statement1.1

    statement1.2

    .

    statement1.n

    }

    function2()

    {

    statement2.1

    statement2.2

    .statement2.n

    }

    .

    functionk()

    {

    7

  • 8/8/2019 Introduction to Programming Using C2

    8/56

    statementk.1

    statementk.2

    .

    statementk.n

    }

    1.4 Simple C ProgramsWe are now ready to write some simple C programs. First we introduce a very important libraryfunction ; the printf() function.

    The printf() function

    This function is the C's general purpose output function. It is one of the most popular I/0 function.Like the main() function it requires a file header. It's general format is:

    printf("output-string")

    This will output the "output-string" on a default device e.g the terminal screen. Let us consider someexamples:

    8

  • 8/8/2019 Introduction to Programming Using C2

    9/56

    /* this program prints HELLO!!!*/

    #include

    main()

    {

    printf("HELLO!!!");

    }

    When compile and executed, this program will display the message HELLO!!! on the screen. Note thatthis simple program illustrates those key aspects of any standard C program.

    The 1st line is reserved for a comment in this case the program heading. This is followed by the#include which causes the file to be read by the C compiler and to be included inthe program. This file contains information related to the printf() function.

    The 3rd line begins with themain()

    function immediately followed by{; signalling where theexecution of the program will start. The nest line is: printf("HELLO!!!"). This is a C statement; it calls

    the standard library function, printf(), which causes the output-string to be displayed.

    Finally the program ends with the usual }.

    9

  • 8/8/2019 Introduction to Programming Using C2

    10/56

    /*this program prints 'This is a short C Program'*/

    #include

    main()

    {

    printf("This is a short C Program");

    }

    /*this is another version of Program 1.4.2*/

    #include

    main()

    {

    printf("This is ");

    printf(" a short C ");

    printf(" Program");

    }

    This program like Program 1.4.2 will display the message:

    This is a short C Program

    The next 2 example programs makes use of library functions as well as user-written functions.

    10

  • 8/8/2019 Introduction to Programming Using C2

    11/56

    /* A program with two user functions*/

    #include

    main()

    {

    printf("I");

    func1();

    printf(" in C ");

    func2();

    }

    func1()

    {

    printf( "can program ");

    }

    func2()

    {

    printf(' language");

    }

    11

  • 8/8/2019 Introduction to Programming Using C2

    12/56

  • 8/8/2019 Introduction to Programming Using C2

    13/56

    {

    func3();

    printf(" 2 ");

    }

    func3()

    {

    printf(" 1 ");

    }

    func2()

    {

    printf(" jump ");

    func1();

    }

    func1()

    {

    printf(" the wall ");

    }

    13

  • 8/8/2019 Introduction to Programming Using C2

    14/56

  • 8/8/2019 Introduction to Programming Using C2

    15/56

    2.0 VARIABLE DECLARATIONS &

    ASSIGNMENT STATEMENTS

    In this section we introduce two extra components of C; namely C variable declarations andassignment statements.

    2.1 C Data TypesThe C compiler supports five different basic data types. This are represented in Table 2.1

    Table 2.1

    Data Type Meaning Keyword Examples

    integer signed whole numbers int -18, 76float floating-point numbers float 6.2,-45.3character character data char 'a', '$', 'M'double double precision (float) double

    void valueless void

    2.2 Variable Declarations

    15

  • 8/8/2019 Introduction to Programming Using C2

    16/56

    Variable declaration in C is used to inform the compiler what type of variable is being used. Thevariable may be an int, float,char double or void data type. The general format for declaring variablesin C is:

    type variable-name;

    where type is a C data type and variable name is the name of the variable. For example can declare avariable sumas an integer variable in C as:

    int sum;

    we such a declaration, the variable sum will hold only integer data type. You can declare more thanone variable of the same data type by using commas to separate them . e.g

    float x, total, y, zoom

    16

  • 8/8/2019 Introduction to Programming Using C2

    17/56

    Points to Note when Declaring Variables

    1. Variables can be declared inside a function (local variables) or outside all functions (globalvariables).A local variable is accessed by only the function it is declared whiles a global variable canbe accessed by all functions in the program.

    2. Global variables should be declared in the main program preferably immediately after the {

    symbol following the main() function. On the other hand it is common to declare local variables of agiven function at the start of the function immediately after the { symbol.

    3. Local variables in one function has no relationship to local variables in another function. That is if alocal variable sum is declared in one function, a second local variable sum can be declared in a secondfunction; the two variables has no relationship to each other.

    4. Local variables are created when the corresponding function is called by the main program andthey are destroyed when the function is exited. Therefore local variables do no maintain their valuesbetween function calls.

    17

  • 8/8/2019 Introduction to Programming Using C2

    18/56

    2.3 Assignment Statements

    Assignment statements are use in C to assign values to variables. The variable must be declaredearlier on on the program. The simplest form of an assignment statement is:

    variable-name=value(arith. expression)

    where value may be a constant or an arithmetic expression which when evaluated by the programwill yield a single value.Let us consider some examples:

    num = 120;sum= x+y;

    rate=prime;

    inches=12*feet;total=(score1+score2+score3)*factor;

    Format Specifier

    In C a format specifier are used in I/O functions like printf() to inform the compiler the data typebeing I/O. The format specifier for each of the data type described above is given in Table 2.3.

    Table 2.3------------------------------------------------------------------------------------------------Data Type Format Specifier-------------------------------------------------------------------------------------------------integer %dfloat %f

    18

  • 8/8/2019 Introduction to Programming Using C2

    19/56

    double %fcharacter %c

    void-------------------------------------------------------------------------------------------------

    Let us consider the following C program:

    #include

    main()

    {

    float x,y;

    int sum;

    x=2.2;

    y=12.8;

    printf("The sum of x and y is %d",sum);

    }

    execution of this program will result in the output:

    The sum of x and y is 15

    Note that the variable sum is declared as an integer and this information is committed to the printf()function with the integer format specifier %d. The % sign tells the printf() function we wish to print anumber in the place in the message where the % is located.

    19

  • 8/8/2019 Introduction to Programming Using C2

    20/56

    During execution, the printf() function substitutes the value (or values of arithmetic statements) of the

    next argument in the place where the format specifier appears in the message. Let us consider somemore examples:

    1. printf("This displays %d, too",100);

    result: This displays 100 too

    2. printf("The total of 6 and 12 is %d.",6+12);

    result: The total of 6 and 12 is 21.

    3. printf("The sum of %f and %f is %f.", 12.2, 15.754, 12.2+15.754);

    result: The sum of 12.200 and 15.75400 is 27.954000

    4. printf("The first letter of the alphabet is an %c.", 'a');

    result: The first letter of the alphabet is an a.

    Note that printf() function in examples 2 and 3 contains arithmetic statements as part of its argument.In general C supports 5 arithmetic operations namely:

    +(add),-(subtract),*(mult.),/(div.) and %(modulus)

    20

  • 8/8/2019 Introduction to Programming Using C2

    21/56

    The modulus returns the remainder of an integer division (e.g 10%3 is equal to 1). Program 2.3.2illustrates the use of these operands in a printf() function.

    include

    main()

    {

    printf("%d", 5/2);

    printf(" %d", 5+2);

    printf(" %d", 4/2);

    printf(" %d", 7%2);

    printf(" %d", 2*6);

    printf(" %f", 12.8-4.6);

    }

    On execution the program will print out:

    2 7 2 1 12 8.2

    The following C program creates variable types char, float, and double; assigns each a value; andoutputs these values on the screen.

    21

  • 8/8/2019 Introduction to Programming Using C2

    22/56

    #include

    main(){

    char baam;

    float time;

    double velocity;

    baam='X';

    time=100.125;

    velocity=156.009;

    printf("baam is %c, ", baam);

    printf("time is %f, ", time);

    printf("velocity is %d, ", velocity);

    }

    22

  • 8/8/2019 Introduction to Programming Using C2

    23/56

    2.4 Input from the Keyboard

    So far we have learn how to output data and message on the terminal using the printf() function. Likeoutput, C provides a library function for input from a designated device like the keyboard of a file.For a moment we shall consider inputs from the keyboard only. This is done using the scanf() libraryfunction.

    The scanf() function

    The scanf() function requires format specifier and variable names as its key arguments. The generalformat is:

    scanf("format-specifiers", &variable-name);

    Note that the & preceding the variable-name is essential to the operation of scanf(); it allows thefunction to place a value into one of its arguments. The followings are some examples usage of thescanf() function:

    scanf("%d", &num);

    scanf("%f", &grade);scanf("%c",&initials);

    scanf("%d%d%c", &num1,&num2,&ch1);

    scanf("%c%c%d%f", &ch1,&ch2,&flag,&average);

    23

  • 8/8/2019 Introduction to Programming Using C2

    24/56

    The following program makes use of the scanf() function. The program asks you to input an integerand a floating-point number and it display the values.

    #include

    main()

    {

    int num;float var1

    printf("Enter an integer: ");

    scanf("%d", &num);

    printf("Enter a floating-point number: ",);

    scanf("%f", &var1);

    printf("%d", num);

    printf("%f", var1);

    }

    Let us consider another example.

    #include

    main()

    {

    int len, width;

    24

  • 8/8/2019 Introduction to Programming Using C2

    25/56

    printf("Enter length: ");

    scanf(%d", &len);

    printf("Enter width: ");scanf("%d", &width);

    printf("Area is %d ", len*width);

    }

    25

  • 8/8/2019 Introduction to Programming Using C2

    26/56

    2.5 Using Standard Library Mathematical FunctionsIn C standard mathematical library functions can be used to a value to a calling routine. Example ofsome of these math. functions are: sqrt,cos,sin etc. These functions requires a math.h header file. Letus consider some example programs:

    Program 2.5.1

    /* this program makes use of the sqrt maths function */

    #include

    #include /*needed by sqrt function */

    main()

    {

    double answer;

    answer = sqrt(16.0);

    printf("The square root is %f ", answer);}

    Alternatively Program 2.5.1 can be written such that the sqrt could simple be an argument of theprintf() function:

    26

  • 8/8/2019 Introduction to Programming Using C2

    27/56

    Program 2.5.2

    #include

    #include /*needed by sqrt function */

    main()

    {

    printf("The square root is %f ", sqrt(16.0));}

    In this example the printf() function is the calling routine and the sqrt function returns a value to it tobe output on the screen.

    The return Statement

    The results of a user-written function can be return to a calling routine using the return statement. Thegeneral format of the return statement is:

    return value;

    where value is the value to be returned.

    The following example illustrates this.

    Program 2.5.3

    27

  • 8/8/2019 Introduction to Programming Using C2

    28/56

    P

    /* this program prints the value 10 on the screen */

    #include

    main()

    {

    int num;

    num = funct();

    printf("%d", num)}

    funct()

    {

    return 10;

    }

    Note that in Program 2.5.3 the function funct() returns a value 10 to the main program. However thevalue associated with the return statement need not be a constant; it can be any valid C expression.(see Program 2.5.4). You can even use the return statement without even specifying avalue/expression. This has the effect of causing the function to return control the calling routine(seeProgram 2.5.5) A program or a function may contain more than one return statements.

    rogram 2.5.4

    /* this illustrates how to associate expression to return statements */

    #include

    28

  • 8/8/2019 Introduction to Programming Using C2

    29/56

    main()

    {

    int var1;var1= get_sqr();

    printf("square: ", var1);

    }

    get_sqr()

    {

    int num;printf("enter a number: ");

    scanf("%d", &num);

    return num*num /* sq. the number */

    }

    Program 2.5.5

    /* this program use of the return statement to transfer control */

    #include

    main()

    {

    funct1();}

    funct1()

    {

    printf("this is printed");

    return;

    29

  • 8/8/2019 Introduction to Programming Using C2

    30/56

  • 8/8/2019 Introduction to Programming Using C2

    31/56

    {

    sum(1, 20);

    sum(9, 6);sum(81, 9);

    }

    sum(int x, int y)

    {

    printf("The sum is: %d ", x+y);

    }

    This program will print 21, 15, 90 on the screen.

    Program 2.6.2

    /* this program use the outchar function*/

    #include

    main()

    {

    outchar('A');

    outchar('B');outchar('C');

    }

    outchar(char alph)

    {

    printf("%c", alph);

    31

  • 8/8/2019 Introduction to Programming Using C2

    32/56

    }

    This program prints A B C on the screen.

    2.7 Escape Sequences

    In C a backslash (\) can be used directly in front of a selected group of characters to tell the computer

    to escape from the way these characters would normally be interpreted. A combination of \ and thesespecific characters is called escape sequence. The following is the list of these escape sequences:

    escape sequence meaning

    -----------------------------------------------------------------------------------\b move back one space

    \f move to next page\n move to next line\r carriage return\t move to next (horiztl.) tab setting\v move to next vertical tab setting\\ backslash character

    \' single quote\a bell\nnn treat nnn as an octal number

    ------------------------------------------------------------------------------------

    Lets consider some examples using the printf() function.

    32

  • 8/8/2019 Introduction to Programming Using C2

    33/56

    Using the \n Control Sequence

    #include (

    main()

    {

    printf("this is line one\n");

    printf("this is line two\n);printf("this is line three");

    }

    The output of this program will be:

    this is line onethis is line two

    this is line three

    Note that the \n does not have to go at the end of the string to be output as in the above program; itcan go anywhere in the string as shown below:

    #include

    main()

    {

    printf("one\ntwo\nthree\nfour");

    33

  • 8/8/2019 Introduction to Programming Using C2

    34/56

    }

    the output will be:

    one

    two

    three

    four

    Lets consider another example:

    #include

    main()

    {

    printf("\n%d", 6);printf("\n%d", 18);

    printf("\n%d", 124);

    printf("\n-----");

    printf("n%d", 6+18+124);

    }

    this program will output:

    6

    18

    124

    34

  • 8/8/2019 Introduction to Programming Using C2

    35/56

    ----

    148

    35

  • 8/8/2019 Introduction to Programming Using C2

    36/56

    Controlling the flow of a C Program like any other program involves the use of special conditionaland unconditional statements like : the if, if-else, the for-loop, while-loop, do-loop, the switch andthe goto statements. Lets consider each in some detail.

    3.1 The if Statement

    The general format:

    if(expression) statement;

    example:if(age==13) printf("Welcome to the teenager world")

    The expression may be any valid C expression. If the expression evaluates as true, the statement willbe executed otherwise it will be by-passed and the line code following the if statement executed.

    In C, an expression is true if it evaluates to any non-zero value otherwise it is false. The statement thatfollows the if statement is referred to as the target of the if statement.

    36

  • 8/8/2019 Introduction to Programming Using C2

    37/56

    In the above example, printf("Welcome to the teenager world") is the target. The expression inside theif compares one value with another using a relational operator. In the example above, the relational

    operator ==(equals) is used to compare age with 13.

    In C the following relational and logical operators are used:

    operator meaning example------------------------------------------------------------------------------------------------relational

    < less than age < 30> greater than weight >10=7.8== equals to grade== 10!= not equal to num != 340

    logical&& AND a>0 && b

  • 8/8/2019 Introduction to Programming Using C2

    38/56

    Some examples relational operators:

    if(15>9) printf("this is true");

    in this example since the if expression is true the statement this is true will be printed.

    if(32 < 23) printf("this is strange");printf("this is not true");

    in this case since the if expression is false, the printf() will no be executed, hence the statement: this isstrange will not be printed, rather control will be transfer to the next program line the the statement:this is not true will be printed.

    The following program either converts feet to meters of meters to feet depending upon what the userrequest:

    #include

    main(){

    float value;

    int choice;

    printf("enter value:")

    38

  • 8/8/2019 Introduction to Programming Using C2

    39/56

    scanf("%f", &value);

    printf("1: ft. to meters, 2: meters to ft.");

    printf("enter choice: ");scanf("%d", &choice);

    if(choice==1) printf("%f", value/3.28);

    if(choice==2) printf("%f", value*3.28);

    }

    The if-else Statement

    general format:

    if(expression) statement1;

    else statement2;

    If the expression is true, then statement1 will be executed and the else portion skipped, otherwisestatement2 will be executed.

    example:

    if(num==5) printf("BINGO!! you've won")

    else printf("hard luck;try next time")

    39

  • 8/8/2019 Introduction to Programming Using C2

    40/56

    We could re-write Program 3.1.1 using the if-else combination as follows:

    #include

    main()

    {float value;

    int choice;

    printf("enter value:")

    scanf("%f", &value);

    printf("1: ft. to meters, 2: meters to ft.\n");

    printf("enter choice: ");scanf("%d", &choice);

    if(choice==1) printf("%f", value/3.28);

    else(choice==2) printf("%f", value*3.28);

    }

    Creating Block of Code:

    In C two or more statements can be linked together to form a block of code. For example the if-elsecombination can be used in conjunction with blocks of code. The general format is:

    40

  • 8/8/2019 Introduction to Programming Using C2

    41/56

    if(expression){

    statement1.1statement1.2

    .

    .

    statement1.N

    }

    else{

    statement2.1

    statement2.2

    .

    .

    statement2.N}

    There are two blocks of code; one after the if expression (this is executed if the if expression is true)and the other is after the else (this is executed if the if expression is false). Lets consider an example:

    #include

    main()

    {

    41

  • 8/8/2019 Introduction to Programming Using C2

    42/56

    int answer;

    printf("What is the prime number after 5? ");scanf("%d", &answer):

    if (answer != 7) {

    printf("not smart!! ");

    printf("what is the matter with you these

    days\n");printf("the answer is 7");

    else {

    printf("clever chap\n");

    printf("you are doing just fine");

    }

    }

    3.3. The for loop

    The for loop is the most flexible of the C loop statements. It allows one or more statements to berepeated.

    42

  • 8/8/2019 Introduction to Programming Using C2

    43/56

    general format:

    for(initialization;test condition; increment) statement;

    The variable that controls the loop is referred to as the loop-control variable.In the general format,initializationassigns an initial value to the loop-control variable, the conditional test, tests the loop-control variable against a target value each time the loop repeats, and incrementis the value by which

    the control-variable is increased each time. If this is left-out, the program assumes a default value of1. In C a special operator is provided for increasing or decreasing values of a counter. e.g

    i=i+1 is equivalent to i++num=num+1 is equivalent to: num++count=count-1 is equivalent to: count--

    An example of the general format of the for loop is therefore:

    for(i=0; i

  • 8/8/2019 Introduction to Programming Using C2

    44/56

    #include

    main()

    {

    int num, i, prime;

    printf("Enter a number:");

    scanf("%d", &num);

    /* testing for prime */

    prime = 1;

    for(i=2; i < num/2; i++)

    if((num%i)==0) prime=0;

    if(prime==1)printf("number is prime:");

    else printf("number is not prime");

    }

    3.4 The nested ifstatement

    A nested if is a if statement which is a target of another if or else statement. The general format is:

    if( expression) /* outer if */

    44

  • 8/8/2019 Introduction to Programming Using C2

    45/56

    if(expression) statement; / * nested if */else statement;

    example:

    if(num >4)

    if(num < 10) printf("number is within range\n");

    else printf("number is outside range");

    3.5 The if-else-ladder

    This is a string of ifs and elses. The general format is:

    if(expression)statement;else

    if(expression)statement;else

    .

    .if(expression)statement;

    3.6 The if- else ifcombination

    45

  • 8/8/2019 Introduction to Programming Using C2

    46/56

    A better alternative to the if-else-if ladder is the if-else if combination. The general form of this is:

    if(expression)

    statement;

    else if(expression)

    statement;

    else if(expression)

    statement;.

    .

    else

    statement;

    Lets consider an example:

    #include

    main()

    int grade

    printf("enter student grade);

    scanf("%d", &grade);

    46

  • 8/8/2019 Introduction to Programming Using C2

    47/56

    if(grade = 90)

    printf("BRAVO!! you got an A+");

    else if(grade >= 80)

    printf("EXCELLENT!! you got an A");

    else if(grade >= 65)

    printf("GOOD WORK!!, you got a B);

    else if(grade >= 50)

    printf(" you got a C");

    else

    printf("POOR WORK!!, you got a C);

    }

    47

  • 8/8/2019 Introduction to Programming Using C2

    48/56

    3.7 The while loop

    The general format of the while loop is:

    while(expression)statement;

    The target of the while loop may be a single statement or a block of statements. The while loop

    repeats its target as long as the expression is true.

    example:

    #include

    main()

    {int count;

    while(num

  • 8/8/2019 Introduction to Programming Using C2

    49/56

    ++count /* add 1 to count */

    }

    }

    the output of this program will be:

    1 2 3 4 5 6 7 8 9 10

    3.8 The do loop

    The general format of the do loop is:

    do {statement

    }while(expression);

    Again the statementcould be a block of C statements. like do loop repeats the statement or block ofstatements while the expression is true. The following program illustrates the do loop.

    49

  • 8/8/2019 Introduction to Programming Using C2

    50/56

    #include

    main()

    {

    float price, rate;

    rate = 3.5;

    do

    {

    printf("\nEnter a price: ");

    scanf("%f", &price);

    salestax = rate*price;

    printf("The sales tax is: \n %f", salestax);}

    while(price >= 4 && price

  • 8/8/2019 Introduction to Programming Using C2

    51/56

    The break statement can be use to exit a loop from any point within it. It is generally used in loopswhich a special condition can cause immediate termination of the loop. The following 2 programs

    illustrates the use of the break statement.

    #include

    main(){

    int num;

    for(num=1; num < 100; num++) {

    printf("%d", num);

    if(num==10)break; /* exit loop */}

    }

    In the next program, the loop is exit if N is pressed. Note also the use of the getchar() function for

    input of a single character input from the keyboard.

    #include

    #include /* header file for getchar() function */

    51

  • 8/8/2019 Introduction to Programming Using C2

    52/56

    main()

    {

    int i;

    char ch;

    /* display all numbers which are multiples of 8 */

    for (i=1; i

  • 8/8/2019 Introduction to Programming Using C2

    53/56

    character constants and when a match is found, it executes a sequence of statements associated withthat match. The general form of the switch statement is:

    switch(expression) {

    case constant1:

    statement sequence

    break;

    case constant2:statement sequence

    break;

    .

    .

    default:

    statement sequence}

    The following program illustrate the use of the switch statement. It is a good example of how theswitch statement can be used to write program menus.

    /* this program uses the switch statement to select

    * arithmetic operation (add mult. div.) to be performed

    * on 2 numbers depending the option selected */

    #include

    53

  • 8/8/2019 Introduction to Programming Using C2

    54/56

    main()

    {int option

    double fnum, snum;

    printf("Please type in 2 numbers: );

    scanf("%f %f, &fnum, snum);

    printf("Enter a select code: );

    printf("\n 1: for addition");

    printf("\n 2: for multiplication")

    printf("\n 3: for addition");

    scanf("%d", &option);

    switch(option)

    {

    case 1:

    printf("\nThe sum of the numbers is %f", fnum+snum);

    break;

    case 2:

    printf("\nThe product of the numbers is %f", fnum*snum);

    break;

    54

    case 3:

  • 8/8/2019 Introduction to Programming Using C2

    55/56

    case 3:

    printf("\nThe 1st no. div. by the 2nd is %f", fnum/snum);

    break;

    default:

    printf("\nUnrecognised numbers");

    } /* end of switch statement */

    } /* end of program */

    Note the switch statement unlike the if statement can only test for equality. Also switch works withonly int and char types

    3.10 The goto Statement

    The goto statement is a non-conditional jump statement. The general format is:

    goto statement

    A simple illustration is given below:

    #include

    55

    main()

  • 8/8/2019 Introduction to Programming Using C2

    56/56

    56

    main()

    {

    int num;

    num = 1;

    repeat;

    printf("%d", num*num);num++

    if(num < 12) goto repeat;

    printf("end of program execution");

    }

    In this program control is transfer to repeat if the if statement is true otherwise the program exit.