Fundamentals of C Structure of a C Program 1 Our First Simple - - PDF document

fundamentals of c structure of a c program
SMART_READER_LITE
LIVE PREVIEW

Fundamentals of C Structure of a C Program 1 Our First Simple - - PDF document

Fundamentals of C Structure of a C Program 1 Our First Simple Program Comments - Different Modes 2 Comments - Rules Preprocessor Directives Preprocessor directives start with # e.g. #include copies a file into the source code before


slide-1
SLIDE 1

1

Fundamentals of C Structure of a C Program

slide-2
SLIDE 2

2

Our First Simple Program Comments - Different Modes

slide-3
SLIDE 3

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

slide-4
SLIDE 4

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 Linking NO 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 this void main(void) int main( )

slide-5
SLIDE 5

5

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

Back To Our First Program

slide-6
SLIDE 6

6

Variables

A 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

slide-7
SLIDE 7

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 11001010 10010100 00100111

So a variable takes a fixed number of bytes in memory

slide-8
SLIDE 8

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

$sum 2names stdnt number int a student_name salary time_of_day Illegal Legal

slide-9
SLIDE 9

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 void void C-Implementation Data Type

slide-10
SLIDE 10

10

Variables : Declaration

Variables : Initialization How 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);

slide-11
SLIDE 11

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 character Symbolic Name ASCII Character

slide-12
SLIDE 12

12

Special Characters

’\\’ Backslash ’\”’ Double Quote ’\’’ Single quote ’\r’ Carriage return ’\f’ Form Feed Symbolic Name ASCII Character

Strings : Constants

slide-13
SLIDE 13

13

Preprocessing : #define Defines 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
slide-14
SLIDE 14

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

slide-15
SLIDE 15

15

To OUTPUT you require

#include <stdio.h>

printf(format string, data list);

Field specifiers are inside the format string i.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; }

slide-16
SLIDE 16

16

What happened?

The statements int a = 57; a 57 int 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:

%Lf long double f L %f double f none %f float f none %Ld long int d l or L %d int d none %hd short int d h %c char c none Example Type Code Size

slide-17
SLIDE 17

17

Specification of Width

12345 12345 12345 1234 1234 1234 123 123 123 12 12 12 %4d %d Value

Precision specification for floats:

%7.2f /* this prints the float in a field

  • f seven characters with two

characters after decimal: nnnn.dd */

slide-18
SLIDE 18

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; }

slide-19
SLIDE 19

19

The output

the number of months is 9 the 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

slide-20
SLIDE 20

20

Standard scanf Statements

scanf(format string, address list);

scanf(“%d%f”, &age, &weight); At keyboard type 23 60.75

Result: weight age 23 60.75

Field Specifiers

%<flag><maximum width><size>code Remember : There is no precision issue here !!!

Codes:

%Lf long double f L %f double f none %f float f none %Ld long int d l or L %d int d none %hd short int d h %c char c none Example Type Code Size

slide-21
SLIDE 21

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 reached ii. Maximum characters are processed

  • iii. A whitespace character is found after a digit
  • iv. An error is detected
slide-22
SLIDE 22

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 */

slide-23
SLIDE 23

23

Working with the variables:

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

An Expression: rateOfPay*hours – tax

Operators

e.g., + plus

  • minus

* multiply / divide % mod You create expressions out of operators.

slide-24
SLIDE 24

24

Some Expressions

35 2 * 3 + 4 23 + b * 6

  • salary

Use parenthesis to clarify complicated expressions: (food + drinks)*(1+gst+pst)

Assignment

Assignment expressions evaluate to the expression on the right of the assignment operator.

slide-25
SLIDE 25

25

Simple Assignment

x=1 1 x=y%4 5 10 x=2 2 x=x/y 5 10 x = 7 7 x=y+2 5 10 Result of Expression Value of Expression Expression Contents 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 11 1*2 + 3*5 answer 17

  • 5*6+2 answer -28
slide-26
SLIDE 26

26

Operators precedence (on the same level they are equal)

  • 1. ( ) takes precedence
  • 2. unary minus -7 unary plus +3
  • 3. * Multiply / Divide

4 % Modulus

  • 5. + 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) */
slide-27
SLIDE 27

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

  • 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
slide-28
SLIDE 28

28

Unary Expressions

9 9

  • -x

10 11 11 ++x 10 Contents of x After Value of Expression Expression Contents 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 */

slide-29
SLIDE 29

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 Operators

Often 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 ;

slide-30
SLIDE 30

30

Compound Assignment

x = 0 x %= y 5 10 x = 15 15 x += y 5 10 x = 5 5 x -= y 5 10 x = 2 2 x /= y 5 10 x = 50 50 x *= y 5 10 Result of Expression Value of Expression Expression Contents 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); }

slide-31
SLIDE 31

31

A Simple Program

The OUTPUT >Please input two real numbers: 23.4 45.6 x= 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; }

slide-32
SLIDE 32

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 drink PST = 0.08 GST =0.06 Tax = subtotal (PST+GST) Total = subtotal + tax

slide-33
SLIDE 33

33

/* A simple program calculate restaurant bill: input: food and drink amounts

  • utput: subtotal, tax, total bill*/

#include <stdio.h> #define PST 0.08 #define GST 0.06 int 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”

slide-34
SLIDE 34

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)