C Training Notes

Embed Size (px)

Citation preview

  • 8/2/2019 C Training Notes

    1/25

    C Programming by

    Zulkhairi Mohd Yusof

    Rev 1.0

  • 8/2/2019 C Training Notes

    2/25

    2

    The following concept will be introduced, examples will be shown and exercises will begiven DIGS (basic), CDR (advanced) and FPASS (professional).

    DIGS Declare, Initialize, Get from user and ShowCDR Compute, Decide and RepeatFPASS Function, Pointers, Array, String and Structure

    1st concept.Computer as storage area ( memory ).There are three types of storage bin ( data types ).

    Int float char

    There are three types of data ( constants ).

    3.14 255 A(decimal point) (x decimal point) character on keyboardFloat / real integer char

    Each type of data can only be stored in its appropriate storage bin.

    Program Edit, Save, Compile, Execute using IDE

    1st program (skeleton)

    void main(void){

    }

  • 8/2/2019 C Training Notes

    3/25

    3

    Knowing the type of data, and give a name to the storage bin is called declaration.

    Data constants : 67, 45, 92, 55, 34 etc (these are exams score)Give it a name ( variable name): ExamScore or Score or Math_Score etc.Data type : integer (because no decimal point!)

    We reserve in memory, a place to store exam score of type integer Score

    void main( void ){

    int Score ; }

    Names other than keywords must be declared

    ex 1.1

    A cashier has currency notes of denominations 10, 50 and 100. If the amount to be withdrawn

    is input through the keyboard in hundreds, find the total number of currency notes of eachdenomination the cashier will have to give to the withdrawer.

    variable data typeamount eg. 200 integer total10 3 integer total50 0 integer total100 2 integer

    void main( void ){

    // declare variablesint amount ;int total10, total50, total100 ;

    }

  • 8/2/2019 C Training Notes

    4/25

    4

    Give an initial value to a variable.

    We reserve in memory, a place named Score of type integer, and store aninitial value 35.

    Score

    void main( void ){

    int Score = 35 ; }

    ex 2.1

    A cashier always has RM250 reserve in the cash register every morning. Find the balance inthe cash register at the end of the day.

    void main( void ){

    // declare variables

    float reserve = 250.0 ;float balance ;}

    35

  • 8/2/2019 C Training Notes

    5/25

    5

    Sometimes we do not know the value. We get the value from user.We use a library function called scanf .

    scanf is not a keyword, therefore it must be declared somewhere. Therefore, either youdeclare the function (chap 3-1) or use a function already declared by somebody else (in thelibrary). To use a library function, we type,

    #include < stdio.h > where stdio.h is the library (h is header files)This statement is placed on top of the program (before any function).

    eg. to get a data from user into a variable called year, we type:scanf("% d", & year );

    %d is a control character. Control characters (preceded by a %) depend on the data type:control character data type%d integer %f float/real%c char

    Notice, &year is used instead of year. This is a pointer (chap 3-2).For now, just remember the syntax; scanf("% d", & year );

    ex 3.1

    Get a radius of a circle from user and compute the area of the circle.

    #include < stdio.h >

    void main( void ){

    // declare variablesfloat radius ;

    float area ;

    scanf("% f ", & radius );}

  • 8/2/2019 C Training Notes

    6/25

    6

    Show the content of the variables to user.

    We use a library function called printf .

    printf is not a keyword, therefore it must be declared. To use this library function, we type,#include < stdio.h >

    eg. to show the content of variable year , we type:printf("% d", year ); -> 2009

    The syntax is almost similar to scanf, except for the &.

    To show any text on the screen, just type:printf(" hello world "); -> hello world

    To print combination of text and variable content on the screen, type:printf(" radius = %f ", radius ); -> radius = 3.146656

    ex 4.1

    Get a radius of a circle from user. Print and radius on the screen.

    #include < stdio.h >

    void main( void ){

    // declare variablesfloat radius ;float pi = 3.142857 ;

    printf("Enter radius : ");scanf("%f", &radius);

    printf(" pi = % f \n", pi);printf(" radius = % f ", radius );

    }

    Now, there is a \n in the syntax. \n is an escape sequence . It can be said as representing aspecial key on your keyboard.escape sequence key\n new line\t horizontal tab\\ backslash

  • 8/2/2019 C Training Notes

    7/25

    7

    \b backspace\" quotation mark \' apostrophe

  • 8/2/2019 C Training Notes

    8/25

    8

    Common programming mistake:

    1. mis-spelled keyword: eg. mian instead of main2. forgot semicolon at the end of statement3. extra semicolon when not needed: eg. void main(void) ;

    eg..#include ;4. forgot &: eg. scanf("%d", year);5. missing double quote: eg. printf(hello world);6. misplaced the double quote: eg. printf(radius = %d, radius);

    Quiz 1

    Get from user his or her initial. Then print a welcome screen.

    Heres what the output screen looks like:

    Please enter your initial : Z

    Assalamualaikum Z!Welcome to C programming.

  • 8/2/2019 C Training Notes

    9/25

    9

    5 (C) Compute

    An important reason for using a computer very fast calculation.

    arithmetic instruction format:var =

    Among the arithmetic operators are:+, -, *, /(division), %(mod)Any formula can be translated into the arithmetic instruction format.

    eg. area = r 2, translated into: area = pi * radius * radius

    Also important is the type conversion . Basically,operation example resultint int 2/5 0int float 2/5.0 0.4float float 2.0/5.0 0.4int int 2%5 2

    ex 5.1

    Get a radius of a circle from user. Calculate the area of the circle and print the result.

    #include

    void main(void){

    //declare variablesfloat radius;float pi = 3.142857;float area;

    printf(Enter radius : );scanf(%f, &radius);

    //calculate areaarea = pi * radius * radius;

    printf("Area = %f\n", area);}

  • 8/2/2019 C Training Notes

    10/25

    10

    Computer can also make decision.We use keywords if , if-else , if-elseif , switch

    conditional statement format: where the conditional operators are:>, =, 3.5) printf(The area is ok.);

    using switch statement:

    eg.switch (ans){

    case Y: printf(Yes); break ;case N: printf(No); break ;default: printf(Others);

    }

    without break, thenif ans==Yes, thecomputer will print

    both Yes, No andOthers

    No semicolon

  • 8/2/2019 C Training Notes

    11/25

    11

    equivalent using if-elseif (ans==Y)

    printf(Yes);else{

    if (ans==N) printf(No);

    else printf(Others);

    }

    equivalent using if-elseif if (ans==Y)

    printf(Yes);elseif (ans==N)

    printf(No);else

    printf(Others);

    eg. 6.1

    Decide the fate of Malaysian soccer team based on the number of goals scored against theteam.

    #include

    void main(void){

    int goals ; printf ("Enter the number of goals scored against Malaysia : " );scanf ("%d", &goals );if ( goals

  • 8/2/2019 C Training Notes

    12/25

    12

    Computer can continue repeating tasks until instructed to stop.We use keywords for , while and do-while

    Basically, need to specify the initial value (init), when to stop (condition) and the step(increment or decrement).

    using for statement:

    for (initial value; stop condition; step)

    Nosemicolon

    If using only one statement, usesemicolon.

    If more than one statements, useblock. Then, no need semicolon.

    indent

    eg. for (i=0, i i=0 i=1 i=2

    using while statement:

    initial value;while (stop condition){

    ..step;

    }

    eg. equivalent to the above for statementsi=0;

    while (i

  • 8/2/2019 C Training Notes

    13/25

    13

    eg. 7.1

    Two numbers are entered through the keyboard. Write a program to find the value of onenumber raised to the power of another.

    #include

    void main(void){

    int a, b, result, i ;

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

    printf ("Enter a number (raised to the power of) : " );scanf ("%d", &b );

    result = 1;for (i=0; i

  • 8/2/2019 C Training Notes

    14/25

    14

    Quiz 2

    Write a program to enter five numbers. At the end it should display the count of positive,negative and zeros entered.

    Heres what the output screen looks like:

    Please enter five numbers:-12 5 0 3 -1

    You have 2 positive numbersYou have 2 negative numbersYou have 1 zeros

  • 8/2/2019 C Training Notes

    15/25

    15

    Writing functions avoids rewriting the same code over and over. Using functions it becomes easier to write programs and keep track of what they are

    doing. If the operation of a program can be divided into separate activities, and eachactivity placed in a different function, then each could be written and checked more or less independently.

    Separating the code into modular functions also makes the program easier to designand understand.

    Any C program contains at least one function. If a program contains only one function, it must be main( ) . Program execution always

    begins with main( ) . There is no limit on the number of functions that might be present in a C program. Each function in a program is called in the sequence specified by the function calls in

    main( ) . Function calling - followed by a semicolon

    argentina( ) ; Function definition - followed by a pair of braces

    void argentina(void ){

    statement ;

    ..statement ;}

    A function can call itself. Such a process is called recursion. A function can be called from other function, but a function cannot be defined in

    another function. There are basically two types of functions:

    Library functions Ex. printf( ) , scanf( ) etc.[compiler comes with a library of standard functions; eg stdio.h, math.h]

    User-defined functions Ex. argentina( ) , brazil( ) etc.

    General function calling and function definition

  • 8/2/2019 C Training Notes

    16/25

    16

    Type 1:accept nothing,return nothing

    Type 2:accept something,return nothing

    Type 1:accept nothing,return something

    Type 1:accept something,return something

  • 8/2/2019 C Training Notes

    17/25

    17

    function need to be declared before use (if typed after main ):

    void display ( int i ) ;

    void main( void )

    {int i = 20 ;display ( i ) ;

    }void display ( int i ){

    int k = 35 ; printf ( "%d\n", i ) ; printf ( "%d\n", k ) ;

    }

    scope of variable is within function:

    void goUK ( int Cathy ){

    int k = 35 ; printf ( "%d\n", Cathy ) ; printf ( "%d\n", k ) ;

    }void main( void ){

    int Khatijah = 20 ;goUK (Khatijah ) ;

    }

    example of call by values :

    void display ( int i ) ;

    void main( void ){

    int i = 20 ;

    display ( i ) ; printf ( In main i = %d\n", i ) ;}void display ( int i ){

    i = i + 1 ; printf ( In display i = %d\n", i ) ;

    }

  • 8/2/2019 C Training Notes

    18/25

  • 8/2/2019 C Training Notes

    19/25

    19

    - when we have the same data type , and we want to combine them

    example on array:

    //This program demonstrate the usual//DIS - Declare, Initialize and Show

    #include

    void main (void){

    //declare variablesint num1, num2, num3float Avg;

    //initializenum1 = 1; num2 = 2; num3 = 4;

    Avg = (num1 + num2 + num3) / 3.0;

    printf ("The numbers are :\n"); printf ("%d\n", num1);

    printf ("%d\n", num2); printf ("%d\n", num3);

    printf ("Average = %.2f\n", Avg);}

    //This program demonstrate the use of array//DIS - Declare, Initialize and Show

    #include

    void main (void){

    //declare arrayint num[3]; //num[0], num[1], and num[2]float Avg;

    //initialize arraynum[0] = 1; num[1] = 2; num[2] = 4;

    Avg = (num[0] + num[1] + num[2]) / 3.0;

    printf ("The numbers are :\n"); printf ("%d\n", num[0]);

    printf ("%d\n", num[1]); printf ("%d\n", num[2]);

    printf ("Average = %.2f\n", Avg);}

  • 8/2/2019 C Training Notes

    20/25

    20

    //This program demonstrate the use of array//DGS - Declare, Get (from user) and Show

    #include

    void main (void){

    int num[3];

    float Avg;

    printf ("Enter 3 numbers : ");scanf ("%d", &num[0]);scanf ("%d", &num[1]);scanf ("%d", &num[2]);

    Avg = (num[0] + num[1] + num[2]) / 3.0;

    printf ("The numbers are :\n"); printf ("%d\n", num[0]); printf ("%d\n", num[1]); printf ("%d\n", num[2]);

    printf ("Average = %.2f\n", Avg);}

    //This program demonstrate the use of array//Use 'for' loop and 'define'

    #include #define no 3

    void main (void){

    int num[no];

    int i, Sum;float Avg;

    //get input from user printf ("Enter %d numbers : ", no);for (i=0; i

  • 8/2/2019 C Training Notes

    21/25

    21

    - when we have the same data type (char) , and we want to combine them

    example on string:

    #include

    void main (void){

    char name[5] = {'A','h','m','a','d'};int i;

    for (i=0;i

  • 8/2/2019 C Training Notes

    22/25

    22

    #include

    void main (void){

    char name[5];int i, pos=0;

    printf("Enter your name : ");gets(name);

    printf("\nYour name is : "); puts(name);

    for (i=0;i

  • 8/2/2019 C Training Notes

    23/25

    23

    - when we have different data types , and we want to combine them

    look at this function later!

    void getAvgMath (struct score *student, float *Avg){

    int i, Sum;

    for (Sum=0, i=0; i

  • 8/2/2019 C Training Notes

    24/25

    24

    example of program using structure:

    #include struct score

    { char name[10];int Math;int Science;int English;

    };

    void main (void){

    int i;int Max, Min;

    float Avg;struct score student[4] = {

    "Amin", 55, 61, 86,"Aman", 48, 69, 76,"Azim", 88, 91, 77,"Azam", 78, 71, 56,

    };

    /* //get input from user for (i=0; i

  • 8/2/2019 C Training Notes

    25/25

    Quiz 3

    Create a structure to specify data of customers in a bank. The data should include;Account No, Name, Balance, Year Join

    Use the following information for your program:Account No Name Balance Year JoinC011 Dahlia bt Atan 200 2004D012 Abu bin Bakar 20 2005B013 Ramli bin Amin 145 2003D014 Fatimah bt Haris 35 2005D017 Wong Hong Kau 45 2005

    Write a function to print the Account number and name of each customer with balance below RM 50

    Example Output :

    ** Welcome to Bank of Wopuchitau **

    ** This utility lets you to list all customers with balance below certain value.

    ** Please enter the cutoff value: RM 50

    The customers with balance below RM 50:1. D012 Abu bin Bakar 202. D014 Fatimah bt Haris 353. D017 Wong Hong Kau 45