42
Introduction Objectives: At the end of this module, the student should be able to: 1. Enumerate the simple data types available in the C language; 2. Use arithmetic, logical and relational operators; and 3. Write simple programs that use input/output statements.

Introduction be able to: the C language; operators; and input/output …lagardemics.weebly.com/uploads/1/1/3/5/11356329/mod… ·  · 2012-03-17Introduction Objectives: At the end

Embed Size (px)

Citation preview

Introduction

Objectives:

At the end of this module, the student should be able to:

1. Enumerate the simple data types available inthe C language;

2. Use arithmetic, logical and relationaloperators; and

3. Write simple programs that useinput/output statements.

#include<stdio.h>

main()

{

printf("hello, world\n");

}

/*include information about

standard library*/

/*define a function called main

that received no argument values*/

/*statements of main are enclosed

in braces*/

/*main calls library function printf

to print this sequence of characters*/

/*\n represents the newline

character*/

In its simplest form, a C program has the following format:

<preprocessor commands>

<variable definitions>

main( )

{

<statements>

}

Preprocessor commands - instruct the compiler or translator) to do some tasks prior to the translation process.

In our sample program, the #include tells thecompiler to include the contents of the filestdio.h during compilation.

The stdio.h file contains information used by thestatements scanf and printf which are present inthe program. So whenever we use scanf or printf,we need to have the command #include<stdio.h> at the start of the program.

Variable definitions - specify the namedefinitions and data type of the variables used ina program.

Main function – contains statements that areexecuted by the computer in sequence.

- Our example had 1 statement (printf)

The symbols /* and */ found in the program are used to enclose comments. They don‟t affect the execution of the program, but they can make the program easier to understand.

variables - sometimes used as temporarystorage, when doing computations. Andwe also store our computation results invariables.

All variables must be properly definedbefore they can be used in program variablestatements.

To define a variable, we specify its nameand its data type.

A valid name (called an identifier) obeys the following rules:

1. It consists of letters (A-Z, a-z), digits (0-9), and underscore ( _ ).

2. It does not start with a digit.

3. It does not contain blank spaces.

Table 3.1 shows examples of valid and invalid identifiers in C.

INVALID VALID REMARKS

my salary My_salary No space allowed

1stday Firstday Should not start with a digit

cost&profits cost_profit & not allowed

Each variable has an associated data type which determines the type of values that can be stored in the variable.

The basic data types are:

int (integer), float (floating point, or real number), char (character), arrays, structures and pointers.

When defining variables, write the data type firstfollowed by variable names (separated by commas)assuming that type.

int x, y, X, num;int sum1, sum2;float gross, net, expenses;char ch;

Notice that names are case sensitive - variable x is different from variable X.

Variables can be distributed among several lines in any way you want. The definition above can also be written as:

int x, y, sum1;int X, num;int sum2;float gross, net;float expenses;char ch;

What is wrong with the following variable definitions?

float gradient, height, weight in lbs;float gpa;Integer 1st_exam, 2nd_exam;

A: The identifier weight in lbs is an invalidvariable name because spaces are notallowed. Also, 1st_exam and 2nd_exam areinvalid because names should not start with adigit. Lastly, integer should be int.

Arithmetic OperatorsC provides the following arithmetic operators:+ addition- subtraction* multiplication/ division% modulo

The modulo (%) operation computes theremainder of an integer division.

For example,

7 % 3 is 1 because 7 divided by 3 is 2 remainder 1.

11 % 3 is 2 because 11 divided by 3 is 3 remainder 2.

The binary operators + and - have the same priority, which is lower than *, / and %.

Operators of the same priority are evaluated from left to right.

Thus, 2+5*10-6*2 is 40 because we performmultiplication first before addition and subtraction.

Parentheses are used in the same way that we usethem in calculators.

The arithmetic expression (2+5)*((10-6)*2) evaluates to 56.

The division operator (/), behaves differentlyfrom the normal division operator when thedivisor is an integer. It performs integerdivision.

For example, 7/2.0 is 3.5, but 7/2 is 3.

And 21/4.0 is 5.25, but 21/4 is 5.

Q:Give the value of each expression below: a. 10-1+2*3 b. 11%4*3+5 c. (5-8/3)*2+12%5

A: a. 10-1+2*3 = 10 – 1 + 6 = 15 b. 11%4*3+5 = 3 * 3 + 5 = 9 + 5 = 14 c. (5-8/3)*2+12%5

