3 Fundamentals of C part1 - Carleton...

34
1 Fundamentals of C Structure of a C Program

Transcript of 3 Fundamentals of C part1 - Carleton...

Page 1: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

1

Fundamentals of C

Structure of a C Program

Page 2: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

2

Our First Simple Program

Comments - Different Modes

Page 3: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

3

Comments - Rules

Preprocessor Directives

Preprocessor directives start with #e.g. #include copies a file into the source code

before compilation

2 forms…..we will usually see the first#include <systemFilename>#include “undefinedFilename”Within “ ” : personal file in your own directory

Page 4: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

4

We will almost always use #include <stdio.h>

• stdio.h is the standard input/output header• Contains code required for I/O (Input/Output)• .h files are header files

Includes header ; The .obj part on LinkingNO code is generally included except on linking

• Header files contain definitions

The function : main()

ALL Programs must have a main() function.

Later we will have add other functions.Different Formats:main( )int main (void ) ***The book likes thisvoid main(void)int main( )

Page 5: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

5

main( ) , void main(void)End with return;

**************************int main (void ) , int main( )End with return 0;

Back To Our First Program

Page 6: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

6

VariablesA Variable is a block of memory that stores data.

A variable has a particular “Type”, i.e. it stores a particular kind of data

A variable is named with an appropriate Identifier (or Name)

Suppose we have a variable declared as follows:

int number_of_days

This reserves a block of memory which holds an integer

Page 7: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

7

Schematic view:

number_of_days

In the course of the program we might want to change the value in the variable. So that later we might want:

number_of_days

365

7361

• The “actual” view of memory: 4 bytes

number_of_days 01100000 110010101001010000100111

So a variable takes a fixed number of bytes in memory

Page 8: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

8

Rules for Naming Variables

1. First character: alphabetic or underscore

2. Consist only of alphanumeric or underscores

3. Only first 31 characters count

4. Cannot duplicate a reserved word

Legal/Illegal Variable Names

Use meaningful names

$sum2namesstdnt numberint

astudent_namesalarytime_of_day

IllegalLegal

Page 9: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

9

Standard C Data Types

Primitive C Data Types

float (4 bytes)double (8 bytes)long double (10 bytes)

floating point

short int (1 or 2 byte)int (2 or 4 bytes)long int (4 or 8 bytes)

unsigned short int (1 byte)unsigned int (2 or 4 bytes)unsigned long int (4 or 8 bytes)

integer

char (1 byte)character

voidvoid

C-ImplementationData Type

Page 10: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

10

Variables : Declaration

Variables : InitializationHow we put a value in a variable

• At compile time in the declaration:

e.g. int x=5;

• At run time by an assignment:

e.g. x =5;

• At run time by an input statement:

e.g.scanf(“%d”,&x);

Page 11: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

11

No variable is initialized until you do so!

You can initialize a variable in the declaration

char code = ‘B’;char letter = ‘B’;int i = 0;int age = 65;float pie = 3.1415;float salary 27.57;double variable2 = 3.1415926535;

Special Characters

’\v’Vertical Tab

’\n’Newline

’\t’Horizontal tab

’\b’Backspace

’\a’Alert (bell)

’\0’Null characterSymbolic NameASCII Character

Page 12: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

12

Special Characters

’\\’Backslash

’\”’Double Quote

’\’’Single quote

’\r’Carriage return

’\f’Form FeedSymbolic NameASCII Character

Strings : Constants

Page 13: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

13

Preprocessing : #defineDefines constants

#define name token

Replaces the name with the token

Example:#define PI 3.1415926535#define SIZE 1000

Syntax for Define : #define

• No equals sign

• No semicolon at the end

Page 14: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

14

Constants

To define a constant define a “variable” (usually, U.C.)with keyword:const

This is how it works:const float PI = 3.1415926;

This does NOT work:const float PI;PI = 3.1415926; /* not allowed to change it */

May be collected into a header file for general use

Standard Input and Output

Page 15: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

15

To OUTPUT you require

#include <stdio.h>

printf(format string, data list);

Field specifiers are inside the format stringi.e. Controls how the data looks when printed

Standard printf statements#include <stdio.h>void main( )/* This codes prints the values of two variables */

