The Essentials of C Programs - Class 3

Embed Size (px)

Citation preview

  • 8/8/2019 The Essentials of C Programs - Class 3

    1/29

    THE ESSENTIALS OF CPROGRAMS

  • 8/8/2019 The Essentials of C Programs - Class 3

    2/29

    essentials within a C program

    Constants and variables

    Expressions

    Statements Statement blocks

    C function types and names

    Arguments to functions

    The body of a function

    Function calls

  • 8/8/2019 The Essentials of C Programs - Class 3

    3/29

    The Basics of the C Program

    C program is made of basic elements, such as

    expressions,

    statements,

    statement blocks,

    and function blocks.

  • 8/8/2019 The Essentials of C Programs - Class 3

    4/29

    Constants and Variables

    As its name implies, a constant is a value that never changes. Avariable, on the other hand, can be used to present different values.

    You can think of a constant as a music CD-ROM; the music saved inthe CD-ROM is never changed. A variable is more like an audiocassette: You can always update the contents of the cassette bysimply overwriting the old songs with new ones.

    i = 1; where the symbol 1 is a constant because it always has thesame value (1), and the symbol i is assigned the constant 1. In otherwords, i contains the value of 1 after the statement is executed.Later, if there is another statement,

    i = 10; after it is executed, i is assigned the value of 10. Because ican contain different values, it's called a variable in the C language.

  • 8/8/2019 The Essentials of C Programs - Class 3

    5/29

    Expressions

    An expression is a combination of constants, variables, andoperators that are used to denote computations.

    For instance, the following:

    (2 + 3) * 10 is an expression that adds 2 and 3 first, andthen multiplies the result of the addition by 10. (The finalresult of the expression is 50.)

    Here are some other examples of expressions:

    Expression Description 6

    An expression of a constant. i An expression of a variable.

    6 + i An expression of a constant plus a variable.

    exit(0) An expression of a function call.

  • 8/8/2019 The Essentials of C Programs - Class 3

    6/29

    Statements

    In the C language, a statement is a complete instruction, ending witha semicolon. In many cases, you can turn an expression into astatement by simply adding a semicolon at the end of theexpression.

    For instance, the following

    i = 1; is a statement. You may have already figured out that thestatement consists of an expression of i = 1 and a semicolon (;).

    Here are some other examples of statements:

    i = (2 + 3) * 10; i = 2 + 3 * 10; j = 6 % 4; k = i + j;

    you learned statements such as

    return 0;

    exit(0);

    printf ("Howdy, neighbor! This is my first C program.\n");

  • 8/8/2019 The Essentials of C Programs - Class 3

    7/29

    Statement Blocks

    A group of statements can form a statement block that starts with anopening brace ({) and ends with a closing brace (}). A statementblock is treated as a single statement by the C compiler.

    For instance, the following for(. . .)

    {

    s3 = s1 + s2;

    mul = s3 * c;

    remainder = sum % c;

    }

    is a statement block that starts with { and ends with }. Here for is akeyword in C that determines the statement block. The for keywordis, "Doing the Same Thing Over and Over."

    A statement block provides a way to group one or more statementstogether as a single statement.

  • 8/8/2019 The Essentials of C Programs - Class 3

    8/29

    Anatomy of a C Function

    Functions are the building blocks of C programs.Besides the standard C library functions, you canalso use some other functions made by you or

    another programmer in your C program. a function consists of six parts:

    the function type,

    the function name,

    arguments to the function, the opening brace,

    the function body,

    and the closing

  • 8/8/2019 The Essentials of C Programs - Class 3

    9/29

    Determining a Function's Type

    The function type is used to signify what type ofvalue a function is going to return after itsexecution.

    the default function type of main() is integer

    In C, int is used as the keyword for the integer datatype.

  • 8/8/2019 The Essentials of C Programs - Class 3

    10/29

  • 8/8/2019 The Essentials of C Programs - Class 3

    11/29

    Arguments to C Functions

    You often need to pass a function some information before executingit. For example, a character string, "Howdy, neighbor! This is my firstC program.\n", is passed to the printf() function, and then printf()prints the string on the screen.

    Pieces of information passed to functions are known as arguments.The argument of a function is placed between the parentheses thatimmediately follow the function name.

    The number of arguments to a function is determined by the task ofthe function. If a function needs more than one argument, argumentspassed to the function must be separated by commas; thesearguments are considered an argument list.

    If no information needs to be passed to a function, you just leave theargument field between the parentheses blank. For instance, themain() function has no argument, so the field between theparentheses following the function name is empty.

  • 8/8/2019 The Essentials of C Programs - Class 3

    12/29

    The Beginning and End of a Function

    braces are used to mark the beginning and end ofa function. The opening brace ({) signifies the startof a function body, while the closing brace (}) marks

    the end of the function body.

    the braces are also used to mark the beginning

    and end of a statement block. You can think of it as

    a natural extension to use braces with functionsbecause a function body can contain severalstatements.

  • 8/8/2019 The Essentials of C Programs - Class 3

    13/29

    The Function Body

    the place that contains variable declarations and Cstatements. The task of a function is accomplished byexecuting the statements inside the function body one at atime.

    1: /* This function adds two integers and returns the result*/

    2: int integer_add( int x, int y )

    3: {

    4: int result;

    5: result = x + y;

    6: return result;

    7: }

  • 8/8/2019 The Essentials of C Programs - Class 3

    14/29

    ANALYSIS

    line 1 is a comment

    In line 2, you see that the int data type is prefixed prior to the functionname. Here int is used as the function type, which signifies that an integershould be returned by the function.

    The function name shown in line 2 is integer_add.

    The argument list contains two arguments, int x and int y, in line 2, where theint data type specifies that the two arguments are both integers.

    Line 4 contains the opening brace ({) that marks the start of the function.

    The function body is in lines 4_6.

    Line 4 gives the variable declaration of result, whose value is specified by

    the int data type as an integer. The statement in line 5 adds the two integers represented by x and y and

    assigns the computation result to the result variable. The return statement inline 6 then returns the computation result represented by result.

    Last, but not least, the closing brace (}) in line 7 is used to close the function.

  • 8/8/2019 The Essentials of C Programs - Class 3

    15/29

  • 8/8/2019 The Essentials of C Programs - Class 3

    16/29

    Making Function Calls

    Based on what you've learned so far, you can writea C program that calls the integer_add() function tocalculate an addition and then print out the result on

    the screen

  • 8/8/2019 The Essentials of C Programs - Class 3

    17/29

    #include

    int integer_add( int x, int y )

    {

    int result;

    result = x + y;

    return result;

    }

    int main()

    {

    int sum;

    sum = integer_add( 5, 12); printf("The addition of 5 and 12 is %d.\n", sum);

    return 0;

    }

  • 8/8/2019 The Essentials of C Programs - Class 3

    18/29

  • 8/8/2019 The Essentials of C Programs - Class 3

    19/29

    Data Types and Names in C

    Learn naming a variable and the C keywordsreserved by the C compiler in this hour.

    Learn four data types of the C language in detail:

    char data type

    int data type

    float data type

    double data type

  • 8/8/2019 The Essentials of C Programs - Class 3

    20/29

    C Keywords

    The C language reserves certain words that havespecial meanings to the language. TYou should notuse the C keywords as variable, constant, or function

    names in your program.

    The following are the 32 reserved C keywords:

  • 8/8/2019 The Essentials of C Programs - Class 3

    21/29

  • 8/8/2019 The Essentials of C Programs - Class 3

    22/29

    The char Data Type

    An object of the char data type represents a single character of thecharacter set used by your computer. For example, A is a character,and so is a. But 7 is a number.

    But a computer can only store numeric code. Therefore, characterssuch as A, a, B, b, and so on all have a unique numeric code that isused by computers to represent the characters. Usually, a charactertakes 8 bits (that is, 1 byte) to store its numeric code.

    For many computers, the ASCII codes are the de facto standardcodes to represent a character set. (ASCII, just for your information,stands for American Standard Code for Information Interchange.)The original ASCII character set has only 128 characters because ituses the lower 7 bits that can represent 27 (that is, 128) characters.

  • 8/8/2019 The Essentials of C Programs - Class 3

    23/29

    Character Variables

    A variable that can represent different characters iscalled a character variable.

    You can set the data type of a variable to char byusing the following declaration format: char variablename; where variablename is the place where you put the name of

    a variable.

    If you have more than one variable to declare, you can

    either use the following format: char variablename1; char variablename2; charvariablename3;

    char variablename1, variablename2, variablename3;

  • 8/8/2019 The Essentials of C Programs - Class 3

    24/29

    Character Constants

    A character enclosed in single quotes (`) is called a characterconstant. For instance, `A', `a', `B', and `b' are all character constantsthat have their unique numeric values in the ASCII character set.

    You can remember to use the single quote (`), instead of the doublequote ("), in character constants because a character constantrepresents a single character.

    From the ASCII character set you will find that the unique numeric(decimal) values of `A', `a', `B', and `b' are 65, 97, 66, and 98,respectively. Therefore, given x as a character variable, for instance,the following two assignment statements are equivalent:

    x = `A'; x =65; So are the following two statements:

    x = `a'; x = 97;

  • 8/8/2019 The Essentials of C Programs - Class 3

    25/29

    The Escape Character (\)

    you learned to use the newline character (\n) to break a messageinto two pieces.

    In the C language, the backslash (\) is called the escape character;it tells the computer that a special character follows.

    For instance, when the computer sees \ in the newline character \n, itknows that the next character, n, causes a sequence of a carriagereturn and a line feed.

    Besides the newline character, several other special characters existin the C language, such as the following:

    Character Description

    \b The backspace character; moves the cursor to the left one character. \f The form-feed character; goes to the top of a new page.

    \r The return character; returns to the beginning of the current line.

    \t The tab character; advances to the next tab stop.

  • 8/8/2019 The Essentials of C Programs - Class 3

    26/29

    Printing Out Characters

    You already know that the printf() function, definedin the C header file stdio.h, can be used to print outmessages on the screen.

    In this section, you're going to learn to use thecharacter format specifier, %c, which indicates to

    the printf() function that the argument to be printedis a character.

  • 8/8/2019 The Essentials of C Programs - Class 3

    27/29

  • 8/8/2019 The Essentials of C Programs - Class 3

    28/29

    As you know, line 2 includes the header file, stdio.h, for theprintf() function.

    Lines 5_14 make up the main() function body.

    Lines 6 and 7 declare two character variables, c1 and c2,

    while lines 9 and 10 assign c1 and c2 with the characterconstants `A' and `a', respectively.

    Note that the %c format specifier is used in the printf()function in lines 11 and 12, which tells the computer that thecontents contained by c1 and c2 should be printed as

    characters. When the two statements in lines 11 and 12 areexecuted, two characters are formatted and output to thescreen, based on the numeric values contained by c1 and c2,respectively.

  • 8/8/2019 The Essentials of C Programs - Class 3

    29/29

    Mini Homework

    Write a C function that can multiply two integersand return the calculated result.

    Write a C program that calls the C function you just

    wrote in exercise 4 to calculate the multiplication of3 times 5 and then print out the return value from

    the function on the screen.