a first c program /* print a message */ #include main() { printf("this is a test!\n"); }...

21
A First C Program /* Print a Message */ #include <stdio.h> main() { printf("This is a test!\n"); } e program is compiled and run as cc pg32.c a.out This is a test!

Upload: aubrey-gardner

Post on 03-Jan-2016

222 views

Category:

Documents


1 download

TRANSCRIPT

A First C Program

/* Print a Message */

#include <stdio.h>main(){ printf("This is a test!\n");}

The program is compiled and run as

cc pg32.c a.out

This is a test!

Computing Distance/*

This program repeatedly reads a time in hours, computesthe distance traveled in that time assuming a rate of 14kilometers per hour, and writes the distance to the videodisplay. It is assumed that the time is a positive integer. Theprogram is terminated by entering zero. The distance iscomputed using the formula

d = r * twhere d is the distance, r is the rate, and t is the time.*/

#include <stdio.h>main(){ int distance, rate, time;

rate = 14; printf("Enter next time: "); scanf("%d", &time);

while(time > 0) { distance = rate * time; printf("Time = %d hours\n", time); printf("Distance=%d kilometers\n\n", distance); printf("Enter next time: "); scanf("%d", &time); } printf("*** END OF PROGRAM ***\n");}

This is pg34.c

Identifiers

• Identifier is the official word for name of a variable in C program.

• It must start with a letter (A through Z or a through z).

• It must consist of only letters (A to Z, a to z), digits (0 to 9), and the underscore _.

• It must not be a keyword, such as int, or while.

Legal identifiers

totaltotal_cars_sumcolumn3TOTAL

Illegal identifiers

total$2nd_sumlongsecond sumTOTAL-CARS

The while Statement

while ( expression ) action

While( ) {

}

expression

statement

NOYES

START

Expressiontrue?

·

·

Expression/Action

• An expression consists of variables and operators of valid combinations. E.g.,

x > 0, y == 0, or just x.

• An action is a statement ending with a semicolon “;”, or several statements enclosed in braces. E.g.,

{ x = 1; printf("x=%d\n", x); x = x + 1; }

Relational Operators

> Greater than

>= Greater than or equal

< Less than

<= Less than or equal

== Equal

!= Not equal

While(), Example

int x;x = 0;while ( x != 2) x = x + 1;printf("x = %d.\n", x);

The statement

x = 0;

sets x to 0. Since 0 is not equal to 2, x != 2 evaluates to true;

x = x + 1;

is executed, making x equal 1. We return to the top of while condition. x now is 1 not equal to 2. So x is increased to 2. Now x != 2 is false. The loop terminates. The printf prints out

x = 2.

Exercise (DO IT NOW)

What is the output?

int x;x = 7;while( x >= 0 ) { printf("%d\n", x); x = x - 2;}

The do while() Statement

do action while ( expression );

do {

} while ( );

NOYES

···

expression true?

expression

Do-While Example

Do { printf("Enter a " "positive integer: "); scanf("%d", &response);} while (response <= 0);

Check for the validity of user input (must be positive). If the input is invalid, the user is prompted again to enter a value.

Exercise (DO IT NOW)

What is printed?

int x;x = 4;do { x = x - 2; printf("x = %d\n", x);} while ( x >= 1);

Real World ApplicationClassifying solutions as acidic or nonacidic

/* This program reads molar concentrations until end-of-file. Foreach molar concentration mc, it computes the corresponding pHusing the formula

pH = - log10(mc).It then reports whether the solution is acidic (pH < 7) or nonacidic.

*/

#include <stdio.h>#include <math.h>

main(){ float mc, ph;

while( scanf("%f", &mc) != EOF ) { ph = - log10(mc); printf("\nMolar concentration = %e\n", mc); printf("pH = %f\n", ph); if (ph < 7.0) printf("Acidic\n"); else printf("Nonacidic\n"); }} This is pg45.c

Standard Mathematics Functions

abs Absolute value of anint

floor Floor

acos Arccosine labs Absolute value ofa long

asin Arcsine log Natural log

atan Arctangent log10 Log base 10

atof Convert string todouble

pow X raised to powery

atoi Convert string to int rand Generate a randomnumber

atol Convert string tolong

sin Sine

ceil Ceiling sinh Hyperbolic sine

cos Cosine sqrt Square root

cosh Hyperbolic cosine srand Seed the randomnumber generator

exp Exponential ex tan Tangent

fabs Absolute value of adoul ble

tahnh Hyperbolic tangent

FIGURE 2.6, page 46.

The If Statement

If ( expression ) action

NOYES

START

If( ){expression

Expression true?

···

}

If, Example

Int code;code = 1;if ( code == 1 ) printf("CZ Courses\n");printf("*** THE END ***");

the output is

CZ Courses*** THE END ***

If code is set to 0, the first line will not be printed.

If, Example 2Int code;code = 1;if ( code == 1 ) { printf("CZ Courses\n"); printf("Dr Wang\n"); printf("Room 07-21\n");}printf("*** THE END ***");

the output is

CZ CoursesDr WangRoom 07-21*** THE END ***

If code is set to 0, the first three lines will not be printed.

If-else Statement

If ( expression ) action 1else action 2

If-else, ExampleInt code;code = 1;if ( code == 1 ) printf("CZ Courses\n");else printf("MA Courses\n");printf("*** THE END ***");

the output is

CZ Courses*** THE END ***

If code is set to 0 or any value otherthan 1, the output becomes:

MA Courses*** THE END ***

Exercise (DO IT NOW)

What is the output?

int x, y;x = 3;y = 5;if ( x < 2) printf("%d\n", x);else printf("%d\n", y);

Summary

• The structure of a C program

• Declare variables with int and float

• printf and scanf for displaying and reading data

• Looping by while and do-while statements

• if and if-else statements for choices

• Forming conditions with ==, !=, <, <=, >, >=

• Mathematical functions log10( ), sin( ), ...

Reading/Home Working

• Read Chapter 2, Pages 32 to 55.

• Work on Problems– Section 2.3, exercise 1, 3, 5, 7,

9.– Section 2.4, exercise 3, 5.– Section 2.7, exercise 3, 5.– Section 2.8, exercise 1.

• Check your answers in the back of the textbook. Do not hand in.