= (5- 8/3 ) * 2 + 2= 3 * 2 + 2= 6 + 2= 8

Remember, *, / and % have the same priorities. In an expression, operators having the same priorities are evaluated from left to right.

Assignment Operator

- To store a value in a variable, we use theequal sign, =, called the assignmentoperator.

A statement that assigns a value to a variableis called an assignment statement and hasthe format

<variable> = <expression>;

An expression is a combination of values,operators, and variables, just like (9*6)+2.

In an assignment statement, the expression isevaluated and its value stored in the variable onthe left hand side.

Examples of assignment statement.x = (2+5)*((10-6)*2);y = 21;gross = 11200.90;ch = „a‟;

In C, it‟s possible to assign a value to avariable during the variable definition.

For example,

int z = 21;

defines z as an integer variable and sets it to21. This is a convenient way to initializevariables.

Another feature of the C language is that an assignment operation may appear within an expression. It evaluates to the value being assigned.

For example, if x is 5,

num = x + (y = 3);

sets y to 3, adds 3 to the value of x which is 5, and stores the result (8) to num.

So actually, we have here an assignment statementwithin another assignment statement.

In C programs, it‟s common to see statements like:

num = x = y = 0; It sets num, x and y to zero.

While the computer converts data types automatically whennecessary, we can actually “force” the conversion process to takeplace.

This is called explicit type conversion and is done with a unaryoperator called a type cast.

The format of a type cast is:

(<data type>) <expression>

The type cast causes the value of expression to be converted to data type.

For example,(float) (10+2)evaluates to a floating point number, 12.0.

Type casts are useful in cases like divisions dealing with an integer divisor.

To effectively divide a number, say 100, with an integer variable, say x, we can use a type cast on the divisor:

100/(float) x

Note that simply writing 100/x causes an integer division.

C provides an easy way to increment and decrementvariables through the use of two operators, ++ and --.

The ++ operator adds 1 to the value of a variable, whilethe decrement operator -- subtracts 1.

For example,x++;y--; increments the value of x and decrements the value of y, respectively.

In this example, we used ++ and -- as a postfix operator. We can also use it as a prefix operator++x;--y; The effect is the same: x is incremented and y is decremented.

There is a difference when the operator is usedinside an expression.x++ evaluates to x and then causes x toincrement, while ++x causes x to increment firstand evaluates to that incremented value.

To illustrate this, if x is 4, thennum = x++; sets num to 4, butnum = ++x; sets num to 5.

In both cases, x increments to 5.

Suppose x is 7 and y is 3. Then,

num = x++ * (8 + --y);sets num to 70, x to 8 and y to 2.

Relational operators are operators used tocompare numerical values.

In C, the relational operators are:> greater than>= greater than or equal< less than<= less than or equal== equal to!= not equal to

The operators >, >=, <, and <= have the same priority, which is higher than == and !=.

All relational operators have lower priority than arithmetic operators.

Thus, x>2+3 is taken as x>(2+3).

A relational expression evaluates to either true or false.

In C, a true has a numerical value of 1, and a false has a numerical value of 0

A statement like

x = 6 > 4;

is a valid statement and it assigns the value 1 to theinteger variable x because 6 > 4 is true.

Relational expressions may be combined using the following logical operators:

&& and|| or! not

The priority of || is lower than that of &&, whose priority islower than that of !.

All logical operators have lower priority than relational operators.

Thus,x > 0 || x > y && net == 0means(x > 0) || ((x>y) && (net == 0)).

Relational expressions are frequently used inselection and iteration statements.

In C, there are a number of input and output statements that may be used. We will discuss two here: printf and scanf.

printf is used to output values.

It has the format:

printf(<format string>,<item>,<item>, ...);

where :<format string> is made up of a combinationof ordinary characters and format commands

<item>s are optional variables orexpressions that match up with formatcommands in the format string.

A format command specifies the data type ofthe variable or expression to be outputted,and its placement within the format stringindicates where the value appears within theoutput.

Suppose x is 10 and y is 3. Then, the statement:

printf(“%d divided by %d is %f.\n”, x, y, x/(float) y);

outputs:10 divided by 3 is 3.333333

In the printf statement above, the format string,“%d divided by %d is %f.\n” specifies the outputand consists of three format commands:two %d‟s and one %f.