{ int a = 57;int b = 145;

printf( "%d\n%d\n", a,b);return;

}

Page 16: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

16

What happened?The statementsint a = 57; a 57int b = 145; b 145

The statement

printf( "%d\n%d\n", a , b);

prints: 57

145

Field Specifiers%<flag><minimum width><precision><size>code

Codes:

%Lflong doublefL%fdoublefnone%ffloatfnone

%Ldlong intdl or L%dintdnone%hdshort intdh%ccharcnone

ExampleTypeCodeSize

Page 17: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

17

Specification of Width

123451234512345

1234 12341234

123 123123

12 1212

%4d%dValue

Precision specification for floats:

%7.2f

/* this prints the float in a field of seven characters with two characters after decimal: nnnn.dd */

Page 18: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

18

Another Example of printf#include <stdio.h>int main()/* This codes prints the values of two variables */

{ int months = 9;float salary = 145.35;printf( "%d\n%7.2f\n", months , salary);return 0;

}

Another Example of printf#include <stdio.h>int main( )/* This codes prints the values of two variables */{ int months = 9;

float salary = 145.35;printf( "the number of months is%4d\nthe salary is%7.2f\n", months,salary);return 0;

}

Page 19: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

19

The output

the number of months is 9the salary is 145.35

Input: Getting information into memory: (reading)

Requires: #include <stdio.h>

scanf(format string, address list);

Again : Field specifiers inside the format string

Page 20: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

20

Standard scanf Statements

scanf(format string, address list);

scanf(“%d%f”, &age, &weight);

At keyboard type 23 60.75

Result: weightage 23

60.75

Field Specifiers%<flag><maximum width><size>codeRemember : There is no precision issue here !!!

Codes:

%Lflong doublefL%fdoublefnone%ffloatfnone

%Ldlong intdl or L%dintdnone%hdshort intdh%ccharcnone

ExampleTypeCodeSize

Page 21: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

21

Rules for scanf formats

Addresses of a variable are specified with:&variableName

A variety of rules apply to conversion

Rules for scanf formats

1. Initial whitespace is ignored (except %c)2. The conversion operation process until:

i. End of file is reachedii. Maximum characters are processediii. A whitespace character is found after a digitiv. An error is detected

Page 22: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

22

Rules for scanf format strings

1. A field specifier for each variable

2. Other characters must be exactly matched

3. Cannot end format string with whitespace

Examples of scanf

scanf(“%d%d%d%c”,&a,&b,&c,&d);

scanf(“%d%d%d %c”,&a,&b,&c,&d);

scanf(“%-8d%-8d%d”,&a,&b,&c);%-8d /* left justify flag */

Page 23: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

23

Working with the variables:

We want to operate on variables: e.g add two variables or subtract them.

An Expression: rateOfPay*hours – tax

Operatorse.g., + plus

- minus * multiply/ divide% mod

You create expressions out of operators.

Page 24: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

24

Some Expressions352 * 3 + 423 + b * 6-salary

Use parenthesis to clarify complicated expressions:

(food + drinks)*(1+gst+pst)

AssignmentAssignment expressions evaluate to the expression on

the right of the assignment operator.

Page 25: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

25

Simple Assignment

x=11x=y%4510

x=22x=x/y510

x = 77x=y+2510

Result of Expression

Value of Expression

ExpressionContents of Variable y

Contents of Variable x

Operator Precedence

Operators have a built in order of precedence which is over ridden by using parenthesis

1+2*3+4 answer 111*2 + 3*5 answer 17-5*6+2 answer -28

Page 26: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

26

Operators precedence (on the same level they are

equal)

1. ( ) takes precedence2. unary minus -7 unary plus +3 3. * Multiply / Divide 4 % Modulus5. + add - subtract

Examples Operators• Examples of C statements using these :• The following is a program fragment only• int i, j ,k, l, m;• i = j + k; • i = j + k * l / m; • /* Here i gets the value j + (k*l/m) */• i = j * k + l * m • /* Here i gets the value (j*k) + (l*m) */

Page 27: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

27

Examples Operators

• Examples of C statements using these :• There is one division operator for integer

