+ All Categories
Home > Documents > Printf_Scanf (1).pdf

Printf_Scanf (1).pdf

Date post: 14-Apr-2018
Category:
Upload: louie-de-la-torre
View: 216 times
Download: 0 times
Share this document with a friend

of 27

Transcript
  • 7/27/2019 Printf_Scanf (1).pdf

    1/27

    Introduction to C Programming

    A very simple C program#include main(){

    printf("Programming in C is easy.");

    }Output:Programming in C is easy._

    A very simple C program#include main() { printf("Programming in C is easy."); }Still the Output is :Programming in C is easy._

    For readability, we indent our code:#include

    main(){printf("Programming in C is easy.");

    }

    C Program in detailRemember: In C, lowercase and uppercase characters are very important! All commands in

    C must be lowercase.#include - This is a preprocessor directive (or compiler directive or header file)- All preprocessor directive starts with a # symbol

    - This line tells the compiler to include or insert a copy of header file stdio.h- The stdio.h file (standard input-output) tells C how to perform or execute input and outputfunctions

    - Other example of header file: ctype.h, stdlib.h, string.h, math.h etc.

    More on header file#include #include "mydecls.h

    The use of angle brackets informs the compiler to search the compilers include directoryfor the specified file.

    The use of the double quotes "" around the filename inform the compiler to search in thecurrent directory for the specified file.

    C program in detailmain( )- It is the name of the function- Every C program has a main( ) function where execution begins. The C programs starting

    point is identified by this word- The parentheses following main indicate that it is a function.- All function names have a ( )

    1

  • 7/27/2019 Printf_Scanf (1).pdf

    2/27

    Introduction to C Programming

    { and }- The left brace indicates the start of a function- The right brace denotes the end of a function- The braces group statements or instructions togetherprintf("Programming in C is easy.");

    - This is some of the built in function in C- The purpose of this is to print something on the computer screen- Notice that this line ends with a semicolon. All statements in C end with a semicolon."Programming in C is easy.- A string constant in C is a series of characters sorrounded by double quotes. This string is

    an argument to the function printf( ).- Arguments are values that are passed to a function at the time it is called. Some functions

    may have several arguments. (commas separate multiple arguments)

    More about printf( )Syntax: printf([text]);

    where [text] signifies any literal string that you want to display on the screen.Example:#include main(){

    printf(I can I really can...");}Output:I can I really can_

    More Examples

    printf(It is not what you say...");printf(It is how you say it);Output:It is not what you sayIt is how you say it_

    printf(It is not what);printf( you say...");printf(It is how);printf( you say it);Output:It is not what you sayIt is how you say it_Note: eventhough we have two or more statements of printf( ) we still have a single line of

    output. Thats why we need a second syntax of printf( ).

    More about printf( )Syntax: printf([text][escape sequences]);where [escape sequences] signifies a character combinations consisting of a backslash (\)

    followed by a letter or by a combination of digits.

    2

  • 7/27/2019 Printf_Scanf (1).pdf

    3/27

    Introduction to C Programming

    Uses of escape sequence- To represent a new line character, single and double quotations mark or certain characterprintf(Its not what you say...");Output: ERROR

    printf(It\s not what you say);Output: Its not what you say_

    An escape sequence is regarded as a single character and is therefore valid as a characterconstant.

    Escape SequencesEscape sequences are typically used to specify actions such as carriage returns and tab

    movements on terminals and printers. They also provide literal representations ofnonprinting characters and characters that usually have special meanings, such as thedouble quotation mark ().

    \a Bell(alert) \ Double quotation mark

    \b Backspace \\ Backslash\f Formfeed\n New Line\r Carriage return\t Horizontal tab\v Vertical tab\ Single quotation mark

    More Examples#include main()

    {

    printf("Programming in C is easy.\n");printf("And so is Pascal.\n");}

    Output:Programming in C is easy.And so is Pascal.

    _More Examples#include

    main(){

    printf("The black dog was big. ");printf("The cow jumped over the moon.\n");

    }Output:

    The black dog was big. The cow jumped over the moon.

    3

  • 7/27/2019 Printf_Scanf (1).pdf

    4/27

    Introduction to C Programming

    More Examples#include

    main(){

    printf("Hello...\n..oh my\n...when do i stop?\n");

    }Output:Hello.....oh my...when do i stop?

    _

    More Examples#include

    main(){

    printf(\aI want to \n break\tfree...");}Output:

    I want tobreakfree_

    Note: Before the statement will be displayed, you will hear a short beep sound coming fromthe PC Speaker.

    More Examples#include

    main()

    { printf(\tI want to\nbreak\nfree...");}

    Output:I want tobreakfree_

    More Examples#include

    main(){

    printf(I want to bre\nak fr\n\tee...");}

    Output:I want to break free..._

    4

  • 7/27/2019 Printf_Scanf (1).pdf

    5/27

    Introduction to C Programming

    C Data TypesINTEGER - These are whole numbers, both positive and negative. Unsigned integers

    (positive values only) are supported. In addition, there are short and long integers.The keyword used to define integers is, intAn example of an integer value is 20. An example of declaring an integer variable called sum

    is, int sum;sum = 20;

    Variables of type int can hold integer quantities that do not require fractional componentssuch as 0, 12, 135, and -24. int variables can usually hold integer numbers between -32,768 to 32,767.

    FLOATING POINT - These are numbers which contain fractional parts, both positive andnegative.

    The keyword used to define float variables is, floatAn example of a float value is 0.12. An example of declaring a float variable called money is,

    float money;money = 0.12;Variables of type float are for numbers with a fractional component (floating-point numbers)

    or for numbers with very large values such as 12.34, -0.5, 9,456,776, and 87.45 x 1023.float variables can usually hold real numbers between 3.4 x 10-38 to 3.4 x 1038.

    DOUBLE - These are exponential numbers, both positive and negative.The keyword used to define double variables is, doubleAn example of a double value is 3.0E2. An example of declaring a double variable called big

    is,double big;

    big = 3.0E+2;Variables of type double are similar to float variables but can hold a wider range of numbers.double variables can have numbers whose values range from 1.7 x 10-308 to 1.7 x 10308.

    CHARACTER - These are single characters.The keyword used to define character variables is, charAn example of a character value is the letter A. An example of declaring a character variable

    called letter is,char letter;letter = 'A';

    Note the assignment of the character A to the variable letter is done by enclosing the value insingle quotes. Remember the golden rule: Single character - Use single quotes.

    Variables of type char hold 8-bit ASCII characters such as A, B, C, or any other 8-bitquantity.

    5

  • 7/27/2019 Printf_Scanf (1).pdf

    6/27

    Introduction to C Programming

    Example#include < stdio.h >

    main(){int sum;

    float money;char letter;double pi;sum = 10; /* assign integer value */money = 2.21; /* assign float value */letter = 'A'; /* assign character value */pi = 2.01E6; /* assign a double value */printf("value of sum = %d\n", sum );

    printf("value of money = %f\n", money );printf("value of letter = %c\n", letter );printf("value of pi = %e\n", pi );

    }

    Sample program outputvalue of sum = 10value of money = 2.210000value of letter = Avalue of pi = 2.010000e+06

    Another Example#include main()

    { int gross, net, cost;gross = 100;cost = 10;net = gross - cost;printf(If the gross income is %d\n, gross);printf( and the cost of materials is %d,\n, cost);printf( then the net income is %d.\n, net);}

    OutputIf the gross is 100

    and the cost of materials is 10,then the net income is 90._

    SOME C ARITHMETIC OPERATORS1. Addition (+)

    Example: sum = num1 + num2;2. Subtraction (-)

    Example: diff = num 10;

    6

  • 7/27/2019 Printf_Scanf (1).pdf

    7/27

    Introduction to C Programming

    3. Multiplication (*)Example: product = 20 * num;

    4. Division (/)Example: quotient = num / 43;

    5. Modulus (%)

    yields the remainder of a division processExample: rem = 5 % 2;the variable rem will be equal to 1

    More Format Specifiers%c forcharvariables or constants%d forint variables or constants%f forfloat variables or constants%lf fordouble variables or constants%e similar to %fexcept that the output is in scientific notation.%g same as %for%e whichever is shorter.

    Another Example#include

    main(){float x, y, sum;x = 1.5;y = 2.0;sum = x + y;printf(The sum of x and y is %f.\n, sum);

    }

    The sum of x and y is 3.500000.Other Features of the printf() Functionprintf(%c%c%c\n,a,b,c);printf(%c%3c%7c\n,a,b,c);Output:abca**b******c*->spaceNote: The number between % and c represents the field width.

    printf(% .1f% .2f% .3f\n,1.0,2.0,3.0);printf(%7.1f%7.2f%7.3f\n,4.0,5.0,6.0);Output:1.02.003.000****4.0***5.00**6.000*->spaceNote: The number between % and . represents the field width. The number between . and f

    represents the number of decimal places

    7

  • 7/27/2019 Printf_Scanf (1).pdf

    8/27

    Introduction to C Programming

    Another Example#include

    main(){float x, y, sum;

    x = 1.5;y = 2.0;sum = x + y;printf(The sum of x and y is %.2f., sum);

    }

    The sum of x and y is 3.50._

    Another Example#include

    main()

    { char sample;sample = M;printf(The letter is %c., sample);

    }

    The letter is M._

    Another Example#include

    main()

    { int num1, num2;num1 = 5;num2 = 3;printf(The product of 5 times 3 is %d., num1*num2);

    }

    The product of 5 times 3 is 15._

    Another Example#include

    main(){int a, b;float ans;a=10;b=2;ans=a/b;printf(%d divided by %d is %f., a, b, ans);

    }10 divided by 2 is 5.000000._

    8

  • 7/27/2019 Printf_Scanf (1).pdf

    9/27

    Introduction to C Programming

    INITIALIZING DATA VARIABLES AT DECLARATION TIMEUnlike PASCAL, in C variables may be initialized with a value when they are declared.

    Consider the following declaration, which declares an integer variable count which isinitialized to 10.

    int count = 10;

    THE VALUE OF VARIABLES AT DECLARATION TIME#include main(){

    int count;char letter;

    printf("Count = %d\n", count);printf("Letter = %c", letter);

    }

    Sample program outputCount = 26494Letter = f_

    NOTE:It can be seen from the sample output that the values which each of the variables take on atdeclaration time are no-zero. In C, this is common, and programmers must ensure thatvariables are assigned values before using them.

    If the program was run again, the output could well have different values for each of thevariables. We can never assume that variables declare in the manner above will take on aspecific value.

    Some compilers may issue warnings related to the use of variables, and Turbo C fromBorland issues the following warning, possible use of 'count' before definition in functionmain

    RADIX CHANGINGData numbers may be expressed in any base by simply altering the modifier, e.g., decimal,

    octal, or hexadecimal. This is achieved by the letter which follows the % sign related to theprintf argument.

    #include main() /* Prints the same value in Decimal, Hex and Octal */{

    int number = 100;printf("In decimal the number is %d\n", number);printf("In hex the number is %x\n", number);printf("In octal the number is %o\n", number);

    }

    9

  • 7/27/2019 Printf_Scanf (1).pdf

    10/27

    Introduction to C Programming

    Sample program outputIn decimal the number is 100In hex the number is 64In octal the number is 144

    _

    Note how the variable number is initialized to zero at the time of its declaration.

    DEFINING VARIABLES IN OCTAL AND HEXADECIMALOften, when writing systems programs, the programmer needs to use a different number

    base rather than the default decimal.Integer constants can be defined in octal or hex by using the associated prefix, e.g., to define

    an integer as an octal constant use 0 (zero)int sum = 0567;

    To define an integer as a hex constant use 0x (zero followed by x or X)int sum = 0x7ab4;int flag = 0x7AB4; /* Note upper or lowercase hex ok */

    SPECIAL NOTE ABOUT DATA TYPE CONVERSIONConsider the following program,#include main(){int value1 = 12, value2 = 5;

    float answer = 0;answer = value1 / value2;

    printf("The value of %d divided by %d is %f.",value1,value2,answer );}

    Sample program outputThe value of 12 divided by 5 is 2.000000.

    Even though the above declaration seems to work, it is not always 100% reliable. Note howanswer does not contain a proper fractional part (ie, all zero's).

    To ensure that the correct result always occurs, the data type of value1 and value2 should beconverted to a float type before assigning to the float variable answer. The following changeillustrates how this can be done,

    answer = (float)value1 / (float)value2;

    PREPROCESSOR STATEMENTSThe define statement is used to make programs more readable. Consider the following

    examples,#define TRUE 1 /* Don't use a semi-colon , # must be first character on line */#define FALSE 0#define NULL 0

    10

  • 7/27/2019 Printf_Scanf (1).pdf

    11/27

    Introduction to C Programming

    #define AND define OR |#define EQUALS ==

    Note that preprocessor statements begin with a # symbol, and are NOT terminated by a

    semi-colon. Traditionally, preprocessor statements are listed at the beginning of the sourcefile.Preprocessor statements are handled by the compiler (or preprocessor) before the program

    is actually compiled. All #statements are processed first, and the symbols (like TRUE) which occur in the C program

    are replaced by their value (like 1). Once this substitution has taken place by thepreprocessor, the program is then compiled.

    In general, preprocessor constants are written in UPPERCASE.

    ExampleUse pre-processor statements to replace the following constants

    0.312W37

    answer:#define SMALLVALUE 0.312#define LETTER 'W'#define SMALLINT 37

    LITERAL SUBSTITUTION OF SYMBOLIC CONSTANTS USING #define

    Lets now examine a few examples of using these symbolic constants in our programs.Consider the following program which defines a constant called TAX_RATE.#include #define TAX_RATE 0.10main(){

    float balance;float tax;balance = 72.10;tax = balance * TAX_RATE;printf("The tax on %.2f is %.2f\n", balance, tax );

    }NOTE: The pre-processor first replaces all symbolic constants before the program is

    compiled, so after preprocessing the file (and before its compiled), it >

    YOU CANNOT ASSIGN VALUES TO THE SYMBOLIC CONSTANTSConsidering the above program as an example, look at the changes we have made below.

    We have added a statement which tries to change the TAX_RATE to a new value.

    11

  • 7/27/2019 Printf_Scanf (1).pdf

    12/27

    Introduction to C Programming

    #include #define TAX_RATE 0.10main(){

    float balance;

    float tax;balance = 72.10;TAX_RATE = 0.15;tax = balance * TAX_RATE;printf("The tax on %.2f is %.2f\n", balance, tax );

    }NOTE: This is illegal. You cannot re-assign a new value to a symbolic constant.

    ITS LITERAL SUBSTITUTION, SO BEWARE OF ERRORSAs shown above, the preprocessor performs literal substitution of symbolic constants. Lets

    modify the previous program slightly, and introduce an error to highlight a problem.

    #include #define TAX_RATE 0.10;main(){float balance;float tax;balance = 72.10;

    tax = (balance * TAX_RATE )+ 10.02;printf("The tax on %.2f is %.2f\n", balance, tax );

    }

    MAKING PROGRAMS EASY TO MAINTAIN BY USING #defineThe whole point of using #define in your programs is to make them easier to read and modify.

    Considering the above programs as examples, what changes would you need to make ifthe TAX_RATE was changed to 20%.

    Obviously, the answer is once, where the #define statement which declares the symbolicconstant and its value occurs. You would change it to read

    #define TAX_RATE = 0.20

    Without the use of symbolic constants, you would hard code the value 0.20 in your program,and this might occur several times (or tens of times).

    This would make changes difficult, because you would need to search and replace everyoccurrence in the program. However, as the programs get larger, what would happen ifyou actually used the value 0.20 in a calculation that had nothing to do with theTAX_RATE!

    12

  • 7/27/2019 Printf_Scanf (1).pdf

    13/27

    Introduction to C Programming

    SUMMARY OF #define

    allow the use of symbolic constants in programsin general, symbols are written in uppercaseare not terminated with a semi-colongenerally occur at the beginning of the file

    each occurrence of the symbol is replaced by its valuemakes programs readable and easy to maintain

    Practice1. Declare an integer called sum2. Declare a character called letter3. Define a constant called TRUE which has a value of 14. Declare a variable called money which can be used to hold currency5. Declare a variable called arctan which will hold scientific notation values (+e)6. Declare an integer variable called total and initialise it to zero.7. Declare a variable called loop, which can hold an integer value.

    8. Define a constant called GST with a value of .125

    CommentsThe addition of comments inside programs is desirable. These may be added to C programs

    by enclosing them as follows,

    /* bla bla bla bla bla bla */

    Note that the /* opens the comment field and */ closes the comment field. Comments mayspan multiple lines. Comments may not be nested one inside another.

    /* this is a comment. /* this comment is inside */ wrong */

    In the above example, the first occurrence of */ closes the comment statement for the entireline, meaning that the text wrong is interpreted as a C statement or variable, and in thisexample, generates an error.

    What Comments Are Used For copyrighting

    documentation of variables and their usageexplaining difficult sections of codedescribes the program, author, date, modification changes, revisions etc

    Basic Structure of C ProgramsC programs are essentially constructed in the following manner, as a number of well defined

    sections./* HEADER SECTION *//* Contains name, author, revision number*//* INCLUDE SECTION *//* contains #include statements *//* CONSTANTS AND TYPES SECTION *//* contains types and #defines */

    13

  • 7/27/2019 Printf_Scanf (1).pdf

    14/27

    Introduction to C Programming

    /* GLOBAL VARIABLES SECTION *//* any global variables declared here *//* FUNCTIONS SECTION *//* user defined functions *//* main() SECTION */

    Adhering to a well defined structured layout will make your programs

    easy to readeasy to modifyconsistent in formatself documenting

    Keyboard InputThere is a function in C which allows the programmer to accept input from a keyboard.It is generally useful to be able to enter data into a program once it is running. This function

    is called scanf().

    The purpose of the scanf() function is to print input data to a program. If printf() is forformatted output then scanf() is for reading formatted input.The most important difference between printf() and scanf(), apart from the fact that one

    displays data while the other reads/accepts it, is that scanf() requires the memory addressof the variables into which it ultimately stores the data it reads.

    The location or address of the operator my be obtained with the address operator (&)

    Examplescanf(%d, &sum);This statement causes the program to pause and wait for the user to input data at the

    keyboard. Once the user types in a number, that number is then stored or placed in

    variable sum.

    The format %d in this example causes the program to interpret the input characters as adecimal integer.

    The ampersand symbol (&) should always be present right before the name of the variablewhere the input data is to be stored.

    In using the printf() function remember the following:- Specify the correct format specifier %- Dont forget to include the & with each subsequent argument

    14

  • 7/27/2019 Printf_Scanf (1).pdf

    15/27

    Introduction to C Programming

    Another Example#include main(){float dollars, pesos;

    printf (Enter the no. of dollars you want to convert : );scanf (%f, &dollars);pesos = dollars * 41.95;printf (\n\n$ %.2f is equal to %.2f pesos., dollars, pesos);}

    Sample Output:Enter the no. of dollars you want to convert : 3.55

    _$ 3.55 is equal to 148.92 pesos._

    Another Example#include main(){float radius, area, pi = 3.14;printf (Enter the radius of the circle: );scanf (%f, &radius);area = pi * radius * radius;printf (\n\nThe area of the circle is %.2f., area);}

    Sample Output:Enter the radius of the circle: 2.0_The area of the circle is 12.56._

    Another Example#include main(){char fst, mid, lst;int age;

    printf (Enter your three initials and age: );scanf (%c%c%c%d, &fst, &mid, &lst, &age);printf (\n\nGreetings %c.%c.%c. Next year your age willbe %d., fst, mid, lst, age + 1);}Sample Output:Enter your three initials and age: VGM21

    _Greetings V.G.M. Next year your age will be 22._

    15

  • 7/27/2019 Printf_Scanf (1).pdf

    16/27

    Introduction to C Programming

    Points to remember

    This program illustrates several important points.the c language provides no error checking for user input. The user is expected to enterthe correct data type. For instance, if a user entered a character when an integer valuewas expected, the program may enter an infinite loop or abort abnormally.

    its up to the programmer to validate data for correct type and range of values.

    Practice1. Use a printf statement to print out the value of the integer variable sum2. Use a printf statement to print out the text string "Welcome", followed by a newline.3. Use a printf statement to print out the character variable letter4. Use a printf statement to print out the float variable discount5. Use a printf statement to print out the float variable dump using two decimal places6. Use a scanf statement to read a decimal value from the keyboard, into the integer variable

    sum7. Use a scanf statement to read a float variable into the variable discount_rate

    8. Use a scanf statement to read a single character from the keyboard into the variableoperator. Skip leading blanks, tabs and newline characters.

    C-LANGUAGE CHARACTER SET

    Among the characters that a programmer can use are the following:

    lowercase letters : a b c ... z uppercase letters : A B C ... Z digits : 0 1 2 ... 9 other characters : * / = ( ) { } < > ! @ # $ % & _ | ^ ~ \ . , ; : ? white space characters such as blank, newline, and tab These characters are collected by the compiler into syntactic units called tokens.

    C Identifiers

    C-Language defines the names that are used to reference variables, functions, labels, andvarious other user-defined objects as identifiers.

    Identifiers can also be called as variable name, function name, label name which are allprogrammer supplied name.

    Rules in forming identifiers An identifier can vary from one to several characters (256). The first character must always be a letter or an underscore ( _ ) with subsequent

    characters being letters, numbers, or underscores. Remember that C is case sensitive (uppercase letters are different from lowercase

    letters). Therefore, the identifierTax_rate is different from tax_rate.

    16

  • 7/27/2019 Printf_Scanf (1).pdf

    17/27

    Introduction to C Programming

    More on IdentifiersThe following is a list of valid variable names:

    summary exit_flag iNumber_of_moves _valid_flag Jerry7

    You should ensure that you use meaningful names for your variables. The reasons for thisare, meaningful names for variables are self documenting (see what they do at a glance)

    they are easier to understand there is no correlation with the amount of space used in the .EXE file makes programs easier to read

    C will only recognize a certain number of characters in identifiers. The exact numberdepends on the computer system being used.

    Example:

    Turbo C running on an IBM PC or compatible will recognize the first 32 characters of anidentifier. This means that if two identifiers are identical in the first 32 characters butdifferent in subsequent characters, Turbo C will not be able to tell them apart. The variablenames are the same as far as Turbo C is concerned.

    this_is_a_very_long_variable_namethis_is_a_very_long_variable_name_1

    Keywords

    The following are examples of keywords in C that should never be used as identifiers:

    auto double int structbreak else long switchcase enum register typedefchar extern return unionconst float short unsignedcontinue for signed voiddefault goto sizeof volatiledo if static while

    Practice1. value$sum

    2. final_grade3. _counter4. 1st_data5. high+low6. last*temperature7. exit flag8. 3lotsofmoney9. Char10. tax_rate

    17

  • 7/27/2019 Printf_Scanf (1).pdf

    18/27

    Introduction to C Programming

    What about Identif iers

    C provides the programmer with FOUR basic data types. User defined variables mustbe declared before they can be used in a program.

    Get into the habit of declaring variables using lowercase characters. Remember that C

    is case sensitive, so even though the two variables listed below have the same name,they are considered different variables in C.

    sumSum

    The declaration of variables is done after the opening brace of main(),

    Variable Declaration#include main()

    { int sum;sum = 500 + 15;printf("The sum of 500 and 15 is %d\n", sum);

    }

    Sample Program OutputThe sum of 500 and 15 is 515

    _

    It is possible to declare variables elsewhere in a program, but lets start simply and thenget into variations later on.

    Variable DeclarationThe basic format for declaring variables is

    data_type var, var, ... ;where data_type is one of the four basic types, an integer, character, float, or double type.

    The program declares the variable sum to be of type INTEGER (int). The variable sum is thenassigned the value of 500 + 15 by using the assignment operator, the = sign.sum = 500 + 15;

    Arithmetic Operators

    The symbols of the arithmetic operators are:Operation Operator Comment Value of Sum before Value of sum afterMultiply * sum = sum * 2; 4 8Divide / sum = sum / 2; 4 2Addition + sum = sum + 2; 4 6Subtraction - sum = sum -2; 4 2Increment ++ ++sum; 4 5Decrement -- --sum; 4 3Modulus % sum = sum % 3; 4 1

    18

  • 7/27/2019 Printf_Scanf (1).pdf

    19/27

    Introduction to C Programming

    The following code fragment adds the variables loop and count together, leaving the resultin the variable sum

    sum = loop + count;

    Printing % on the printf()

    Note: If the modulus % sign is needed to be displayed as part of a text string, use two, ie %%#include main(){

    int sum = 50;float modulus;modulus = sum % 10;printf("The %% of %d by 10 is %f\n", sum, modulus);

    }

    Sample Program Output

    The % of 50 by 10 is 0.000000_

    Practice1. Assign the value of the variable number1 to the variable total2. Assign the sum of the two variables loop_count and petrol_cost to the variable sum3. Divide the variable total by the value 10 and leave the result in the variable discount4. Assign the character W to the char variable letter5. Assign the result of dividing the integer variable sum by 3 into the float variable costing.

    Use type casting to ensure that the remainder is also held by the float variable.

    Increment Operator ( + + )The increment operator (++) is a unary operator that increments the contents of a variable by

    1. For example, the statement++ age;

    increments the contents of the variable age by 1. Ifage = 5, then ++age will make age = 6.In other words, ++age is the same as age = age + 1.

    The ++ operator can also be in the postfix notation. This means that age ++ will also havethe same effect as ++age

    Decrement Operator ( - - )The decrement operator (--) is a unary operator that decrements the contents of a variable by

    1. In other words, --age orage-- is the same age = age - 1.

    NOTE: Both the increment and decrement operators are not applicable to constants orordinary expressions. For example, --8 and ++(a + b) are not allowed.

    19

  • 7/27/2019 Printf_Scanf (1).pdf

    20/27

    Introduction to C Programming

    Prefix vs. Postfix

    The postfix and prefix notations of the increment and decrement operators differ whenused in expressions.

    a = ++age;

    Assume age = 5. After execution of this statement, a = 6 and age = 6. In other words, thevalue ofage is incremented first and then its value is assigned to variable a.

    a = age++;Assume age = 5. After execution of this statement, a = 5 and age = 6. In other words, the

    value ofage is assigned first to variable a and then its value is incremented.

    Example#include main(){

    int a, b, c, d;

    c = 1;d = 1;a = ++c;b = d++;printf (The value of a is %d and the value of c is %d.\n, a, c);printf (The value of b is %d and the value of d is %d.\n, b, d);

    }The output of the program is:

    The value of a is 2 and the value of c is 2.The value of b is 1 and the value of d is 2.

    Precedence and Associativity of Operators As in algebra, the arithmetic operators (+, -, *, /, and %) in C follow rules in precedence

    and associativity. These rules determine how evaluation of expressions should takeplace.

    The following summarizes the rules of precedence and associativity:Operators Associativi ty

    ( ) ++ (postfix) -- (postfix) left to right+ (unary) - (unary) ++ (prefix) -- (prefix) right to left* / % left to right+ - left to right

    = += -= *= /= etc. right to left

    Remember this!

    In the table above, all operators in the same line have equal precedence with respect toeach other, but have higher precedence than all operators that occur on the lines belowthem. The associativity rule for all operators on a given line appears on the right side ofthe table.

    20

  • 7/27/2019 Printf_Scanf (1).pdf

    21/27

    Introduction to C Programming

    Examplea) 2 * 5 + 5 * 3 + 4 * 10= 10 + 5 * 3 + 4 * 10= 10 + 15 + 4 * 10= 10 + 15 + 40

    = 25 + 40= 65

    b) 4 % 2 + 3 - 4 * 5= 0 + 3 - 4 * 5= 0 + 3 - 20= - 17

    c) 7 - - a * ++bwhere a = 2 and b = 4= 7 - (-2) * ++b

    = 7 - (-2) * (5)= 7 - (-10)= 7 + 10= 17

    Parentheses

    Parentheses change the rules of precedence and associativity. Expressions inparentheses have the highest precedence.

    Examples:1. 5 + 3 * 4 + 2

    = 5 + 12 + 2 = 17 + 2 = 19

    2. 5 + 3 * (4 + 2)= 5 + 3 * 6 = 5 + 18 = 233. (5 + 3) * (4 + 2)

    = 8 * (4 + 2) = 8 * 6 = 48

    Nested Parentheses

    In case of nested parentheses (parentheses within parentheses), the innermost set isevaluated first.

    Example:(1 + 7 * (3 + 8)) * (5 - 3)= (1 + 7 * 11) * (5 - 3)

    = (1 + 77) * (5 - 3)= 78 * (5 - 3)= 78 * 2= 156

    Performing Arithmetic Operations on Different Data TypesAny variable whose value is computed from at least one floating-point operand should

    generally be a floating-point variable.

    21

  • 7/27/2019 Printf_Scanf (1).pdf

    22/27

    Introduction to C Programming

    Example:x = 3.5 + 2 Variable x should be of type float ordouble.y = 2.7 * z Variable y should be of type float ordouble regardless on the type of variable z.

    Any variable whose value is computed from at least one division operation should be a

    floating-point variable.Example:x = y / z Variable x should be of type float.

    Intricacies of DivisionDivision between two integers yields either an integer or a floating-point number.Examples:y = 10 / 2 = 5 (integer)y = 11 / 2 = 5.5 (floating-point) In C, the division of two integers always results in an integer. The value obtained will

    be truncated, or rounded down to the largest whole number less than the result.

    Examples:y = 11 / 2 = 5y = 10 / 3 = 3y = 5 / 2 = 2

    Example#include

    main(){float a;a = 5/2;

    printf ("The value of a is %d.", a);}The output of this program is:

    The value of a is 0._

    Example#include

    main(){int a;a = 5/2;

    printf ("The value of a is %d.", a);}The output of this program is:

    The value of a is 2._

    22

  • 7/27/2019 Printf_Scanf (1).pdf

    23/27

    Introduction to C Programming

    Example#include main(){int a;

    a = 5/2;printf ("The value of a is %f.", a);}This program will not run (although it will compi le).The following error message will appear:

    printf: floating poin t formats not linkedAbnormal program terminat ion

    Example#include main(){

    float a;a = 5/2;printf ("The value of a is %f.", a);}

    The output of this program is:The value of a is 2.000000._

    Example#include main(){

    float a;a = 5.0/2;printf ("The value of a is %f.", a);}

    The output of this program is:The value of a is 2.500000._

    Programming Examples1. Write a C program that will input three integers (x, y, and z) and compute the value of

    variable a using the following formula:a = 3x + y

    z + 2Then print the value ofa on the screen.

    2. A Celsius (centigrade) temperature c can be converted to an equivalent Fahrenheittemperature faccording to the following formula:

    f = 9 c + 325

    Write a C program that will read in a Celsius temperature and output the equivalentFahrenheit temperature.

    23

  • 7/27/2019 Printf_Scanf (1).pdf

    24/27

    Introduction to C Programming

    The Assignment Operator

    Unlike other programming languages, C treats the equal sign (=) as an operator. Itsprecedence is lower than the other operators that were discussed so far and itsassociativity is from right to left.

    Examples:

    1. The program segment:a = 1;b = 2;c = a + b;

    is equivalent to: c = (a = 1) + (b = 2);2. The expression:

    a = b = c = 0;evaluates to: a = (b = (c = 0));

    The Combined Operators

    It is a very common assignment to add one variable to another

    Example:x = x + ygets the value ofx and y, add them together, then store the result in x.

    A combined operator of fers a shortcut for these k inds of express ions .x = x + y x += yx = x - y x -= yx = x * y x *= yx = x / y x /= yx = x % y x %= y

    Relational Operators A relational expression compares two values. If the relation or comparison is true, the

    expression has a value of 1 (or any nonzero value in some implementation). If false, theexpression has a value of 0.

    For example, the expression 5 < 1 is equal to 0 (false) while 3 > 2 is equal to 1 (true).

    < less than> greater than= greater than or equal

    x = -5, power = 1024, MAX_POW = 1024, y = 7, item = 1.5, MIN_ITEM = -999.0x = y x greater than or equal to y 0 (false)item > MIN_ITEM item greater than MIN_ITEM 1 (true)

    24

  • 7/27/2019 Printf_Scanf (1).pdf

    25/27

    Introduction to C Programming

    Precedence and Associativity of Relational OperatorsOperators Associativi ty

    ( ) ++ (postfix) -- (postfix) left to right+ (unary) - (unary) ++ (prefix) -- (prefix) right to left* / % left to right

    + - left to right< > = left to right= += -= *= /= etc. right to left

    Example:1) x - y < 0 is equivalent to (x - y) < 02) z >= w + 1 is equivalent to z >= (w + 1)3) a - b > c + d is equivalent to (a-b) > (c+d)

    ExamplesAssume that x = 5, y = 3, z = 10

    x + y < = z truez / x > y falsex + y >= z - y truey * z / x x * y false

    Equality Operators

    An equality expression compares whether two values are equal or not.

    = = equal! = not equal

    For example,2 = = 2 is 1 (true) while 2 != 2 is 0 (false)3 != 5 is 1 (true) while 3 = = 5 is 0 (false)

    mom_or_dad = M, num = 999, SENTINEL = 999mom_or_dad == M mom_or_dad equal to M 1 (true)num != SENTINEL num not equal to SENTINEL 0 (false)

    Precedence and Associativity of Equality OperatorsOperators Associativity

    ( ) ++ (postfix) -- (postfix) left to right+ (unary) - (unary) ++ (prefix) -- (prefix) right to left* / % left to right+ - left to right< > = left to right= = != left to right= += -= *= /= etc. right to left

    25

  • 7/27/2019 Printf_Scanf (1).pdf

    26/27

    Introduction to C Programming

    Example:p * q = = 0 is equivalent to (p * q) = = 0m != n - 7 is equivalent to m != (n - 7)a - b != c + d is equivalent to (a-b) != (c+d)

    Logical Operators Combining more than one condition These allow the testing of more than one condition as part of selection statements. Logical expressions involve Boolean operations.

    && and| | or! not

    (a < b) && (c > d)checks ifa is less than b AND ifc is greater than d

    (w = = x) || (y q.

    exp1 exp2 !exp1 !exp2 exp1&&exp2 exp1||exp20 0 1 1 0 00 1 1 0 0 11 0 0 1 0 11 1 0 0 1 1

    Precedence and Associativi ty of Logical OperatorsOperators Associativity( ) ++ (postfix) -- (postfix) left to right+ (unary) - (unary) ++ (prefix) -- (prefix) ! right to left* / % left to right+ - left to right< > = left to right= = != left to right&& left to right|| left to right= += -= *= /= etc. right to left

    ExamplesAssume that x = 6, y = 2, z = 20

    x < = z && x < y falsey = = z || x ! = z truex + 15 > z && !(y > z) true!(x > y) || y > z - 10 falsex > y || x = = z && y < z true!(x < z) && x >= y + 4 || z = = 19 false

    26

  • 7/27/2019 Printf_Scanf (1).pdf

    27/27

    Introduction to C Programming

    More on relational, equality, and logical expression

    It is possible to assign the result of a relational, equality, or logical expression to aninteger variable.

    Examples:Assume that x = 6, y = 2, z = 20 and a, b, c, d, e, and fare variables of type in t.

    a = x < = z && x < yb = y = = z || x ! = zc = x + 15 > z && !(y > z)d = !(x > y) || y > z - 10e = x > y || x = = z && y < zf = !(x < z) && x >= y + 4 || z = = 19Then:

    a = 0 d = 0b = 1 e = 1c = 1 f = 0

    Writing English Conditions in CEnglish Condition Logical Expressionsx and y are greater than z x>z && y>zx is equal to 1.0 or 3.0 x==1.0||x==3.0x is in the range of z to y, z


Recommended