These three format commands correspondrespectively to the three items appearing afterthe format string: x, y, and x/(float) y.

When the output is actually written, each formatcommand is replaced by the value of thecorresponding item.

A %d denotes an integer (d stands for decimal)value, and a %f denotes a floating point value.

The first two format commands are %d, becausethe first two items, x and y, are integer variables!The third format command is %f because thethird item is a floating point value.

There is another format command that you mightuse: %c for characters.

The „\n‟ that appears at the end of the format string is a special character called a newline which is similar to a carriage return.

Placing it at the end of the format string causes the next output to appear on the next line.

It can, however, be placed in the middle of the format string, likeprintf(“%d divided\n by %d is %f.”, x, y, x/(float) y);

which produces the output10 dividedby 3 is 3.333333

Below are more examples of the printf statement.int x = 10, y = 3;float r = 12.5;char ch = „A‟;

printf(“Pay me $%f\n”,r);printf(“Pay me $%d\n”,x);printf(“%d Pay me $\n”,x);printf(“I have %d and %d.\n”,x,y);printf(“I have %d, and %d.\n”,y,x);printf(“I have 15 and %d\n”,x);printf(“%c %d-minute break\n”,ch,x);printf(“%d-minutebreak %c\n”,x,ch);

The output of the program is

Pay me $12.500000Pay me $1010 Pay me $I have 10 and 3.I have 3 and 10.I have 15 and 10A 10-minute break10-minutebreak A

C allows you to specify in the format command %f thenumber of digits to use. We can specify the total numberof digits to be used, and the number of fractional digits.

This is best illustrated by an example. The statement

printf(“Pay me $%6.2f\n”, r);

specifies that the value of r is to be outputted at least 6characters wide, with 2 fractional digits.

This gives the outputPay me $ 12.50

Note that an extra space is placed after the dollar signbecause the value should occupy 6 characters as specified.

Let‟s have more examples. The statements

printf(“Pay me $%6.3f\n”, r);printf(“Pay me $%6.2f\n”, r);printf(“Pay me $%6.1f\n”, r);printf(“Pay me $%5.2f\n”, r);printf(“Pay me $%5.1f\n”, r);printf(“Pay me $%5.0f\n”, r);

produces the following output:

Pay me $12.500Pay me $ 12.50Pay me $ 12.5Pay me $12.50Pay me $ 12.5Pay me $ 12

scanf is used to input values. It has the sameformat,

scanf(<format string>,<item>,<item>, ...);

Where: <format string> is made up of formatcommands and<item>s are variables that match up withformat commands in the format string.

The format string specifies how the input isread, and the input values are stored in thevariables.

For example, the statement:

scanf(“%d %f”, &x, &r);

expects an input of 2 numbers separated by a space.

The first number is an integer and will be stored invariable x,

The second number is a floating point and will bestored in variable r.

Have you noticed the ampersand (&) before eachvariable? The reason why we placed & is a bitcomplicated to explain at this point, and we willdiscuss it later. In the meantime, let‟s just have it as arule that in scanf we should place an & before eachvariable.

Consider another example,

scanf(“u%d, v%d”, &x, &y);

expects an input of two numbers separatedby a comma and a space (or a tab or anewline).

In addition, the first number should bepreceded by a letter u and the second by aletter v.

A valid input for this is u10, v20

When reading an input, it‟s always a goodidea to output a message, called a “prompt”,before the scanf statement to indicate to theuser of the program that an input has to bemade.

This prompt is usually a printf statement that outputs something like “Enter an integer: ” or “Input two numbers separated by a comma: ”.

A prompt makes a program user-friendly. Itmakes the user aware that an input has to bemade.

Simple C program consists of preprocessorcommands, variable definitions, and the mainfunction.

Preprocessor commands instruct the compiler toperform some tasks before translating the program tomachine language.

The variable definitions list the variables used in theprogram along with their corresponding data types.

The main function contains program statements thatare sequentially executed by the computer.

A variable used in the program needs to bedefined first by specifying its name and datatype.

The simple data types include int, float, and char.

To store a value in a variable, the assignmentoperator is used.

The C language also provides a rich set of otheroperators that may be used in computations.

The operators are classified as: arithmetic,logical, relational and increment/decrement.

Two commonly used input/output statements are scanf and printf.

The scanf statement is used to input data into avariable, while printf is used to output thecontent of a variable.