and float but it means different things.• 2 / 5 → 0• 2.0 / 5.0 → 0.4• % is the modulus (remainder) operation• 5 % 2 → 1• 2 % 5 → 2

Unary operator + and -

+a – evaluates to the contents of a

-a – evaluates to the negative contents of a

Page 28: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

28

Unary Expressions

99--x10

1111++x10

Contents of x After

Value of Expression

ExpressionContents of x Before

Unary operator ++ and --

Post-increment and decrement i++ i--

/*First use the value ; then do operation*/

Pre-increment and decrement ++i --i

/*First do operation; then use the value */

Page 29: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

29

Unary operator ++ and --Examples for int i , j , k;• i=1;• i++; /* i → 2 */• j = i++ ; /*j → 2 and then i → 3• j =++i ; /* i → 4 and then j → 4• j = i-- /* j → 4 and then i → 3• Note that i++ and i=i+1 are equivalent• Note that i-- and i=i-1 are equivalent

Binary Compound OperatorsOften a variable is changed as follows :• i = i + 5; /* Take the value of i add 5 and

put the result back into the variable i*/.Leads to new assignment operators

+= -= *= /= %=• i = i + 1; same as i += 1;• j = j * k; same as j *= k ;

Page 30: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

30

Compound Assignment

x = 00x %= y510

x = 1515x += y510

x = 55x -= y510

x = 22x /= y510

x = 5050x *= y510

Result of Expression

Value of Expression

ExpressionContents of Variable y

Contents of Variable x

A Simple Program#include <stdio.h>int main( void ) {

double x, y,z ;printf("Pls. input two real numbers:\n") ;scanf("%f%f",&x,&y);z = x + y;printf("x=%6.2f y=%6.2f z= %6.3f \n",x,y,z);

return(0);}

Page 31: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

31

A Simple ProgramThe OUTPUT>Please input two real numbers:23.4 45.6x= 23.40 y= 45.60 z=69.000

/* A simple program to average 3 numbers*/#include <stdio.h>int main(void){ float number1,number2,number3,sum,average;

printf("\n Please enter number1. ");scanf("%f",&number1);printf("\n Please enter number2. ");scanf("%f",&number2);printf("\n Please enter number3. ");scanf("%f",&number3);sum = number1+number2+number3;average = sum/3.0;printf("\nthe sum of %f %f and %f is= %f",number1,number2,number3, sum);printf("\nthe average is = %f\n",average);return 0;

}

Page 32: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

32

Whats the problem with the previous program?

What if you wanted to average 50 numbers?

It would be very clumsy to repeat 50 times.

Also you have to change the program each time you have a different number of numbers.

Program to calculate tax on a bill

First you have to know the facts.Subtotal = food and drinkPST = 0.08GST =0.06Tax = subtotal (PST+GST)Total = subtotal + tax

Page 33: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

33

/* A simple program calculate restaurant bill: input: food and drink amountsoutput: subtotal, tax, total bill*/

#include <stdio.h>#define PST 0.08#define GST 0.06int main(void) {

float food,drink,sum,total,tax;printf("\n Please enter food total. ");scanf("%f",&food);printf("\n Please enter drink total. ");scanf("%f",&drink);sum = food + drink;tax = sum*(GST +PST);total= sum+tax;printf("\nthe food total is $%6.2f ",food);printf("\nthe drink total is $%6.2f ",drink);printf("\n =====");printf("\nthe subtotal is $%6.2f ",sum);printf("\nthe tax is $%6.2f ",tax);printf("\n =====");printf("\nthe total is $%6.2f\n\n ",total);return 0;

}

Whats the problem with the previous program?

The rule is not right. If the subtotal is less than $3.00 the no GST

So we need decision possibility

So we need “CONTROL STRUCTURES”

Page 34: 3 Fundamentals of C part1 - Carleton Universitypeople.scs.carleton.ca/~sbtajali/1002/slides/3_Fundamentals_of_C.pdf · %-8d /* left justify flag */ 23 Working with the variables:

34

Unary Operator sizeof

sizeof is an operator. It is NOT a function

Evaluates to number of bytes for that item

sizeof(int)sizeof(x)sizeof(3.256)