Lecture Notes

Lecture Notes Assignments Syllabus Grading Policy Professor Malki

 

Lecture Notes
Assignments
Syllabus
Grading Policy
Professor Malki

 

Introduction to C Language

 

ELET 2300

 

Student’s Handout

 

WEEK 1 WEEK 2 WEEK 3 WEEK 4 WEEK 5 WEEK 6 WEEK 7
WEEK 8 WEEK 9 WEEK 10 WEEK 11 WEEK 12 WEEK 13 WEEK 14
WEEK 15 WEEK 16 TIME PERMITING GO BACK TO HOME PAGE

 

 

 

 

University of Houston

 

College of Technology

 

 

Dr. Heidar Malki

 

Fall 1997

 

 

 

 

 

 

 

 

 

 

 

WEEK ONE

Chapter 1

INTRODUCTION TO C

 

· Turbo C

- Command line system

- Integrated Development Environment or IDE

In this system all the necessary operations for the program development are available in unified

screen display with menus and windows.

· History of C

C is created by Dennis Ritchie of Bell labs in 1972. It came from Thompson’s B language.

· General features:

1) C is designed to work with hardware

 

2) C offers many programming shortcuts

· Advantages of C:

1) Design features

2) Efficiency

3) Portability

4) Power and flexibility

5) Programming orientation

6) Well structured

Potentially Disadvantageous

 

· Why use C

It provides the convenience of high level langauge such as BASIC or Pascal, while allowing the close control of a computer’s hardware and peripheral that assembly language does.

· What equipment you need to use

1) Hardware

 

- IBM PC, XT, AT or compatible or IBM PS/2 series

- Mainframe, UNIX system

 

2) Software

 

- Operating system: MS-DOS or PC-DOS

- UNIX system: vi or emacs editor

- Compiler for PC: Microsoft C/C++ or Turbo C/C++

for Mainframe: UNIX operating system

· How to use IDE

C:\>tc <cr>

- menu bar at the top with the words:

File, Edit, Run, Compile,... etc

- with 2 windows: Edit window (top)

Message window (bottom)

· How to create a program in the IDE

C:\tc program1.c <cr>

 

- You can start typing your program.

- Saving the program by pressing - F2 key.

- Compiling and linking the program by pressing - F9 key.

- In the Turbo C IDE, compiling and linking can be performed together in one step by pressing - F9

key.

During compiling, two more files will be generated

1) The compiler will transform the source file (program1.c) into an object file, program1.obj. This file contains machine language code that you need the start-up code to interface your program and the operating system.

2) The linker will combine the object code, the standard start-up code, and your library code into a single file, called the executable file. The resulting file will be called program1.exe

· Executing a program (RUN or ALT-R)

· Debugging a program

Once you compile a program, you may get either of these cases

- Errors

- Success

Once you have error message on the bottom of the window press any key, you will see edit window with your program, and one character (or the entire line) will be highlighted.

 

 

Steps of programming

1) Define the program objectives

2) Design the program

3) Write the code

4) Compile

5) Run the program

6) Test and debug the program

7) Maintain and modify the program.

 

 wpe12.gif (1355 bytes)Back to Top

 

WEEK TWO

Chapter 2

Basic structure of C programs

Ex:

#include <stdio.h>

void main(void)

{

printf("This is an example of a C program.\n");

}

Output:

This is an example of a C program.

 

Example:

/* simple.c */

#include <stdio.h>

void main (void)

{ int num; /* define a variable called num */

num = 1; /* assign a value to num */

printf("I am a simple "); /* use the printf() function */

printf("computer. \n");

printf("My favorite number is %d because ", num);

printf("it is first. \n");

}

Output:

I am a simple computer.

My favorite number is 1 because it is first.

 

1) Preprocessor #include <stdio.h>

Standard Input/Output header file. This should be the first line on any program which is part of the C compiler package. It contains information about input and output functions such as printf().

2) main()- function name

The new ANSI specifies if a function does not return any type (such as int or float), it should follow the following format:

void main (void)

3) /* .... */ - comment

4) { .... } - block of execution

{ - marks the beginning of the body of the function

} - marks the end of the body of the function

You can have more than one { or } in the program

5) int num; - declaration statement.

6) num = 1; - assignment statement.

7) printf("computer.\n"); \n tells the computer to start a new line.

printf(" My favorite number is %d because ",num);

printf(" it is first.\n ");

or you can combine them

printf(" My favorite number is %d because it is first.\n ", num);

Ex:

/* A Sample Program

Meant to illustrate the format of a C listing */

#include <stdio.h> /* Compiler directive */

void main(void) /* Beginning of function */

{ int quiz; /* Declaration of a variable */

quiz = 20; /* Assignment */

/* Displays on screen */

printf("A perfect quiz is %i points.\n", quiz);

printf("Will I get perfect scores?\n");

}

Output:

A perfect quiz is 20 points.

Will I get perfect scores?

 

· Declarations

In C all variables must be declared and you must show what "type" each variable is:

Ex:

int num, sum, all;

float point, area;

 

· Data types can be classified into:

1) Integers

2) Characters

3) Floating points

· Name choice: preferably up to 8 characters and use meaningful names

Ex: valid names invalid names

names $johnson

array1 1array

end_file end-file

You need to be carefull for a system with upper limit of 8 characters.

Ex: shakespeare vs shakespencil

Since the first 8 characters are the same then the computer will only see shakespe.

· Reasons to declare variables

1) It is easier for a reader to understand about the program.

2) It encourages you to plan before you start writing a program

3) It helps prevent misspelled variable names

Ex:

float area;

float diameter=20.0;

area = 2.0*pi*dmeter;

This program will not run because dmeter is not defined.

Example for multiple functions

/* two_func.c */

#include <stdio.h>

void main (void)

{ printf("This program will call another function.\n");

printf("What’s your name?\n");

name();

printf("Yes, I got your name. \n ");

}

void name (void)

{

printf("My name is John! \n ");

printf("You have a nice name. \n ");

}

 

Output

This program will call another function. from main()

My name is John! from name()

You have a nice name from name()

Yes, I got your name from main()

 

 

Ex:

/* A program to print a triangle */

#include <stdio.h>

void triangle (void) {

printf(" *\n ***\n*****\n");

}

 

void main (void) {

printf("Wait for it folks...\n");

triangle();

printf("That's all folks!\n");

}

 

 

Output:

Wait for it folks...

*

***

*****

That’s all folks!

 

· Debugging

- Syntax errors are result of not following C’s rules

ex: inte n1, n2;as supposed to be int n1, n2;

- Semantic errors or logical errors

are errors in meaning. You need to multiply A1 and A2, but instead you multiply them, you add them together.

ex: sum = A1+A2; as supposed to be sum = A1*A2;

An example of a program with errors.

/* nogood.c a program with errors */

#include <stdio.h>

void main (void)

(

int n, int n2, int n3;

n=5;

n2=n*n;

n3=n2*n2;

printf(" n=%d, n squared=%d, n cubed=%d \n ", n, n2, n3);

)

- Compile for syntax error

- Trace a program for semantic/logical errors

- Debug programs

 

Chapter 3

Data on C

· C data type :

int, short, long, unsigned, char, float, double, long double.

· int :

The int type is signed integer, which means it must be whole number and can be positive, negative, or zero.

Ex: int : 42, -32, 0

range : -32768 to +32767 on IBM PC

byte: 2 byte word (16 bits) to store an int.

· Declaring an int variable:

 

int vector, sum, total;

Initializing a variable:

 

int vector, sum=5, total; (poor form)

int vector=1, sum=5, total=10; (better form)

Type int constant:

 

int sum = 0; (assign a variable to a constant value)

int count = 10;

Normally, C assumes integers as decimal.

Octal - use 0 (zero) prefix.

Ex: 020 (16 decimal)

 

Hexadecimal - use 0x or 0X prefix

Ex: 0x10 (16 decimal)

Ex: Printing integer values.

#include <stdio.h>

void main (void)

{ int ten = 10;

printf("%d minus %d is %d \n ", ten, 2, ten-2);

}

Output

10 minus 2 is 8

Ex: printing octal and hex

void main (void)

{ int x = 100;

printf("Dec=%d, Octal=%o, Hex=%x \n ", x, x, x);

}

Output

Dec=100, Octal=144, Hex=64

Other integer types

1) int

short int and signed short int the max range is -32768 to +32767

unsigned int and unsigned short the max range is 0 to 65535

2) long int

unsigned long int or unsigned long max range is 0 to 4294967295

signed long int or signed long max range is -2147483648 to +2147483647

Integer Overflow

#include <stdio.h>

void main (void)

{ int i = 32767;

printf("%d, %d, %d \n ", i, i+1, i+2);

}

Output

32767, -32768, -32767

Type of characters

are used to store characters such as letters and punctuation marks.

How to declare character type variables?

char table, chair;

- signed type -128 to +127

- unsigned type 0 to +255

character constant and initialization

char grade = 65; (poor form)

char grade = ‘A‘; (better form and more preferred)

Nonprinting characters include: backspacing or speaker beep.

Ex:

char beep = 7;

Octal ASCII code

Ex:

char beep = ‘\007‘; or char beep=‘\7‘;

Hex ASCII code

char beep=‘\x10’; or char beep=‘\x010‘;

Special escape sequences see p.61

\n new line

\t horizontal tab

\\ backslash

 

wpe12.gif (1355 bytes)Back to Top

 

 

 

WEEK THREE

 

 

Ex: Writing an interactive program.

#include <stdio.h>

void main (void)

{ char ch;

printf("please enter a character\n");

scanf("%c", &ch);

printf("The code for %c is %d. \n ", ch, ch);

}

Output

Please enter a character

B <cr>

The code for B is 66.

 

· Type float and double

Allows you to represent decimal fractions and scientific notation to express very large and very small numbers.

Number Scientific Notation Exponential Notation

10000000 = 1.0x106 = 1.0 e6

532.23 = 5.3223 x 102 = 5.3223 e2

.00011 = 1.1x10-4 = 1.1 e-4

32 bits are used to store floating point numbers

- double floating point type use 64 bits

- long double floating point type provide even more precision than double

Declaring floating point variables

 

 

float area;

double mass;

long double national_gross;

float plant = 6.63e-34;

Ex:

include <stdio.h>

void main (void)

{ float time = 27.250000;

printf("time = %f \n ", time);

/*a number following the decimal point is for the field_width. */

printf("time = %.2f \n ", time);

}

 

 

Output

time = 27.250000

time = 27.25

Ex: Formatted output.

#include <stdio.h>

void main (void)

{ float f, g, radius, Avogadro;

f = 2.8;

g = -1.684;

radius = f + g;

Avogadro = 6.02e23;

printf("%f %6.3f %8.2f\n", radius, -12.81963, Avogadro / 1e19);

printf("%e %6.3e %8.2e\n", radius, -12.81963, Avogadro / 1e19);

printf("%g %6.3g %8.2g\n", radius, -12.81963, Avogadro / 1e19);

}

 

Compare between two outputs

Turbo C Output:

1.116000 -12.820 60200.00

1.11600e+00 -1.28e+01 6.0e+04

1.116 -12.8 6e+04

Another compiler ( Output of the program):

1.116000 -12.820 60200.00

1.116000e+00 -1.282e+01 6.02e+04

1.116 -12.8 6e+04

 

Ex: Field width

given that: int age = 33;

printf("age is %2d ", age);

printf("age is %4d ", age);

Ex: print type

#include <stdio.h>

void main (void)

{ float salary;

printf("Enter your desired monthly salary: ");

printf("$_________\b\b\b\b\b\b\b\b\b\b ");

scanf("%f ", &salary);

printf("\rGee!\n ");

printf("\n\t $%.2f a month is $%.2f a year. ", salary, salary*12.0);

}

 

 

Output

Enter your desired monthly salary: $3000.00

Gee! $3000.00 a month is $36000.00 a year.

Ex: A program to convert cents to dollars and cents.

#include <stdio.h>

void main (void) {

int dollars, cents;

cents = 12705;

dollars = cents / 100;

cents = cents % 100;

printf("$%d.%2.2d\n", dollars, cents);

}

Output:

$127.05

 

A possible problem using scanf:

Buffer (what you enter from the keyboard will be stored in a temporary memory location called buffer)

 

printf("Enter your desired monthly salary: \n ");

scanf(" %f ", &salary);

Solution:

Use fflush() after each scanf() function.

fflush () will flush the content of the buffer.

 

 

 

Chapter 4

Character Strings and Formatted Input/Output

· Character strings:

- Strings are stored in an array of char type.

- An array is an ordered sequence of data elements of one type.

· Type of arrays:

- One dimensional

- Two dimensional

- Multi dimensional

· How to declare strings

char name[n] where n is the dimension size

Ex: "My name is David"

 

Null (\0) character is used to indicate the end of a string.

Ex:

/* praise.c */

#include <stdio.h>

#define PRAISE "my Dear, that’s a good name! "

void main (void)

{

char name[50];

printf("What’s your name?\n ");

scanf("%s", name);

printf("Hello, %s %s \n ", name, PRAISE);

}

Output:

What’s your name?

Steve <cr>

Hello, Steve my Dear, that’s a good name!

 

Preprocessor directives:

1) #define: is part of the preprocessor directive which allow establish manifest constant, that is,

symbolic representation for constants.

Ex: #define PI 3.14159

2) #include: is another preprocessor directive causes the processor to add the contents of another file to

your file at the location of the directive.

· How to read the phrase as string:

use function gets()

· String vs Character

The string "X" is not the same as the character ‘X‘.

 

String 1) is enclosed by double quotation marks.

2) consists of two character ‘X‘ and the null character ‘\0‘.

‘X‘ would be considered as character X. => X

"X" would be considered as string X. => X\0

· strlen() : gives the length of a string in characters.

Ex:

#define PRAISE "my Dear, that’s a good name!"

length = strlen(PRAISE);

length = 28.

· sizeof() : gives the size of strings in bytes.

Ex:

#define PRAISE "my Dear, that’s a good name!"

...

size = sizeof(PRAISE); size = 29

int_size = sizeof(int); int_size = 2

float_size = sizeof(float); float_size = 4

- The difference between strlen() and sizeof()

strlen(): gives us the exact number of character in the string

sizeof(): gives us a number, one larger, for it also counts the null character used to terminate the

string.

Ex:

#include <stdio.h>

#define PRAISE "my Dear, that’s a good name!"

void main (void)

{ char name[50];

printf("What’s your name? \n");

scanf("%s", name);

printf("Hello, %s %s \n", name, PRAISE);

printf("Your name has %d letters. It occupies %d"

"memory cells.\n", strlen(name), sizeof(name));

printf("The phrase of PRAISE has %d letters",strlen(PRAISE));

printf("and occupies %d memory cells.\n",sizeof(PRAISE));

}

Output

What’s your name?

Steve <cr>

Hello, Steve my Dear, that’s a good name!

Your name has 5 letters occupies 50 memory cells.

The phrase of PRAISE has 28 letters and occupies 29 memory cells.

wpe12.gif (1355 bytes)Back to top

 

 

 

WEEK FOUR

 

· Constant and the C preprocessor

1) float PI;

PI = 3.14159;

circ = PI * diameter;

 

2) #define PI 3.14159

The #define statement can be used for both character and string constants.

#define BEE ‘B‘

#define NAME "What is your name "

Using #define and #include together

If you have different programs that use the same set of constants.

1) collect all your #define statements in one file, call it, say const.h

2) at the head of each file of programs, insert the statement

#include "const.h" causes the preprocessor to look in the current then system directory.

#include <const.h> the preprocessor look in specific system directory.

Ex: Preprocessor directive constant.

/* printout.c */

#include <stdio.h>

#define PI 3.141593

void main (void)

{ int number = 5;

float ouzo = 13.5;

int cost = 3100;

printf("The %d women drank %f glasses of ouzo.\n", number, ouzo);

printf("The value of PI is %f \n. ", PI);

printf("Farewell! Thou art too dear for my possessing,\n");

printf("%c%d\n", ‘$‘, 2*cost);

}

Output

The 5 women drank 13.500000 glasses of ouzo.

The value of PI is 3.141593.

Farewell! Thou art too dear for my possessing,

$6200

· How to print % sign using printf() function

printf("Your discount is %d %% \n", 15);

Output: Your discount is 15%

See table 4.2 & 4.3 for conversion specification modifiers.

 

 

 

Ex: Printing with field width

#include <stdio.h>

void main (void)

{

int data1 = 100;

float data2 = 1256.56;

printf("%2d\n", data1);

printf("%10d\n", data1);

printf("%-10d\n", data1);

printf("%3.1f\n", data2);

printf("%10.3e\n", data2);

printf("%10.2\n", data2);

printf("%010.2\n", data2);

}

 

Output

100

_______100

100_______

1256.6

1.257e+03_

___1256.56

0001256.56

Ex:

void main (void)

{ printf("%x %X %#x \n ", 31, 31, 31);

printf("**%d ** %d**%d**\n", 42, 42, -42);

printf("**%5d**%5.3d**%05d**%05.3d**\n", 6, 6, 6, 6);

}

 

Output

1f 1F 0x1f

**42 ** 42**-42**

**____6**__006**00006**__006**

· The return value of printf()

It returns the number of characters it printed. The counts includes all the printed characters, including

the spaces and the unseen newline character.

Ex: Returen value of printf ()

void main (void)

{ int n = 212;

int rv;

rv = printf("%d F is water’s boiling point.\n", n);

printf("The printf function printed %d characters. \n", rv);

}

Output

212 F is water’s boiling point.

The printf function printed 32 characters.

· Use of * in printf() and scanf()

* Can be used as a field width argument in the printf ().

Ex:

#include <stdio.h>

void main (void)

{ unsigned width, precision;

int number = 256;

double weight = 242.5;

printf("What field width? \n");

scanf("%d", &width);

printf("The number is: %*d \n", width, number);

printf("Now enter a width and precision\n");

scanf("%d %d", &width, &precision);

printf("weight = %*.*f\n", width, precision, weight);

}

Output

What field width

6

The number is:___256

Now enter a width and a precision

8 3

weight = _242.500

Use of * for scanf()

Ex: scanf("%*d %*d %d", &n);

It is useful, if a program needs to read just certain items from a file that has data arranged in a standard format.

- scanf() function

converts string input into various forms of integer, floating point number, characters, and string.

Syntax: scanf("control string", argument(s));

Rules: For reading values for one of the basic variables types, preceed the variable name with & ,

except for a string variable.

-Ex:

#include <stdio.h>

void main (void)

{ int event;

char heat;

float time;

printf("Type event number, heat letter and time ");

scanf("%d %c %f ", &event, &heat, &time);

printf("The wining time is heat %c ", heat);

printf("of event %d was %.2f. ", event, time);

}

Output:

Type event number, heat letter and time 4 B 36.34

The winning time is heat B of event 4 was 36.34.

· The scanf() view of input

- scanf reads input one character at a time and it skips over whitespace character until it finds a non

whitespace character.

- scanf can’t read more than one word for one %s specifier.

- scanf() places the string in the designated array, it adds the termination ‘\0‘ to convert the input to a C

string.

· If you use a %c specifier:

1) scanf("%c", &ch) reads the first character encountered in input.

2) scanf(" %c", &ch) reads the first non-whitespace character encountered.

· scanf return value

- scanf returns the value 0 when you type a nonnumeric string when the function expects a number.

- scanf return EOF if it detects the condition known as end of file.

- %*d couses that function to skip over corresponding input.

 

Ex: Use of * in scanf ().

#include <stdio.h>

void main (void)

{ int n;

printf("Please enter three integers:\n ");

scanf("%*d %*d %d", &n);

printf("The last integer was %d\n ", n);

}

Output

Please enter three integers

25 35 40 <cr>

the last integer was 40

Macro: is simply a string of tokens that will be substituted for another string of tokens.

Ex: A macro example.

#include <stdio.h>

#define SQUARE(x) x*x

#define PI 3.141592

#define CIRCLE_AREA(r) PI*SQUARE(r)

void main (void)

{ float area;

float radius;

printf("Give me a radius =>");

scanf("%f", &radius);

area = circle_area(radius);

printf("The area of a circle with a radius of %f \n", radius);

printf("is %f square units. ", area);

}

Output:

Give me a radius => 3

The area of a circle with a radius of 3.000000

is 28.274334 square units.

· Function gets() and puts()

- Function gets() specialized in reading strings. It is terminated only when

the returns key is struck.

- Function puts() will output the string.

Ex: An example of gets () and puts ().

#include <stdio.h>

void main (void)

{

char name[81];

puts("Enter your name:");

gets(name);

puts("Greetings, ");

puts(name);

}

Output

Enter your name:

Jack Jefferson <cr>

Greeting,

Jack Jefferson

· Function getchar() and putchar()

- getchar() function takes no argument, and it returns the next character from input.

- putchar() function takes a data type char variable and prints it.

Note: The return value of getchar () function is an integer. In order to assign its return value to a charater, you need to type cast it as follows (assume ch is declared as char):

ch = (char)getchar(); /*takes a character from keyboard and store it in ch*/

putchar(ch); /*prints the content of character ch*/

Ex: intgere overflow

#include <stdio.h>

void main (void)

{ int num = 336;

int mnum = -336;

printf("%d %u %d %u \n", num, num, mnum, mnum);

printf(%d %c \n", num num);

printf(%ld %d \n", 65616, 65616);

}

 

Output

336 336 -336 65200

336 P

65616 80 last two bytes

Ex: A program to calculate the result of the following equation.

#include <stdio.h>

void main (void)

{ float z, a, b, f, h, x;

printf("Enter your data below:\n");

printf("a: "); scanf("%f", &a); fflush(stdin);

printf("b: "); scanf("%f", &b); fflush(stdin);

printf("f: "); scanf("%f", &f); fflush(stdin);

printf("h: "); scanf("%f", &h); fflush(stdin);

printf("x: "); scanf("%f", &x); fflush(stdin);

z = (a+b)*(a+b) / (f - (x+1)/(h-4));

printf("z = %f\n", z);

}

Output

Enter your data below:

a: 4.0

b: -6.0

f: 9.0

h: 7.0

x: 4.0

z = 0.545455

 

 

wpe12.gif (1355 bytes)Back to top

 

WEEK FIVE

 

 

Chapter 5

Operators in C

 

1) Assignment operator: =

Ex: sum = 10; NOT 10 = sum;

sum = total;

height = width = length = 70;

2) Addition operator: +

Ex: sum = total + subtotal;

sum = sum + 1;

3) Subtraction operator: -

Ex: net = gross - tax;

net = 1000 - 500;

4) Sign operators: - and + (is also called unary operator)

Ex: -10;

+25;

5) Multiplication operator: *

Ex: area = width * height;

total = 0.85 * 25;

6) Division operator: /

Ex:

int divide;

float division;

/* poor form */

divide = 5/3; => gives you divide=1

/* better form */

division = 5.0/3.0; => gives you division=1.666667

· Operator precedence

Ex:

sum = (5+6) + 2 * 6 / 3;

 

In general, the order is from left to right with following priorities:

 

operators

symbol

parentheses

( )

+, -, (unary)

-6

multiplication/division

*, /

addition/subtraction

+, -

=

right to left

 

 

Ex: sum = 11 + 2 * 6 / 3;

sum = 11 + 12 / 3

sum = 11 + 4

sum = 15

Ex: top = score = -(2+5) * 6 + (4 + 3 * (2+3));

top = score = -7 * 6 + (4 + 3 * 5)

top = score = -7 * 6 + (4 + 15)

top = score = -7 * 6 + 19

top = score = -42 + 19

top = score = -23

· Modulus operator: %

It gives the remainder that results when the integer to its left is divided by the integer to its right.

Modulus operator doesn’t work with floating point numbers.

· The incrementing operator: ++

 

It increments variable’s value by one.

 

I = I + 1; is same as I++;

The incrementing operator (++) has two modes:

1) prefix mode: ++sum;

2) postfix mode: sum++;

· The decrementing operator: --

 

It decrements variable’s value by one

I = I - 1; is same as I--;

The decrementing operator (--) has two modes:

1) prefix mode: --sum;

2) postfix mode: sum--;

Ex: Convert Centigrade to Fahrenheit

#include <stdio.h>

#define OFFSET 32.0

#define SCALE 1.8

void main (void)

{

float centigrade, fahrenheit;

printf("Centigrade Fahrenheit\n");

centigrade = 0.0;

while(centigrade < 200.0)

{ /* start of while loop */

fahrenheit = SCALE * centigrade + OFFSET;

printf("%10.1f %15.2f\n ", centigrade, fahrenheit);

centigrade = centigrade + 1;

} /* end of while loop */

}

How to modify this program using the incrementing operator.

....

centigrade = 0.0;

while(centigrade < 200.0)

{ fahrenheit = scale * centigrade + OFFSET;

printf("%10.1f %20.2f\n", centigrade, fahrenheit);

centigrade++;

}

or

while(centigrade++ < 200.0)

The difference between the prefix and postfix forms:

 

a++ means increment variable ‘a‘ after its value is used.

++a means increment variable ‘a‘ before its value is used.

prefix: a = 1;

g=2* ++a; first increment a by 1; then multiply a by 2 and assign to g.

g = 4 and a = 2

postfix: a = 1;

g = 2*a++; first multiply a by 2 and assign to g; then increment a by 1.

g = 2 and a = 2

precedence of ++ and -- operators are ranked after parantheses:

x*y++ means (x) * (y++) not (x*y)++

Ex:

x = 3;

y = 6;

result = (x + y--) / 4;

computer calculates as follow (assume result is declared float):

result = (3 + 6) / 4

result = 9 / 4

result = 2.25

When using ++ and -- operator follow the following rules:

1) Don’t use ++ or -- operator on a variable that is part of more than one argument of a statement.

2) Don’t use increment(++) or decrement(--) operators on a variable that appears more than once in an expression.

Ex:

ans = num / 2 + 5 * (1 + num++);

Ex:

n = 3;

y = n++ + n++;

y = 6 or y = 7

n = 5 or n = 5

 

Expression and statement

 

- Expression: an expression is a combination of operators and operands

Ex: constant or variables

if(a > 5)

....

- Statement: a statement is a command to the computer

y=5; or y=2+2;

- Declaration statement: int n;

- Function statement: printf("%d\n ", n);

- Null statement: ;

- Compound statements (Blocks)

 

A compound statement is two or more statements grouped together by enclosing them in braces.

Ex:

sum = 0;

initial = 0;

while(initial++ < 5)

{ sum = sum + initial;

printf("sum = %d\n ", sum);

}

....

Output:

initial ++: ++initial:

sum = 1 sum = 1

sum = 3 sum = 3

sum = 6 sum = 6

sum = 10 sum = 10

sum = 15

Type conversion

1) In any operation involving two types, both values are converted to the "higher" ranking of the two

types.

2) In an assignment statement, the final result of the calculations is converted to the type that is being

assigned a value promotion or demotion.

 

· Type Casting operator

int i;

i = 1.6 + 1.7;

i = (int)1.6 + (int)1.7;

The cast operator converts the following value to the type specified by the

enclosed keyword(s).

Ex:

(float)9 converts integer 9 to the floating point number 9.0

 

 

 

 

Chapter 7

Loops and conditional statement in C

· The if statement

Form: if (expression)

statement;

Ex: If statement.

#include<stdio.h>

void main (void)

{ char ch;

scanf("%c", &ch);

if (ch == ‘y‘)

printf("you typed y\n");

}

Difference between while loop and if statement

· if else statement it let us choose between two choices

form: if (expression)

statement1;

else

statement2;

Ex: If else statment.

#include <stdio.h>

void main (void)

{ char ch;

scanf("%c", &ch);

if(ch == ‘y‘)

printf("You typed ‘y‘.\n");

else

printf("You didn’t type ‘y ‘.\n");

}

Ex:

if(x>0)

{ printf("incrementing x:\n");

x++; }

else

printf("x<0\n");

· Nested if statement

form: if expression1

if expression

 

 

 

Ex: Nestet if statement.

#include <stdio.h>

void main (void)

{ int x, y;

if(x>0)

if(y<10)

printf("your number is between 1-9 ");

}

Ex: If else statement.

#include <stdio.h>

void main (void)

{ float number;

printf("\nGive me a number from 1 to 10 => ");

scanf("%f", &number);

if(number > 5.0)

printf("Your number is greater than 5 \n");

else

printf("Your number is less than or equal to 5 \n");

printf("The value of your number was %f" number);

}

getchar() and putchar()

The getchar() function takes no arguments and it returns the next character from input.

ch = getchar(); reads the input character and assigns it to ch (assume ch in type int)

putchar(ch); prints out the character previously assigned to ch

Ex: Use of getchar () in an if else statement.

#include <stdio.h>

#define SPACE ‘ ‘

void main (void)

{ char ch;

ch = (char) getchar();

while(ch!=‘\n‘) /* while not end of line */

{ if (ch == SPACE)/* leave the space */

putchar(ch); /* character unchanged */

else

putchar(ch+1); /* print other character */

ch = getchar();

}

}

Output

call me hal <cr> You type from the keyboard

dbmm nf ibm Computer gives these results

 

 

Another way of writing while loop for the above example.

 

while((ch=getchar()) != ‘\n‘)

{ if (ch == SPACE)

putchar(ch);

else

putchar(ch+1);

}

else if: How does the computer decide which if goes with which else?

else goes with the most recent if unless braces indicate otherwise.

Ex:

if (number > 6)

if (number < 12)

printf("You are close! \n");

else

printf("Sorry, you lose a turn!\n");

Output

Number Response1 Response2

5 (none) Sorry you lose a turn

10 You are close! You are close!

15 Sorry you lose a turn (none)

Ex:

if(number > 6)

{ if (number < 12)

printf("you are close!\n");

}

else

printf("Sorry, you lose a turn!\n");

 

 

wpe12.gif (1355 bytes)Back to top

 

WEEK SIX

 

REVIEW

EXAMINATION #1

 

 

wpe12.gif (1355 bytes)Back to top

 

WEEK SEVEN

 

 

Form 3

if (expression1)

statement1

else if (expression2)

statement2

else

statement3

Ex: Else if example

#include <stdio.h>

void main (void)

{ float num1, num2;

char op;

while(1)

{ printf("Type number, operator, number\n");

scanf("%f %c %f", &num1, &op, &num2);

if(op==‘+‘)

printf("=%f", num1+num2);

else if(op==‘-‘)

printf("=%f", num1-num2);

else if(op==‘*‘)

printf("=%f", num1*num2);

else if(op==‘\‘)

printf("=%f", num1\num2);

printf("\n\n");

}

}

The else-if construction is a reformating of nested if-else statement.

Logical operators

Symbol

Name

Note

&&

And

Expression1&&Expression2 is true if both expression are true

||

Or

Expression1||expression2 is true if either one or both expressions are true

!

Not

!Expression is true if the expression is false

 

Order of evaluation: they are evaluated from left to right. Evaluation stops as soon as something is discovered that renders the expression false.

Ex:

6>2 && 3==3 True

!(6>2 && 3==3) False

Priorities of logical operators:

! (same as increment operator)

&& (above assignment)

|| (above assignment)

a>b && b>c || b>d => ((a>b) && (b>c)) || (b>d)

Ex:

#include <stdio.h>

#define PERIOD ‘.‘

void main (void)

{ char ch;

int char_count = 0;

while((ch= (char) getchar()) != PERIOD)

if (ch!=‘ ‘ && ch != ‘\n‘ && ch!=‘\t‘)

char_count++;

printf("There are %d non-white space characters\n ", char_count);

}

logical operators <cr>

combine relationships. <cr>

There are 36 non-whitespace charaters <output from computer>

Ex: A word count program.

#include <stdio.h>

void main (void)

{ int charcnt = 0;

int wordcnt = 0;

char ch;

printf("Type in a phrase:\n");

while((ch=getchar()) != ‘\r‘)

{ charcnt++;

if(ch==‘ ‘)

wordcnt++;}

printf("character count is : %d\n", charcnt);

printf("Word count is %d\n ", wordcnt+1);

}

Output

Type in a phrase

cat and dog <cr>

character count is 11

word count is 3

Multiple choice: switch and break

General form:

switch(integer expression)

{ case 1: statement1;

break;

case2: statement2;

break;

case 3: statement3;

break;

default: statement4;

}

The switch labels must be type integer constant or constant expressions. You can’t use a variable for a label. The expression in the parantheses should be one with an integer value. Break is used to escape from a loop.

Ex: Four function calculator.

#include <stdio.h>

void main (void)

{ float num1, num2;

char op;

while(1)

{ printf("type number, operator, number \n");

scanf("%f %c %f", &num1, &op, &num2);

switch(op)

{ case ‘+‘: printf("=%f", num1+num2);

break;

case ‘-‘: printf("=%f", num1-num2);

break;

case ‘*‘: printf("=%f", num1*num2);

break;

case ‘/‘: printf("=%f", num1/num2);

break;

default: printf("Unkown operator ");

}

printf("\n\n");

}

}

Ex:

#include <stdio.h>

void main (void)

{ int i = 0;

while(i<3)

{ switch(i++)

{ case 0: printf("Merry");

case 1: printf("Merr");

case 2: printf("Mer");

default:printf("Oh no!"); }

putchar(‘\n‘);

}

}

Output

MerryMerrMerOh no!

MerrMerOh no!

MerOh no!

The continue statement

This statement can be used in the three loop forms but not in a switch. Continue causes the rest of an iteration to be skipped and the next iteration to be started.

Ex:

while((ch= (char) getchar()) != ‘\n‘)

if(ch==‘\t‘)

break;

putchar(ch);

Alternative

while((ch= (char) getchar()) != ‘\n‘ && ch!=‘\t‘)

putchar(ch);

Ex:

while((ch= (char) gethcar()) != ‘\n‘)

{ if (ch== ‘\t‘)

continue;

putchar(ch);

}

Alternative

while((ch= (char)getchar()) != ‘\n‘)

if(ch != ‘\t‘)

putchar(ch);

· The goto statement

The goto statement has two parts: the goto keyword and label name.

Note: Since C is a structured language, you must use goto in right situation. You must use it

judiciously. If you have goto all over your program, then there is no meaning for the C language to

have a loop structure.

· goto part2;

...

part2: printf("Refined analysis\n");

· Ex:

if(ibex > 14)

goto exp1;

sheds = 2;

goto exp2;

exp1: sheds = 3;

exp2: help = 2 * sheds;

Alternative:

if(ibex > 14)

sheds = 3;

else

sheds = 2;

help = 2 * sheds;

/* Program to read hours worked for each of a company's employees, and print the salary owing to each one. */

#include <stdio.h>

void main (void)

{ float hours, salary;

printf("Enter hours worked for an employee (-1 to finish): ");

scanf("%f", &hours);

while (hours != -1.) {

if (hours <= 40.)

salary=hours*25.; /*$25/hour up to 40 hours*/

else

salary = 40. * 25. + (hours - 40.) * 35.;

/*$25/hour for first 40, then $35/hour*/

printf("Salary is %.2f\n\n", salary);

printf("Enter hours worked for an employee (-1 to finish): ");

scanf("%f ", &hours);

}

}

Output

Enter hours worked for an employee (-1 to finish): 30

Salary is 750.00

Enter hours worked for an employee (-1 to finish): 40

Salary is 1000.00

Enter hours worked for an employee (-1 to finish): 1

Salary is 25.00

Enter hours worked for an employee (-1 to finish): 0

Salary is 0.00

Enter hours worked for an employee (-1 to finish): -1

[Terminate here]

Example of else if construct

#include <stdio.h>

void main(void)

{ float weight, price = .2;

printf("Enter weight of apple: ");

scanf("%f", &weight);

printf("Ajax ");

if (weight > 10.)

{ printf("Premium ");

price += .1; }

else

if (weight > 8.) /* Brace not necessary */

printf("Juicy ");

else

if (weight > 6.)

{ printf("Snack ");

price -= .05; }

else

{ printf("Cooking ");

price -= .1; }

printf("Apple. $%4.2f.\n", price);

}

Output:

Enter weight of apple: 6

Ajax Cooking Apple. $0.10.

Enter weight of apple: 10

Ajax Juicy Apple. $0.20.

Another example of else if construct

#include <stdio.h>

void main(void)

{ float weight, price = .2;

printf("Enter weight of apple: ");

scanf("%f", &weight);

printf("Ajax ");

if (weight > 10.)

{ printf("Premium ");

price += .1; }

else if (weight > 8.)

{ printf("Juicy "); /* Brace necessary? */

} /* Brace necessary? */

else if (weight > 6.)

{ printf("Snack ");

price -= .05; }

else

{ printf("Cooking ");

price -= .1; }

printf("Apple. $%4.2f.\n", price);

}

Output

Enter weight of apple: 6

Ajax Cooking Apple. $0.10.

Enter weight of apple: 10

Ajax Juicy Apple. $0.20.

 

 

 

Example of break statement

#include <stdio.h>

void main(void)

{ float price;

char grade;

printf("Enter grade of apple: ");

scanf(" %c", &grade);

printf("Ajax ");

switch (grade)

{ case 'P':

case 'p':

price = .3;

printf("Super ");

break;

case 'J':

case 'j':

price = .2;

printf("Excellent ");

break;

case 'S':

case 's':

price = .15;

printf("Delicious ");

break;

default:

price = .1; }

printf("Apple. $%4.2f.\n", price);

}

Output

Enter grade of apple: p

Ajax Super Apple. $0.30.

Enter grade of apple: J

Ajax Excellent Apple. $0.20.

Enter grade of apple: s

Ajax Delicious Apple. $0.15.

Enter grade of apple: Q

Ajax Apple. $0.10.

 

wpe12.gif (1355 bytes)Back to top

 

 

WEEK EIGHT

 

 

Chapter 6

Looping

While loop

Form:

while (expresssion)

body of while loop

Ex: While loop.

#include <stdio.h>

void main (void)

{ long num;

long sum = 0L;

int status;

printf("Please enter an integer to be summed ");

printf("Enter ‘q‘ to quit\n");

status = scanf("%ld", &num);

while(status == 1)

{ sum = sum + num;

printf("Please enter next integer to be summed ");

printf("Enter ‘q‘ to quit \n ");

status = scanf("%ld", &num);

}

printf("Those integers sum to %ld\n ", sum);

}

Note:

The return value of scanf: 1 if it receives an integer, 0 if it receives an non-numeric

Modify the program:

while ((scanf("%ld", &num)) == 1)

{

/* Loop statements */

}

PseudoCode: is writing the program in simple english before you write the actual computer code.

How to terminate the while loop?

index = 1;

while(index < 5)

printf("Good morning!\n ");

Ex: While loop.

#include <stdio.h>

void main (void)

{ int count = 0;

int total = 0;

while (count < 10)

{ total += count; /* total = total + count; */

printf("count=%d, total=%d\n ", count++, total); }

}

Output

count=0, total=0

count=1, total=1

count=2, total=3

count=3, total=6

count=4, total=10

count=5, total=15

count=6, total=21

count=7, total=28

count=8, total=36

count=9, total=45

· Important points about while loop

1) An entry condition must be met before the body of the loop is entered.

n=10;

while(n<8)

2) If a while loop begins without braces {}, then the single statement immediately following the test

condition is part of the loop.

3) Be carefull where you place the semicolons.

Ex: While loop.

#include <stdio.h>

void main (void)

{ int n=0;

while(n<3)

printf("n is %d\n ", n); /*part of the loop*/

n++; /*NOT part of the loop*/

printf("That’s all this program does\n");

}

Output

n is 0

n is 0

n is 0

In the absence of a compound statement, the loop ends at the first semicolon.

Ex: While loop.

#include <stdio.h>

void main (void)

{ int n = 0;

while(n++ < 3);

printf("n is %d\n ", n);

printf("That’s all this program does. \n");

}

Output

n is 4

That’s all this program does.

 

Relational operators are used to form the relational expression used in while statements and in other C statement.

Operator

Meaning

<

less than

<=

less than or equal to

= =

equal to

>=

greater than or equal to

>

greater than

! =

not equal to

 

Precedence of relational operators is the lowest of all except that of assignment

x > y + 2; same as x > (y+2);

x = y > 2; same as x = (y>2); x=1 if y>2

x=0 if y<2

 

· The for loop

General form:

for(initialize, test, update)

The for loop contain three expression seperated by semicolons

1) initialization statement

2) a test condition

3) end statement, increment or decrement statement

Ex: For loop

#include <stdio.h>

void main (void)

{ int num;

printf("\t n \t n squared \n");

for(num=0; num<=6; num++)

printf("\t%5d \t %5d \n", num, num*num);}

Output

n n squared

0 0

1 1

2 4

: :

6 36

 

Ex: Another example of for loop

#include <stdio.h>

void main (void)

{ int count, total;

for(count=0, total=0; count<5; count++)

{ total += count; /*same as: total=total+count*/

printf("count=%d, total=%d\n", count, total);

}

}

Output

count=0, total=0

count=1, total=1

count=2, total=3

count=3, total=6

count=4, total=10

 

Ex: For loop.

#include <stdio.h>

void main (void)

{ char ch;

for (ch=‘a‘; ch<=‘z‘; ch++)

printf("The ascii value for %c is %d\n", ch, ch);

}

Output

The ascii value for a is 97

The ascii value for b is 98

:

The ascii value for z is 122

Note: Characters are stored as integers.

Ex:For loop.

#include <stdio.h>

void main (void)

{ float debt;

/* same: debt *= 1.1 */

for(debt=100.0; debt<150.0; debt=debt*1.1)

printf("Your debt is now $%.2f\n", debt);

}

Output

Your debt is now $100.00

Your debt is now $110.00

Your debt is now $121.00

Your debt is now $133.00

Your debt is now $146.00

Ex: For loop

#include <stdio.h>

void main (void)

{ for( ; ; )

printf("I want some action\n "); }

 

 

Output

I want some action

I want some action

I want some action

:

It goes on forever, since empty test is considered to be true.

Ex: For loop

#include <stdio.h>

void main (void)

{ int num;

for (printf("Keep entering numbers!\n"); num!=6;)

scanf("%d", &num);

printf("That’s the one I want! \n");

}

Output

Keep entering numbers!

5

9

10

6

That’s the one I want!

 

 

New assignment operators: +=, -=, *=, /=, %=

Such as: sum += 10; => sum = sum + 10;

sum *= 10; => sum = sum * 10;

sum -= 10; => sum = sum - 10;

sum /= 10; => sum = sum / 10;

sum %= 10; => sum = sum % 10;

Ex:

x *= 3 * y + 12; is as same as x = x*(3*y+12);

 

 

wpe12.gif (1355 bytes)Back to top

 

WEEK NINE

 

 

Ex: How to calculate quarterly and yearly interest rate

#include <stdio.h>

void main(void)

{ float rate, balance, interest;

float yearly_interest;

float total_interest;

int year, quarter;

printf("Enter interest rate (zero to quit): ");

scanf("%f", &rate);

while (rate != 0)

{ if (rate < 5 || rate > 20)

printf("Out of the reasonable range.\n");

else

{ printf("\nStart Interest End\n");

balance = 1000;

total_interest = 0;

for (year = 1; year <= 3; ++year)

{ printf("Year %i\n", year);

yearly_interest = 0;

for(quarter=1;quarter<=4;++quarter)

{ printf(" %i %7.2f",quarter, balance);

interest=balance*rate/100*.25;

yearly_interest += interest;

balance += interest;

printf(" %7.2f %7.2f\n", interest, balance); }

printf("Total interest for the year: $%.2f\n",

yearly_interest);

total_interest += yearly_interest;

}

printf("\nEnding balance: $%.2f. Interest earned: $%.2f.\n\n",

balance, total_interest);

}

printf("Enter interest rate (zero to quit): ");

scanf("%f", &rate);}

}

Output

Enter interest rate (zero to quit): 12.5

Start Interest End

Year 1

1 1000.00 31.25 1031.25

2 1031.25 32.23 1063.48

3 1063.48 33.23 1096.71

4 1096.71 34.27 1130.98

Total interest for the year: $130.98

Year 2

1 1130.98 35.34 1166.33

2 1166.33 36.45 1202.77

3 1202.77 37.59 1240.36

4 1240.36 38.76 1279.12

Total interest for the year: $148.14

Year 3

1 1279.12 39.97 1319.09

2 1319.09 41.22 1360.32

3 1360.32 42.51 1402.83

4 1402.83 43.84 1446.66

Total interest for the year: $167.54

Ending balance: $1446.66. Interest earned: $446.66.

Enter interest rate (zero to quit):0

An exit condition loop: do-while

do-while: the condition is evaluated after the loop is executed rather than before. The loop must be

executed at least once.

Form:

do

{ statement1;

statement2;

} while(expression);

 

EX: Do while.

#include <stdio.h>

void main (void)

{

int count = 0;

int total = 0;

do

{ total += count;

printf("Count=%d, total=%d\n", count++,

total);

} while (count < 10);

}

Output

count=0, total=0

count=1, total=1

:

count=9, total=45

 

#include <stdio.h>

void main(void)

{ float price;

short quantity;

char answer;

printf("Enter 0,0 to quit.\n");

do

{ printf("Enter 'price,quantity': ");

scanf("%f,%hi", &price, &quantity);

printf("The total for this item is "

"$%6.2f.\n", price * quantity);

printf("Another (Y/N)? ");

scanf(" %c", &answer);

}while (answer == 'Y' || answer == 'y');

printf("Thank you for your patronage.\n");

}

 

Output:

Enter 0,0 to quit.

Enter 'price,quantity': 100,30

The total for this item is $3000.00.

Another (Y/N)? y

Enter 'price,quantity': 25, 75

The total for this item is $1875.00.

Another (Y/N)? n

Thank you for your patronage.

Which loop: while or do-while?

entry-condition: while

exit-condition: do-while

Which loop: for loop or while?

The for loop involves initialization and updating a variable. Use while loop when the conditions are

otherwise.

for(count=1; count<=100; count++)

while(scanf("%d", &num) ==1)

Nested loops

A nested loop is a loop that is inside another loop.

Ex: A nested loop.

#include <stdio.h>

#define ROWS 6

#define COL 6

void main (void)

{ int row, col;

for (row=0; row<ROWS; row++)

{ for(col=0; col<COL; col++)

printf("%d", col);

printf("\n");

}

}

Output

012345

012345

012345

012345

012345

012345

 

 

Ex: Another nested loop.

#include <stdio.h>

#define ROWS 6

#define CHARS 6

void main (void)

{ int row;

char ch;

for (row=0; row<ROWS; row++)

{ for (ch=‘A‘+ row; ch<‘A‘+CHARS; ch++)

printf("%c", ch);

printf("\n");

}

}

Output

ABCDEF How can you modify this program to do the opposite?

BCDEF

CDEF

DEF

EF

F

ARRAYS

An array is a collection of data objects of the same type stored sequentially in memory.

Array declaration:

int temper [7];

char alpha[26];

float average[30];

char name[50];

Ex: Use of one dimensional array.

#include <stdio.h>

void main (void)

{ int temper[7];

int day, sum;

for(day=0; day<7; day++)

{printf("Enter temperature for day %d: ",day);

scanf("%d", &temper[day]);

}

sum=0;

for (day=0; day<7; day++)

sum+=temper[day];

printf("Average is %d.", sum/7);

}

Output

Enter temperature for day 0: 74

:

Enter temperature for day 6: 69

Average is 71

Ex: Reading an unkown number of elements

#include <stdio.h>

#define LIM 40

void main (void)

{ float temper[LIM];

float sum=0.0;

int num, day=0;

do

{ printf("Enter temperature for day %d: ", day);

scanf("%f", &temper[day]);

} while(temper[day++] > 0);

num=day-1;

for(day=0; day<num; day++)

sum+=temper[day];

printf("Average is %f ", sum/num);

}

Output

Enter temperature for day 0: 71.3

Enter temperature for day 1: 80.9

Enter temperature for day 2: 89.2

Enter temperature for day 3: 0

Average is 80.5

Bounds Checking

C does not warn you when an array subscript exceeds the size of the array.

Solution:

do

{ if (day>=LIM)

{ printf("Buffer full.\n");

day++; }

break;

}

printf("Enter temperature for day %d: ", day);

:

:

 

WEEK TEN

 

Chapter 13

Storage Classes

 

Initialization and storage classes

-External

-Static How widely known as data item is to various functions in a

-Automatic program and for how long it is kept in memory.

-Automatic (local) variables and arrays are private to a function. When a function finishes and returns to the calling function, the space used to hold its variables is freed.

In ANSI C automatic arrays are initialized as follows:

void main (void)

{ int powers[5]={1,2,6,6,7};

:

:

Because the array is defined inside main(), it is an automatic array.

-External variables and arrays (global)

An external variable or external array is one defined outside a function.

EX:

#include <stdio.h>

int report;

int powers[5]={1,2,6,6,7};

void main (void)

{

:
}

int nxt_func(int n)

{

:

}

External vs Automatic variables and arrays

External variables and arrays are:

1) known to all functions following them in a file

2) they persist as long as the program runs

3) They are initialized to zeros by default, therefore it is initialized to 0.

Static variables and arrays

The keyword static creates an array that is local to the function. Like an external array, static array retains its value between functions calls and is initialized to zero by default.

int account (int n, int m)

{ static int beans[2]={34, 33};

:

}

The storage class defines two characteristics of the variable:

1) lifetime: The lifetime of a variable is the length of time it retain aparticular value.

2) visibility or scope: of a variable refers to which parts of program will be able to recognize it.

 

Why storage classes are necessary

1) use memory more efficiently

2) run faster

3) less prone to programming errors

 

Lifetime of Automatic Variables

Such variables are called "automatic" because they are created and destroyed automatically.

func( )

{ int alfa;

auto int beta;

register int gamma;

...

- A register variable is a special kind of automatic variable. The compiler will assign it to one of the CPU

registers leading to faster operation provided a register is available.

- They (registers) are created when the function containing them is called, and destroyed when the

function terminates.

 

Lifetime of static variables

A static variable is known only to the function in which it is defined, but unlike automatic variables, it does not disappear when the function terminates.

 

func( )

{ static int delta;

:

}

 

Static initialization:

Static variables or arrays are initialized to zero you don’t explicitly initialize them to some other value.

External static variables

Declare a static variable outside any function.

- The difference between an ordinary external and an external static variable lies is the scope.

 

static randx =1;

int rand( )

{ }

 

External variables

A variable defined outside a function belongs to external storage class

int names;

double mass;

void main(void)

{ extern int names;

extern double mass;

}

 

including the extern keyword allows a function to use an external variable even if it is defined in a file or in a different file.

 

Ex:

int name; /*global variable*/

int num; /*global variable*/

int magic(void); /*function prototyping*/

void main (void)

{ extern int name; /*Same as name in global*/

int num; /*different num than in global*/

: /*and it is auto*/

}

 

int magic(void)

{ auto int num; /*different num than in global*/

: /*and it is explicitly auto*/

name = .....; /*no need declaration of name*/

/*by default it is the global name*/

}

The keyword extern always indicates that a declaration is not a definition, since it instructs the compiler to look elsewhere.

Ex:

extern int term; doesn’t cause space to be allocated and don’t use the keyword extern to create an

external definition.

void main(void)

{...}

Ex: correction of the above example

int term;

void main(void)

{...

 

 

Summary of storage classes

Storage class Keyword Lifetime duration Scope

automatic auto Temporary(function) local

Register register Temporary(function) local

Static static Persistent(program) local

External extern Persistent(program) global(all files)

Extern static static Persistent(program) global(one file)

void main(void)

{ ...

}

int theta; /*global variable*/

func( )

{ ...

}

The variable theta will be visible only to the function func( ), and will be invisible to main( ) .

An external variable can be initialized once, and that must occur when the variable is defined.

 

Ex: Static Vs. automatic variables.

#include <stdio.h>

extern void trystat(void);

void main(void)

{ int count;

for (count =1; count <=3; count++)

{ printf("Here comes iteration%d:\n", count);

trystat();

}

}

 

extern void trystat(void)

{ int tade =1;

static int stay =1;

printf("fade=%d and stay=%d\n",fade++,stay++);

}

Output

Here comes iteration 1:

fade =1 and stay =1

Here comes iteration 2:

fade =1 and stay =2

Here comes iteration 3:

fade =1 and stay =3

 

 

 

Ex: Storage classes

#include <stdio.h>

extern void static_demo (void);

static int i = 10;

void main (void)

{ printf("The value of i in function main() is:%4d\n\n",i);

i++;

static_demo();

printf("The value of i in function main() is:%4d\n\n",i);

}

 

extern void static_demo (void)

{ i+=5;

printf("The value of i in function static_demo() is:%4d\n\n", i);

}

 

Output

The value of i in function main() is: 10

The value of i in function static_demo() is: 16

The value of i in function main() is: 16

Ex: Storage classes

#include <stdio.h>

/*user defined function prototypes*/

extern void static_demo1(void);

extern void static_demo2(void);

/*external variable declarations*/

static int i = 10;

extern int k;

void main (void)

{i++;

printf("The value of i in function main() is:%4d\n\n",i);

k++;

printf("The value of k in function main() is:%4d\n\n",k);

static_demo1();

printf("The value of i in function main() is:%4d\n\n",i);

printf("The value of k in function main() is:%4d\n\n",k);

k += i;

printf("The value of k in function main() is:%4d\n\n",k);

static_demo2();

printf("The value of i in function main() is:%4d\n\n",i);

printf("The value of k in function main() is:%4d\n\n",k);

}

static int j =5;

extern void static_demo1(void)

{i+=5;

printf("The value of i in function static_demo1() is:%4d\n\n",i);

j-=i;

printf("The value of j in function static_demo1() is:%4d\n\n",j);

}

int k=5;

extern void static_demo2(void)

{i+=5;

printf("The value of i in function static_demo2() is:%4d\n\n",i);

j-=i;

printf("The value of j in function static_demo2() is:%4d\n\n",j);

k=i+j;

 printf("The value of k in function static_demo2() is:%4d\n\n",k);

}

Output

The value of i in function main() is: 11

The value of k in function main() is: 6

The value of i in function static_demo1() is: 16

The value of j in function static_demo1() is: -11

The value of i in function main() is: 16

The value of k in function main() is: 6

The value of k in function main() is: 22

The value of i in function static_demo1() is: 21

The value of j in function static_demo1() is: -32

The value of k in function static_demo1() is: -11

The value of i in function main() is: 21

The value of k in function main() is: -11

 

The following program fragment uses variable i with "extern" storage-class specifier. Since there is no external level variable with the keyword "extern" using identifier i. The internal level i with "extern" storage-class specifier is visible only in the block in which it is declared.

void main(void)

{ int k ;

...

for (k=1; k<5; k++)

{ extern int i;

k+=i;

i++;

}

}

int i;

 

 

 

The following program fragment uses two "static" variables. The one in the main program is explicitly initialized and the other is initialized to 0 by the compiler.

visibility of i in main() :function main()

visibility of i in function-1() :function function-1()

lifetime of i in main() :global

lifetime of i in function-1() :global

initial value of i in main() :10

initial value of i in function-1() :0

extern void function_1(void);

void main(void)

{ static int i=10;

...

function_1();

i++;

function_1();

...

}

extern void function_1(void)

{ static int i;

i++;

...

}

 

The following program fragment illustrates extern variable i which is defined in module 1, and how to make this variable visible in module 2.

visibility of i :functions main() and function_1()

lifetime of i :global

initial value of i :10

/* MODULE 1 */

extern void function_1(void);

int i =10; /*definition of variable i*/

void main(void)

{ i++;

...

function_1();

...

function_2();

}

extern void function_1(void)

{ i+=5;

...

}

visibility of i : all function that may be defined in this module

lifetime of i : global

initial value of i : depends on the calling function

 

 

/* MODULE 2 */

extern void function_2(void);

/*reference to variable i in MODULE 1*/

extern int i;

extern void function_2(void)

{ i+=20;

...

function_1();

...

}

 

The following program fragment shows variables i and j defined with static storage class, but with different visibility. Variable k is defined so that it can be made visible in other modules (module two in this case) by using the extern keyword.

visibility of i : functions main(), func_1(), func_2()

visibility of j : functions func_1(), func_2()

visibility of k : function func_2()

Lifetime of i : global

Lifetime of j : global

Lifetime of k : global

Initial value of i : 10

Initial value of j : 0

Initial value of k : 12

/* Module 1 */

extern void func_1(void);

extern void func_2(void);

static int i = 10;

void main (void)

{ i++;

...

func_1();

...

func_2();

...

}

static int j;

extern void func_1(void)

{ i += 5;

j = ++I + 10;

...

}

int k = 12;

extern void func_2(void)

{ i += 5;

j = j+10;

k ++;

}

To write a function with a return value

1) When you define a function, state the type of value it returns

2) Use the keyword return to indicate the value to be returned

 

Ex: User define function ().

#include <stdio.h>

void main (void)

{ double x, xpow;

double power(double a, int b);

int n;

printf("Enter a number and the positive ");

printf("integer power to which\n the number ");

printf("will be raised. Enter ‘q‘ to quit.\n");

while(scanf("%lf %d ", &x, &n) == 2)

{ xpow = power(x, n);

printf("%.3e to the power %d is %.3e\n", x, n, xpow);

}

}

double power (double a, int b)

{ double powr=1;

int i;

for (i=0; i<=b; i++)

powr *=a;

return powr; /* return the value of power */

}

Output

Enter a number and the positive integer power to which

the number will be raised. Enter ‘q’ to quit.

2.2 5 <cr>

2.200e+000 to the power 5 is 5.154e+001

8.0 <cr>

8 <cr>

8.000e+000 to the power 8 is 1.678e+007

144 2 <cr>

1.440e+002 to the power 2 is 2.074e+004

q <cr>

Overview on of arrays

Initializing two dimensional array

 

static matrix[3][4]={{2,4,5,6},{3,5,6,8},{8,9,10,11}};

static int sq[2][3]={{5,6},{7,8}};

Initializing Arrays

Ex: This program makes change; you type in a price in cents, and the program tells you how many half-

dollars, quarters, dimes, nickels, and pennies it take to make up this amount.

 

#include <stdio.h>

#define LIM 5

int table[LIM] = {50, 25, 10, 5, 1};

void main (void)

{ int dex, amount, quantity;

printf("Enter amount in cents: ");

scanf("%d", &amount);

for (dex=0; dex<LIM; dex++)

{ quantity = amount/table[dex];

printf("Value of coint=%2d, ",table[dex]);

printf("Number of coints=%2d\n", quantity);

amount=amount%table[dex];

}

}

Output:

Enter amount in cents: 143

value of coint=50, number of coints=2

value of coint=25, number of coints=1

value of coint=10, number of coints=1

value of coint=5, number of coints=1

value of coint=1, number of coints=3

Array initialization:

You can’t initialize a local (automatic) array. Because C doesn’t create such an array until the function

containing it is called and by then it is too late to put initial values in it.

static int table[]={50, 25, 10, 5, 1};

Array contents and initialization

void main (void)

{ int array[10];

:

}

If the array was declared an external or static variable, it will be initialized to zero.

 

More than one dimension:

float agents [5][COL]; 5 is rows, and COL is coloumns

Initializing Three-Dimensional Arrays

 

int threed[3][2][4]={{{1,2,3,4},{5,6,7,8}},

{{6,7,8,9},{4,5,6,7}},

{{7,2,6,3},{0,1,9,4}}};

 

It’s in the 3rd group <-- -->the 2nd of the 2 dim array

| |

int threed[2][1][0] = 0;

|

-->the 1st element in 1-dim

 

 

wpe12.gif (1355 bytes)Back to top

 

WEEK ELEVEN

 

Chapter 8

I/O functions

I/O functions:

Functions that transport data to and from your program.

printf(), scanf(), getchar(), and putchar()

ex: getchar() and putchar()

Ex: Use of I/) functions.

#include <stdio.h>

void main (void)

{ char ch;

while((ch=getchar()) != ‘#‘)

putchar(ch);

}

Output

Hello, there I would <CR> (what you type)

Hello, there I would (what you see)

like a #3 bag of potatoes. <CR>

like a

Question: Why do you have to type a whole line before the input is echoed?

Is there any better way to terminate input?

Buffers

- Unbuffered or direct: it is immediate echoing of what you type.

- Buffered: the character you type are collected and stored in an area of temporary storage called buffer.

Terminating keyboard input

Files: A file is a block of memory in which information is stored

- low level I/O host operating system

- Standard I/O package: getchar(), putchar(), printf(), and scanf()

C treats input and output devices the same as it treats regular files on storage device.

* The keyboard and display devices are treated as files that are opened automatically by every C

program.

How to detect end-of-files to terminate keyboard input?

1) to place a special character at the end of the file: ^Z

2) to store information on the size of the file: 200 bytes

- C uses the getchar() function to return a special signal when the end of file is detected, regardless of the method actually used to find the end of the file (EOF).

EOF is defined in stdio.h file as follow:

#define EOF -1

Ex: EOF example.

#include <stdio.h>

void main (void)

{ int ch;

/*character variable may be represented by*/

/*unsigned integer in the range of 0 to 255*/

while((ch=getchar()) != EOF)

putchar();

}

Note:

1) stdio.h takes care of EOF

2) putchar() prints out the character equivalent

3) Unix system: Control D Microcomputer: Control Z

 

Redirection and files

A C program using the standard I/O package looks to the standardinput as a source of input, which is the stream we earlier identified as stdin.

Two methods to work with files:

1) using special functions that open files, close files, read files.

2) redirecting input & output a long different channels.

Redirecting Input

Sample1.C

Sample1 < words where Sample1 is the name of executable file

< Unix redirection operator

words is a text file

It causes the words file to be associated with the stdin stream, chanelling the file contents into Sample1.

-File words is the I/O "device"

Redirecting Output

 

Sample1 > mywords

You type the text file and end it with Control Z on DOS or Control D on Unix

To see the content of file mywords:

- type mywords on DOS

- type mywords on Unix

Combine Redirection

to make a copy of the file mywords and call it saveword.

Sample1 < mywords > saveword or

Sample1 > saveword < myword

 

Rules of redirection

1. A redirection operator connects an executable program with a file (not a file with another file).

2. Input cannot be taken from more than one file, nor can output be directed to more than one file using

these operators.

3. The space between the names and operators are optional.

>> : lets you add data to the end of an existing file

| : lets you connect the output of one program to the input of a second program.

 

Mixing Numeric and character input

#include <stdio.h>

void main (void)

{ int ch;

int rows, cols;

void display(char c, int n, int m);

while((ch=getchar()) != EOF)

{ scanf("%d %d", &rows, &cols);

display(ch, rows, cols);

}

}

void display(char c, int n, int m)

{ int row, col;

for (row=1; row<=n; row++)

{ for(col=1; col<=m; col++)

putchar(c);

putchar(‘\n‘);

}

}

Output

a 2 3

aaa

aaa

b12

[blank lines]

bb

[control z]

[control z]

 

Modification of the above program:

while((ch=getchar()) != EOF)

{ if (ch!= ‘\n‘ && ch!=‘ ‘ && ch!=‘\t‘)

{ if (scanf("%d %d", &rows, &cols) != 2)

break;

display(ch, rows, cols);

}

}

 

Without space skipping, the input line will look like the following:

b 1 2 c 3 5

Menu browsing

 

Enter the letter of your choice:

a. advice b. bell

c. count d. quit

Goals

1) The program works well when the user follows instruction

2) The program works well when the user fails to follow instruction

 

The getchoice () function

pseudo code:

show choices

get response

while response is not acceptable, prompt for more response

get response

int getchoice()

{ int ch;

printf("Enter the letter of your choice:\n ");

printf("a. advice b. bell \n ");

printf("c. count d. quit \n ");

ch = getchar();

while(ch<‘a‘ || ch>‘d‘)

{ printf("Please respond with a, b, c, or"

" d.\n ");

ch = getchar();

}

return ch;

}

Problem: Every newline generated by the enter key is treated as an erroneous response.

Solution: Use getfirst() function. It reads the first character on a line and discard the rest.

int getfirst()

{ int ch;

ch = getchar();

while(getchar() != ‘\n‘)

;

return ch;}

Ex: Menu browsing program.

#include <stdio.h>

void main (void)

{ int choice;

int getchoice(void);

void count();

while ((choice=getchoice()) != ‘d‘)

{ switch(choice)

{ case ‘a’: printf("Buy low, sell high\n");

break;

case ‘b’: putchar(‘\7’);

break;

case ‘c’: count();

break;

default: printf("Program error");

break; }

}

}

void count(void)

{ int n, i ;

printf("Count how far? Enter an integer: \n");

if(scanf("%d", &n) != 1)

{ printf("Please use digits next time, this " "time ");

printf("I will use the integer 5\n");

n=5; }

 

for(i=1; i<=n; I++)

printf("%d\n", I);

while(getchar()!=‘\n’)

; /* discard newline, bad input */

}

 

 

Chapter 9

Functions

Frequently asked questions about functions:

1) Can I call a function more than once?

2) Can one function contain calls to another?

3) Can a function contains more than one statement?

4) Can a function contains call to itself?

 

Major points to know about functions

Function Prototyping (ANSI):

is a function declaration that specifies the data types of the argurments, the return type, and the number of arguments

int imax ( int, int);

int imax ( int a, int b);

Traditional C:

 

int imin ( ) ;

It does not say anything about the number or type of arguments that this function requires.

These names are dummy names and don’t have to match the names used in the function definition

1) Function Definition & Declaration

 

The syntax of the function header is shown below.

[storage class] [return type] function name ([formal parameter list])

{

:

:

}

Ex:

 

int sample(char ch, float num);

extern float func_1(void);

void nxt_sample(int num);

- Storage Class: the optional "storage class" specifies the function’s storage class, which must be either "static" or "extern". If the storage class is omitted the default is extern.

- If the storage class is specified as "static" the function is visible only to the source file in which it is defined. All other function whether they are given extern storage class explicitly or implicitly are visible throughout the source files that make up the program.

- The optional "return-type" and mandatory "function name" together specify the function return type and name. If no return type is specified the compiler assumes type int.

- The function definition must match the return type in the declaration of the function elsewhere in the program.

2) Calling a function from the main() program, it returns to the next line of the calling program.

Ex:

result = function_1();

printf("%d", function_1());

Ex:

#define SPACE ‘ ‘

#define NAME "John"

Sample (SPACE, 65); or Sample (‘ ‘, 65);

Sample (SPACE, strlen(NAME));

3) Creating a function

 

Ex: ANSI C

int function_1(char ch, int num)

{ declare local variables

:

body of the function

:

}

Ex: K&R C

int function_2(ch, num)

char ch;

int num;

{

declare local variables

:

body of the function

:

}

Formal arguments: are declared before the brace that marks of the body of the function.

4) you can include main() and function_1() in the same file or two separate files.

- Single file is easier to compile.

- Two separate files make it simpler to use the same function in different programs

Returning a value from a function

Use keyword return followed by a variable to send it back to the calling function.

- you can enclose the return value in parentheses for clarity if it’s not required.

- return , terminates the function returns control to the next statement in calling function.

extern int min(int n, int m)

{ int min;

if (n < m ) or if (n < m )

min=n; return (n);

else else

min=m; return (m);

return min;

}

Ex: Function () generation and calling

 

#include <stdio.h>

extern int imax (int x, int z);

void main (void)

{ printf ("The maximum of %d and %d is %d.\n",3,5,

imax(3));

printf ("The maximum of %d and %d is %d.\n",3,5,

imax(3,5));

}

int imax (n, m) or extern int imax(int n, int m)

int n,m;

{ int max;

if (n > m)

max = n;

else

max=m;

return max;

}

Ex: user’s defined function

#include <stdio.h>

int power (int a, int b);

void main(void) {

int base, exponent, result;

printf("Raise what number to a power?");

scanf("%d", &base);

printf("what is the integer exponent?");

scanf("%d", &exponent);

result=power(base,exponent);

printf("%d to the power %d is %d.\n", base, exponent, result);

}

int power (int base, int exponent)

{ int I, result = 1;

for (I=0; I<exponent; I++)

result = result * base;

return (result);

}

Example A: the following example defines a function named function_1 which has the following specifications:

storage class : defaults to extern

return type : defaults to int

parameter list : void, meaning no paramter is

passed to this function from the calling function

visibility : all source files that make up the program

function_1(void)

{

int num1 = 1, num2=2;

return(num1+num2);

}

 

Example B: the following example defines a function named function_2

which has the following specifications:

storage class : extern

return type : float

parameter list : 2 integer paramters are passed

to this function from the calling function

visibility : all source files that make up the program

extern float function_2(int i, int j)

{

return((float)(i+j));

}

 

Ex) Another user define function

#include <stdio.h>

int total(int cur, int end);

void main (void)

{ int beg, end;

printf("Enter beginning ending: ");

scanf("%d %d", &beg, &end);

printf("Total: %d\n", total(beg, end));

}

int total(int cur, int end)

{ int count, tot=0;

for(count=cur; count<=end; ++count)

tot+=count;

return tot;

}

Output

Enter beginning ending: 3 10

Total: 52

 

wpe12.gif (1355 bytes)Back to top

 

WEEK TWELVE

 

 

Macros: A #define directive that uses arguments is called a "macro".

Macros:

#define PI 3.141592 is called define directive

#define is: preprocessor directive

PI is: the phrase to be searched for "identifier"

3.141592 is: the phrase to replace it with "text"

#define ERROR printf("\n ERROR. \n");

 

if (input > 20) or if (input > 20)

ERROR printf("\nERROR.\n");

 

 

Ex: Using macros in a program.

#include <stdio.h>

#define PR(n) printf ("%.2f\n",n)

void main (void)

{ /* PR(n): an argument n: identifier*/

/* PR (num1) : cause the variable num1 to be subsituted for n.*/

float num1 = 27.25;

float num2;

num2= 193.0;

PR(num1);

PR(num2);

}

/*PR (num1) <=> printf("%.2f\n",num1);*/

output

27.25

193.00

#define PR(n) printf ("%.2f\n",n);

Ex: Another example of macros

/*Calculate area of a sphere */

#include <stdio.h>

#define PI 3.14159

#define AREA (x) (4*PI*x*x) /*macro for area of sphere*/

void main(void)

{ float radius;

printf("Enter radius of sphere: ");

scanf("%f", &radius);

printf("Area if sphere is %.2f",AREA(radius));

}

the preprocessor will subtitute the text

AREA (radius) = (4*3.14159*radius * radius)

Use of parentheses in Macros

#define SUM (x,y) x+y

:

ans = 10 * SUM ( 3,4);

ans = 10 * 7 = 70 wrong

ans = 10*3+4

= 30+4=34

- For safety’s sake, put parentheses around the entire text of any define directive that uses arguments and also around each of the argument.

Macros and Functions

Macros and function can actually perform many of the same tasks .

When to use macros

A macro generates more code but executes more quickly than a function .

The #include directive

Causes one source file to be included in another.

Suppose you write a lot of math-oriented program. Place all the equations as macros, in a single separate file.

#define PI 3.141592

#define KONST 345

:

:

#define SCALE 0.5

When you write your a program that needs to use these formulas, you simply include the directive #include "areas.h" at the begining of your program.

The following causes the preprocessor to start searching for the areas.h file in the directory containing the current source file.

#include <area.h>

The following format causes the preprocessor to start searching in the standard header directory.

The & operator: when followed by a variable name, & gives the address of that variable.

 

Ex:

 

home = 15915; /*unsigned decimal integer*/

printf("%d %u\n", home, &home);

Output:

 

15915 address(some address in memory)

%p displays the address in hexadecimal form (in turbo C on a pc)

Ex: Altering variables in the calling program.

#include <stdio.h>

int void interchange(int,int);

void main (void)

{ int x=5, y=10;

print("originally x = %d and y = %d. \n", x, y);

interchange (x, y);

print("Now x = %d and y = %d.\n", x, y);

}

 

void interchange(int u,int v) /* define function*/

{ int temp;

printf("Originally u = %d and v = %d. \n", u,v);

temp = u;

u = v;

v = temp;

printf("Now u = %d and v = %d. \n", u, v);

}

Output:

Originally x = 5 and y = 10

Originally u = 5 and v = 10

Now u = 10 and v = 5

Now x = 5 and y = 10

To send the return value back to the calling program:

return(u); and change

x=interchange(x, y); change declaration to int interchange( )

Note: with return you can send just one value back to the calling program

Pointers

are symbolic repressentation of addresses.

- &home is a pointer_to_home, actual address is a number (Hex number) the symbolic representation &home is a pointer constant.

- C has pointer variables which has an address as a value

ptr = &home /*assigns home’s address to ptr*/

To create a pointer variable

indirection operator, *: when followed by a variable, it gives the value stored at the pointed_to address.

 

Ex:

home = 14914;

ptr = &home;

Val = ptr;

Val = 14914

Declaring pointers

 

int *home; /*points to an integer variable*/

float *pi; /*points to a float variable*/

char *ch; /*points to a character variable*/

Declaring and using pointers

Ex: Using pointers to communicate between functions.

#include <stdio.h>

void interchange(); or void interchange(int *u,int *v);

void main(void)

{ int x = 5, y = 10;

printf("Originally x = %d and y = %d.\n ", x, y);

interchange(&x,&y);/*send addresses to function*/

printf("Now x = %d and y = %d.\n",x, y);

}

 

 

void interchange(u,v) or interchange(int *u,int *v)

int *u, *v;

{ int temp;

temp = *u;

*u = *v;

*v = temp;

}

output

Originally x = 5 and y = 10

Now x = 10 and y = 5

 

Ex: Use of pointers.

#include <stdio.h>

void gets(int *px, int *py);

void main(void)

{ int x, y;

gets(&x, &y);

}

void gets(int *px, int *py)

{ *px = 3;

*py=5;

}

 

 

#include <stdio.h>

void main ( void )

{ int x = 4 , y = 7;

int *px , *py;

printf("x is %d, y is %d. \n", x, y);

px = &x;

py = &y; /*put address of numbers in pointers */

*px = *px + 10;

*py = *py +10;

printf("x is %d, and y is %d.\n",x, y);

}

x is 4, y is 7

x is 14, y is 17.

*px is the contents of ptr

&var is the address of var

Recursion: two programs call each other.

#include <stdio.h>

extern void more(void);

void main(void)

{ char ch;

printf("Enter any character you want.");

printf("A Q will end things.\n");

ch = (char) getchar();

printf("Aha! That was a %c!\n", ch);

if(ch != ‘Q‘)

more( );

}

 

extern void more(void)

{

main();

}

output

Enter any character you want A Q will end things.

A <cr>

Aha! That was a A!

Enter any character you want A Q will end things.

Aha! That was a <--prints newline

!

Enter any character you want A Q will end things.

Q <cr>

Aha! That was a Q!

Recursion: To find factorial

n! = n x (n-1) x ( n-2) x (n-3)x......x 3 x 2 x 1

5! = 5 x 4 x 3 x 2 x 1 = 120

#include <stdio.h>

extern int factorial(int n);

void main(void)

{ int n, result;

print("Find the factorial of what?\n");

scanf("%d",&n);

result = factorial(n);

printf("the factorial of %d is %d\n", n, result);

}

extern int factorial(int n)

{

if(n ==1)

return(1);

else

return(n*factorial(n-1));

}

 

 

WEEK THIRTEEN

 

REVIEW

EXAMINATION #2

 

 

wpe12.gif (1355 bytes)Back to top

 

WEEK FOURTEEN

 

Chapter 10

Pointers and Arrays

 

Pointers and Arrays

The compiler translates array notation into pointer notation when compliling, since the internal architecture of the microprocessor understands pointers but does not understand arrays.

Ex: One dimensional array.

/*array C */

#include <stdio.h>

void main (void)

{ static int nums [5] = {92, 81, 70, 60, 58};

int dex;

for (dex = 0; dex < 5; dex ++)

printf("%d\n",nums [dex]);

}

output

92

81

70

60

58

Now modify the previous program by using pointer notations:

print("%d\n", *(nums + dex);

if dex=3 => nums[3] == 60

*(nums + dex)

nums + dex = 1400 + 3 * 2 = 1406

 

number of bytes per integer

*(nums + dex)

&nums[dex]

&nums[2] == (nums +2) == 1404

nums[2] == *(nums + 2) == 70

 

Ex: Use of poiter notations in the previous program.

#include <stdio.h>

void rets2(int *px, int *py)

void main(void)

{ int x, y;

rets2(&x, &y);

printf("First is %d, Second is %d.",x, y);

}

 

void rets2(int *px, int *py)

{

*px = 3 ;

*py = 5 ;

}

 

Output

First is 3, Second is 5

Pointers to Arrays in functions

#include <stdio.h>

#define SIZE 5

void addcon(int *ptr, int num, int con);

void main(void)

{ static int array[SIZE] = {3,5,7,9,11};

int konst = 10;

int j;

addcon(array, SIZE, konst);

for(j=0, j < SIZE, j++)

printf("%d", *(array+j));

}

void addcon(int *ptr, int num, int con)

{ int k;

for(k=0; k<num; k++)

*(ptr)=*(ptr++) + con;

}

Output

13 15 17 19 21

 

Examples of arrays & pointers

{ static int arr[3] ={4,5,6};

int j;

for(j=0; j<3; j++)

printf("%d", arr[j];

}

Ex:

{ static int arr[3] = {4,5,6};

int j, *ptr;

ptr=arr;

for(j=0; j<3; j++)

printf("%d", *ptr++); 4, 5, 6

 

Two-dimensional Arrays & Pointers

 

 

char name[i][j];

...

Sample(name);

Sample(int *name[j])

{...}

Pointer notation vs. bracket notation

 

Given the following declarations and initialization:

 

int a[5], *ptr;

ptr = a;

*(a+3)=10;

*(ptr+3)=10; They are all the same, but use different notations.

a[3]=10;

ptr[3]=10;

We can also have (ptr is a pointer variable)

 

ptr = a;

ptr += a;

*ptr = 10;

in this case, ptr itself is modified, since array name a is constant, not a variable, we can’t say a += 3.

Why pointers?

Array version:

 

x = ptr [I++]

1) Fetch the content of I.

2) Multiply it by the size of one object-pointed-to store the result in anonymous scratch variable

3) Then, increment I and put it back.

4) Fetch the content of ptr

5) Then add the results of the multiply to it.

6) Finally, fetch the contents of the memory whose address was just computed, and put it into x.

* 3 - fetches and one multiply

Pointer version:

x = *ptr++

1) Fetch the contents of ptr.

2) Fetch the object at that address and put it into x.

3) Add to ptr the size of an object-pointed-to.

4) Store the result of the addition in ptr.

* 2 - fetches and no multiplication

Pointers and strings: Searches string for a given character

#include <stdio.h>

#include <string.h>

#include <conio.h>

void main(void)

{ char ch, line[81], *ptr;

puts("Enter the sentence to be searched:");

gets(line);

printf("Enter Character to Search for:");

ch = getch();

ptr = strchr(line, ch);

printf("\n String starts at address %u \n",line);

printf("first occurance of char is address "

"%u.\n",ptr);

printf("this is position %d (starting from 0)",ptr-line);

}

Output:

Enter the sentence to be searched:

The quick brown fox jumped over the lazy dog. <cr>

Enter Character to Search for: <cr>

String starts at address 65424

first occurance of char is address 65442.

this is position 18 (starting from 0)

*Strchr(): returns a pointer to the first occurrence of a particular character in a string.

ptr = strchr(str,’x’);

- strcmp(string1, string2)

returned value

meaning

less than zero

string 1 less than string 2

zero

string 1 identical to string 2

greater than zero

string 1 greater than string 2

 

Ex:

strcmp("A","A")=>0 strcmp("A","B")=>-1

strcmp("B","A")=>1 strcmp("apples","apple")=>1

Ex:

#include <stdio.h>

#include <string.h>

#define MAX 5

void main(void)

{ int dex;

int enter =0;

char name[40];

static char *list[MAX] = { "Katrina", "Nigel","Alistair", "Francesca",

"Gustar"};

printf("Enter your name:");

gets(name);

for (dex=0; dex < MAX; dex++)

if(strcmp(list[dex], name) == 0)

enter=1;

if(enter == 1)

printf("you may enter, Oh honored one.");

else

printf("Guards! Remove this person!");

}

 

Output:

Enter your name:Andy

Guards! Remove this person!

Enter your name:Katrina

you may enter, Oh honored one.

An array of strings

An array of string is really an array of arrays, or a two-dimensional array.

Ex: An array of strings

#include <stdio.h>

#include <string.h>

#define MAX 5

#define LEN 40

void main(void){

int dex;

int enter = 0;

char name[40];

static char list[MAX][LEN] = {"Katrina", "David", "Steve", "Sue",

"Lee"};

printf("Enter your name: ");

gets(name);

for(dex = 0; dex < MAX; dex ++)

if (strcmp(&list[dex][0], name) == 0)

enter =1;

if(enter == 1)

printf("You may enter, it is in the list.");

else

printf("It is not in the list!");

}

Output:

Enter your name: James

It is not in the list!

Enter your name: Lee

You may enter, it is in the list.

 

- strcmp(&list[dex][0], name) == 0

The difference between arrays and pointers

Pointer version takes up less space in memory; it ends at 1038, while the array version ends at 1049

To obtain greater flexibility in the manipulation of the strings in the array.

Manipulating pointers to strings

This program accepts a series of names typed in by the user, places them in an array, and sorts them pointers to the array so that, in effect, the names are rearranged into alphabetical order.

#include <stdio.h>

#include <string.h>

#define MAXNUM 30

#define MAXLEN 81

void main(void)

{ static char name[MAXNUM][MAXLEN];

char *ptr[MAXNUM]; /*array of ptrs to strings*/

char *temp;

int count=0;

int in, out;

 

while (count < MAXNUM)

{ printf("NAME %d: ", count+1)

gets(name[count]);

if(strlen(name[count])== 0)

break; /*quit if no name*/

/*each ptr points to name*/

ptr[count++] = name[count];

}

for (out = 0; out < count-1; out++)

for(in = out +1; in < count; in ++)

if (strcmp(ptr[out],ptr[in])>0)

{ temp = ptr[in];

ptr[in] =ptr[out];

ptr[out]=temp;

}

printf("‘In sorted‘ list:\n");

for (out = 0; out < count; out ++)

printf("Name %d: %s \n", out +1, ptr[out]);

}

Input List

NAME 1: Baker

NAME 2: Bakers

NAME 3: John

NAME 4: Smith

NAME 5: Al

NAME 6: Pacino

NAME 7: Steve

NAME 8: <cr>

'Sorted' list:

Name 1: Al

Name 2: Baker

Name 3: Bakers

Name 4: John

Name 5: Pacino

Name 6: Smith

Name 7: Steve

An example of pointer

 

#include <stdio.h>

int data[2]={100, 300};

int moredata[2]={100, 300}

void main(void)

{ int *p1, *p2, *p3;

p1= p2=data;

p3= moredata;

printf("%d %d %d\n",*p1++,*++p2, (*p3)++);

printf("%d %d %d \n", *p1, *p2, *p3);

}

output

100 300 100

300 300 101

 

 

wpe12.gif (1355 bytes)Back to top

 

 

WEEK FIFTEEN

 

 

The pointer operators * and ++ have the some precedence but associate from right to left.

Pointers and two-dimensional arrays (double indirection)

-The name of the array is pointer to its first element

int zippo[m][n]=*(*(zippo+m)+n)

zippo[0] == &zippo[0][0] == *zippo

zippo[1] == &zippo[1][0] == *(zippo+1)

zippo[2] == &zippo[2][0] == *(zippo+2)

zippo[3] == &zippo[3][0] == *(zippo+3)

 

Applying the * operator to each gives the following results

*z[0] == z[0][0] == **z

*z[1] == z[1][0] == *(*(z+1))

*z[2] == z[2][0] == *(*(z+2))

*z[3] == z[3][0] == *(*(z+3))

The following 2 program show how arrays, pointers and addresses relate to each other.

Ex: arrays and addresses

#include <stdio.h>

void main (void)

{ int zippo[4][2];

printf("zippo = %u, zippo[0] = %u \n"

"&zippo[0][0]=%u, ", zippo, zippo[0], &zippo[0][0] );

printf("*zippo=%u\n", *zippo);

}

Output

zippo = 3512, zippo[0] = 3512

&zippo[0][0] = 3512, *zippo = 3512

Ex: More arrays and address

#include <stdio.h>

void main (void)

{ int zippo[4][2];

printf("zippo = %u, zippo[0] = %u \n"

"&zippo[0][0]=%u, ", zippo, zippo[0], &zippo[0][0] );

printf("*zippo=%u\n", *zippo);

printf("zippo+1=%u, zippo[0]+1=%u\n", zippo+1, zippo[0]+1);

printf("&zippo[0][0]+1=%u, *zippo+1=%u\n",&zippo[0][0]+1, *zippo+1);

printf("*(zippo+1)=%u\n", *(zippo+1));

}

output

zippo = 3512, zippo[0] = 3512

&zippo[0][0] = 3512, *zippo = 3512

zippo+1=3516, zippo[0]+1=3514

&zippo[0][0]+1=3514, *zippo+1=3514

*(zippo+1)=3516

 

Function and multi-dimension array

There are 3 ways to pass multi-dimensional arrays to a function:

1) use a function written for one dimensional arrays on each subarray.

2) use the same function on the whole array, but treat the whole array as one dimensional instead of 2

dimensional.

3) use a function that explicitly deals with 2 dimensional arrays.

Ex: Passing a two dimensional array to a function ().

#include <stdio.h>

#define MODELS 2

#define COLORS 3

extern void print_inv(short inv[][COLORS]);

void main(void)

{ short inv[MODELS][COLORS]={{46,12,122},{62,20,88}};

print_inv(inv);

}

 

extern void print_inv(short inv[][COLORS])

{ int model, color;

printf(" RED GREEN PUCE\n");

for (model = 0; model < MODELS; ++model)

{ if (model == 0)

printf("STANDARD ");

else

printf("DELUXE ");

for (color = 0; color < COLORS; ++color)

printf("%6hi ", inv[model][color]);

printf("\n");

}

}

Array Notation:

Ex: Manipulating Two dimensional arrays .

#include <stdio.h>

#define ROW 4

#define COL 5

void main(void)

{ static int table[ROW][COL] = { { 1, 2, 3, 4, 5}, { 6, 7, 8, 9, 10},

{ 11, 12, 13, 14, 15}, {16, 17, 18, 19, 20} };

int konst = 10;

int j, k;

for(j = 0; j < ROW; j++)

for(k=0; k < COL; k++)

table[j][k] = table[j][k]+konst;

for(j=0; j < ROW; j++)

{ for(k=0; k<COL; k++)

printf("%d ", table[j][k]);

printf("\n");

}

}

 

Pointer Notation

 

:

for(j=0; j < ROW; j++)

for(k=0; k<COL; k++)

*(*(table+j) + k) = *(*(table+j)+k) + konst;

An element of a two-dimenstional array can be referenced with a pointer to a pointer.

 

 

Chapter 11

Character Strings and String Functions

 

Defining strings within a program

Whenever the compiler encounters something enclosed in double quotation marks, it recognizes the pharse as a string constant. The enclosed characters, plus a terminating ‘\0’ character automaticallly provided by the compiler, are stored in adjacent memory locations.

Ex:

1) ‘X‘, ‘x‘, ‘E‘ => these are character

2) "X", "x", "E" => these are string

3) "Hello there." => these are string

 

Compiler treats them as

1) X , x , and E => w/o \0 as null char.

2) X\0 , x\0 , and E\0 => with \0 as null char.

3) Hello there.\0 => with \0 at the end of string.

 

Array and Pointer differences

We can examine the differences between initializing a character array to hold a string and initializing a pointer to point to a string. Keep in mind that by pointing to a string, the pointer is pointing to the first character of a string.

Ex:

1) Declaring a constant pointer:

static char heart[] = "I love Tillie!";

2) Declaring a variable pointer:

char *head = "I love Tillie!";

Points to remember

- Both can use pointer addition:

for (i=0; i<6; i++) for(i=0; i<6; i++)

putchar(*(heart+i)); putchar(*(head+i));

putchar(‘\n‘); putchar(‘\n‘);

- Only pointer version can use the increment/decrement operator:

while(*(heart)!=‘\0‘) while(*(head)!=‘\0‘)

putchar(*(heart++));(err) putchar(*(head++));(OK)

putchar(‘\n‘); putchar(‘\n‘);

- head can points to heart but not vice versa:

head = heart; (OK) heart = head; (error)

- You can alter heart message by going into the array itself:

heart[7]=‘X‘ *(heart+7)=‘X‘

Note: elements of an array are variables, but the name of an array is a constant.

 

Arrays of character strings

Sometimes it is convenient to have an array of character strings. Then you can use a subscript to access several different strings:

#define LIM 5

static char *mytal[LIM] = {"Adding together",

"Multiply accurately", "Stacking data",

"Follow instruction", "Understand clearly"};

You can see that mytal is an array of five pointers to char. That means under mytal, you have 5 pointers which are pointing to character. The first pointer is mytal[0], and it points to the first character of the first string. The second pinter is mytal[1], and it points to the beginning of the second string.

*mytal[0]==‘A‘, *mytal[1]==‘M‘, *mytal[2]==‘S‘

The initialization follows the rules for arrays. The braced portion is equivalent to

{{...},{...}, ..., ..., {...}};

for which the first set of double quotation marks corresponds to brace-pair and thus is used to initialize the first character string pointer. The next set of double quotation marks initializes the second pointer, and so on. A comma seperates neighboring sets.

We can be explicit about the size of the character strings by using a declaration like:

#define LIM 5

#define LINLIM 30

static char mytal[LIM][LINLIM];

The difference is that the last one is set up as a "rectangular" array with all the rows the same length. The first declaration:

#define LIM 5

static char *mytal[LIM];

sets up a "ragged" array, with each row’s length determined by the string it is initalized to. The ragged array doesn’t waste any storage space.

Pointer to strings

Most C operations for strings actually work with pointers. For example: consider the useless, yet instructive, program in the following example.

Ex: Pointers and strings.

#include <stdio.h>

void main (void)

{ char *mesg = "Don’t be a fool!";

char *copy;

copy = mesg;

printf("%s\n", copy);

printf("mesg=%s; value=%u; &mesg=%u\n",mesg,mesg,

&mesg);

printf("copy=%s; value=%u; &copy=%u\n",copy,copy,

&copy);

}

Output

Don't be a fool!

mesg=Don't be a fool!; value=404; &mesg=65498

copy=Don't be a fool!; value=404; &copy=65500

value is the value of the specified pointer, which is the address it contains. Therefore, we see that mesg points to location 14, and so does copy. In other words, the string itself is never copied. All that copy = mesg; does is produce a second pointer that points to the same string.

 

String output

ANSI C recognizes 3 standard functions for printing strings: puts(), printf(), and fputs(). Note that fputs() is file oriented and is describe in Chapter 12.

Ex: Another example of poiters and strings.

#include <stdio.h>

#define DEF "I am a #define string."

void main (void)

{ static char str1[]="Array is initialized to me.";

char *str2 = "A pointer was initialized to me.";

puts("I’m an arguments to puts(). ");

puts(DEF);

puts(str1);

puts(str2);

puts(&str1[4]);

puts(str2+4);

}

Ouput

I’m an argument to puts().

I am a #define string.

Array is initialized to me.

A pointer was initialized to me.

y is initialized to me.

inter was initialized to me.

 

The puts() function stops accepting characters for output when it encounters the null char. When puts() finally finds the closing null character, it replaces it with a newline characetr and then sends the string on.

 

Main function arguments

The command line is the line you type in to run your program. Suppose we have a program in a file named count. The command line may look like:

% count => in UNIX

C:\> count => in DOS

$ count => in VAX/VMS

 

Command line arguments are additional items on the same line.

Traditionally, the formal parameters are called

argc -- argument count

argv -- argument vectors

 

argc: is the first argument to main and it is an integer value that specifies the number of argument typed

on the command line.

argv: is the second argument to main and it is an array of pointers to char.

 

 

 

Old Style Prototype Style

void main(argc,argv) void main(int argc,char *argv[])

int argc; {

char *argv[]; :

{ }

:

}

 

Ex:

c:\tc>count 2 text 25 C_book <cr>

 

 

What the program gets from this command line:

argc = 5

argv[0] = "c:\tc\>count.exe"

argv[1] = "2"

argv[2] = "text"

argv[3] = "25"

argv[4] = "C_book"

Ex: Command line arguments.

#include <stdio.h>

void main(int argc, char *argv[])

{ int counter;

printf("The number of arguments you entered is: %d\n", argc);

for(counter=0; counter < argc; counter++)

printf("Argument number %d: is %s\n", counter, argv[counter]);

}

C:\TC\> mystuff one two three

 

 

output:

The number of arguments you entered is: 4

Argument number 0: is C:\TC\> mystuff.exe

Argument number 1: is one

Argument number 2: is two

Argument number 3: is three

 

wpe12.gif (1355 bytes)Back to top

 

WEEK SIXTEEN

 

 

 

 

Chapter 12

FILE input/output

C sees a file as a sequence of bytes, each of which can be read individually.

Text File

 

Information are stored as strings. MS-DOS text files represent the end of a line with the carriage

return and line feed combination:\r\n

Binary file

 

Each byte of the file is accessible to a program. Binary view is more efficient way of storing

information.

ANSI C

Provides both a binary and a text view but these views can be implemented identically.

 

- In text view of a file, a C program converts \n to \r\n when writing to a file.

- Unix: both views are the same for unix implementations.

Levels of I/O:

low-level I/O - unbuffered, you can create your own buffer within a program.

Number storage in text formal

Binary mode and text mode

 

How numbers are stored?

How files are opened?

C originated on UNIX system and used UNIX file convention. MS-DOS, evolved separately from UNIX, has its own, somewhat different, conventions.

Text mode-------> UNIX files

Binary mode------> MS-DOS files

Differences

1) The handling of newlines and the representation of end-of -file.

text mode: newline------------>CR/LF combination

Binary mode: no translation

2) the way end-of-file is detected.

Text mode

- A special character 1A hex (26 decimal), inserted after the last character in the file, to indicate EOF. (EOF == -1).

- If a file stores numbers in binary format, it’s important that binary mode be used in reading the file back, since one of the numbers might well be 1A.

Standard I/O: buffered

Advantages of standard I/O over low-level I/O

1) The buffer speed up the program considerably.

2) It has many specialized functions for handling various I/O problems.

3) It is part of the ANSI standard library, thus providing a highly portable solution to I/O programming

needs.

Ex: How to open a file.

#include <stdio.h>

void main(void)

{ FILE *file_pointer; /*this is the file pointer*/

file_pointer = fopen("myfile.dta", "W");

/*creates a file called myfile.dta and assign its

address to the file ptr to the file pointer*/

fclose(file_pointer);

}

- fopen() function: to open a file

- "W": the file will be opened for writing into it.

- fclose(): built-in C to close the file once you opened it. It flushes buffers as needed.

The getc ( ) and putc( ) functions

ch = getc(fp); means get a character from the file identified by fp

putc(ch, fp); means put the character ch into the file identified by the File pointer fp.

 

Mode String

Means

"r"

open text file for reading

"w"

open text file for writing

"a"

open text file for writing, appending to the end of existing file, or creating file if it does not yet exist

"r+"

open text file for update, that is, for both reading and writing

"w+"

open text file for update, first truncating file to zero length if it exists or creating file if it does not yet exist.

"a+"

open text file for update (reading or writing), appending to the end of existing file, or creating file if it does not yet exist; the whole file can be read, but writing can only be appended.

"rb","wb",...

for binary mode

 

fprintf(fp, "%f", num)

Example: the creation and opening of the same file ex(1), but this time the character C is put into the file

add: putc(‘c’, file_pointer);

you now have a file called Myfile.DTA that contains the character C.

Ex: Reading data from a disk file.

#include <stdio.h>

void main (void)

{

FILE *file_pointer;

char file_character;

file_pointer = fopen ("myfile.dta", "r");

file_character = getc(file_pointer);

/*get the first letter from the opened file*/

printf("The character is %c\n", file_character);

fclose(file_pointer);

}

Input:

Hello world! (inside myfile.dta)

Output:

The character is H

Ex: Saving a character string, the user may input any string of characters from the keyboard and have them automatically saved to a file called myfile.dta.

#include <stdio.h>

#include <conio.h>

void main(void)

{ FILE *file_pointer;

char file_character;

file_pointer = fopen("myfile.dta", "w");

/*put a stream of characters into the file*/

while((file_character = getc(stdin)) != ‘\n‘)

putc(file_character, file_pointer);

fclose(file_pointer);

}

Input:

Hello world! <cr> (from keyboard)

Output:

c:\>type myfile.dta

Hello world!

Reading a character stream

The concept of a character stream is a sequence of bytes of data being sent from one place to another (such as from computer memory to the disk).

Ex: Open a file for reading.

#include <stdio.h>

void main(void)

{ FILE *file_pointer;

char file_character;

file_pointer = fopen("myfile.dta", "r");

while((file_character=getc(file_pointer))!=EOF)

printf("%c", file_character);

fclose(file_pointer);

}

Input

This is from myfile.dta (inside myfile.dta)

Output

This is from myfile.dta

The exit() function causes the program to terminate, and closing any open files.

Ex: Counting character: a program that counts the characters in a file .

#include <stdio.h>

#include <stdlib.h>

void main(int argc, char *argv[])

{ FILE *fptr;

int count = 0;

if ( argc !=2) /*check # of args*/

{ printf("format: c>prog filename");

exit(1); }

if ((fptr = fopen(argv[1],"r")) == NULL)

{ printf("can’t open file %s.",argv[1]);

exit(1); }

while (getc(fptr)!= EOF)

count++;

fclose(fptr);

printf("File %s contains %d characters.",argv[1], count);

}

Input:

C:\>prog myfile.dat<cr>

this is from myfile.dta (inside myfile.dta)

Output

File myfile.dta contains 23 characters.

We have used a command-line argument to obtain the name of the file to be examined, rather than writing it into the fopen( ) statement.

Ex: This program reads the data from the keyboard, then writes it to a "textfile.txt" file.

#include <stdio.h>

void main(void)

{ FILE *fp;

char name[40];

int code;

float height;

fp = fopen("textfile.txt", "w");

do

{ printf("Type name, code number, and height:");

scanf("%s %d %f", name, &code, &height);

fprintf(fp, "%s %d %f\n", name, code, height);

}

while(strlen(name)>1);

fcolse(fp);

}

 

Input:

Type name, code number, and height: Bond 7 5.10<cr>

Type name, code number, and height: James 8 5.9<cr>

Type name, code number, and height: x 0 0<cr>

Output (from textfile.txt):

Bond 7 5.100000

James 8 5.900000

x 0 0.000000

 

 

Modify this program to read the data from the file and print them out.

:

fp = fopen("textfile.txt", "r");

while(fscanf(fp,"%s %d %f",name,&code,&height)!= EOF)

print("%s %03d %.2f\n", name, code, height);

fclose(fp);

:

 

#include <stdio.h>

#include <stdlib.h>

#define MAX 20

void main(void)

{ FILE *fp;

char words[MAX]

if((fp=fopen("words", "a+")) == NULL)

{fprintf(stdout,"can’t open \"words\" file.\n");

exit(); }

puts("Enter words to add to the file, type the "

"enter");

puts("Key at the begining of a line to "

"terminate.");

while(gets(words)!=NULL && words[0]!=‘\0’)

fprintf(fp,"%s", words);

puts("File contents:")

rewind(fp);

while(fscanf(fp,"%s", words)== 1)

puts(words);

fclose(fp);

}

c>addaword

 

Enter words...

Key...

See the canoes <cr>

[enter]

 

File contents:

See

the

canoes

C>addaword

 

Enter words...

Key...

on the

sea

[enter]

 

File contents:

See

the

canoes

on

the

sea

FILE I/O access

- sequential access: processing the file content in order

- random access: accessing the contents in any desired order.

The fprintf( ) and fscanf( ) functions

- They work just like printf( ) and scanf( ), except that they require an additional argument to point to

the proper file. This argument is the first in the argument list.

fprintf(stdout, "can’t open words file.\n");

fprintf(fp,"%s", words);

 

The fgets( ) and fputs( ) functions

- The fgets( ) function takes three arguments, whereas the gets( ) take only one.

fgets(pointer_to_char,

integer that presents the upper limit to

the size of the input string,

the final arguments is the file pointer

that identifies the file to be read.)

Ex:

fgets(name, 80,fp)

Random access: fseek( ) and ftell( )

fseek(): let’s you directly access any byte in a file opened by fopen( ).

fseek() has three arguments and return an int value.

- The first of the three fseek argument is a FILE pointer to the file being searched.

- The second argument is called the offset, which tells us how far to move from the starting point(must be long value)(+,-)

- The third argument is the mode, and it indentifies the starting point.

Mode Measure offset form

Seek_Set Beginning of file

Seek_Cur Current position

Seek_End End of file

Ex:

fseek(fp, Count, Seek_End); /*go backward*/

 

#include <stdio.h>

#define MAXLINE 20

void main(void)

{ char line[MAXLINE];

while(fgets(line,MAXLINE,stdin)!=NULL && line[0]!=‘\n’)

fputs(line, stdout);

}

Output:

It is spring. <cr>

It is spring.

The hills are green and The sea is sparkling <cr>

The hills are green and The sea is sparkling

<cr>

- fgets() reads first 19 character through n in green.

- fgets() reads the newline and places it in the first element of array.

- gets() discards the newline and you test it with ‘\0’.

- Like gets(), fgets returns the value NULL when it encounters EOF. This

features lets you check the end of file.

- Unlike puts(), fputs() does not append a new line when it prints.

 

 

Ex: A program to open a file for reading and writing.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

void main (void)

{ FILE *fp;

char string[81];

/*create file for writing*/

if((fp=fopen("myfile.txt", "w"))==NULL)

{ printf("Cannot create data file\n");

exit(1);

};

while(strlen(gets(string)) > 0)/*get input from keybd, so long >0*/

{ fputs(string, fp); /*write into the file*/

fputs("\n", fp); /*append each string with new line*/

}

fclose(fp); /*close data file*/

fp=fopen("myfile.txt", "r"); /*open file for reading*/

while(fgets(string, 80, fp) != NULL) /*read up the end of file*/

printf("%s", string); /*print each line it reads*/

fseek(fp, 0, SEEK_SET); /*set file pointer to the beginning*/

fgets(string, 80, fp); /*read only the first line*/

printf("%s", string); /*and print it*/

fclose(fp); /*close data file*/

}

Output:

University of Houston <cr>

College of Technology <cr>

4800 Calhoun Rd. <cr>

Houston, Texas 77204 <cr>

See you all next semester! <cr>

<cr>

 

 

More Examples

/* How to read numbers from one file and write them to another file*/

#include <stdio.h>

#include <stdlib.h>

void main (void)

{ FILE *fp1, *fp2;

char fname[80];

float num1, num2, num3;

int i=0;

printf("Enter the name of your data file: ");

scanf("%s", fname);

if((fp1 = fopen(fname, "r")) == NULL)

{ printf("Can't open file: %s\n", fname);

exit(1);}

if((fp2 = fopen("output.dat", "w")) == NULL)

{ printf("Can't create data file\n");

exit(1);}

while(fscanf(fp1, "%f %f", &num1, &num2) != EOF)

{ i++;

num3 = (num1 * num2) / (num2 + num1);

printf("Writing set #: %d => %.3f\n", i, num3);

fprintf(fp2, "%3d) %f \t %f \t => \t %f\n", i, num1,

num2, num3);

}

fclose(fp1);

fclose(fp2);

printf("Finish processing data file\n\n");

}

Output:

Enter the name of your data file: input.txt <cr>

Writing set #: 1 => 0.935

Writing set #: 2 => 48.196

Writing set #: 3 => 50.060

Writing set #: 4 => 21.266

Writing set #: 5 => 0.082

Writing set #: 6 => 2.276

Finish processing data file

Content of input.txt

1.2 4.234

56.7 321.34

56.23 456.23

34.2 56.23

0.1 0.45

3.04 9.05

Content of output.dat after running this program:

1) 1.200000 4.234000 => 0.935002

2) 56.700001 321.339996 => 48.195900

3) 56.230000 456.230011 => 50.060127

4) 34.200001 56.230000 => 21.265797

5) 0.100000 0.450000 => 0.081818

6) 3.040000 9.050000 => 2.275600

/* How to read strings from one file and write them to another file*/

#include <stdio.h>

#include <stdlib.h>

void main (void)

{ FILE *fp1, *fp2;

char fname[80];

char first[20], last[80];

int i=0;

clrscr();

printf("Enter the name of your data file: ");

scanf("%s", fname);

if((fp1 = fopen(fname, "r")) == NULL)

{ printf("Can't open file: %s\n", fname);

exit(1);}

if((fp2 = fopen("output.dat", "w")) == NULL)

{ printf("Can't create data file\n");

exit(1);}

while(fscanf(fp1, "%s %s", first, last) != EOF)

{ i++;

printf("Writing set #: %d => %s %s\n", i, first,

last);

fprintf(fp2, "%3d) %s \t %s \n", i, last, first);

}

fclose(fp1);

fclose(fp2);

printf("Finish processing data file\n\n");

}

Output:

Enter the name of your data file: name.txt

Writing set #: 1 => Al Pacino

Writing set #: 2 => Robert Wayne

Writing set #: 3 => James Smith

Writing set #: 4 => Andy Calhoun

Finish processing data file

Content of name.txt:

Al Pacino

Robert Wayne

James Smith

Andy Calhoun

Content of output.dat after running this program:

1) Pacino Al

2) Wayne Robert

3) Smith James

4) Calhoun Andy

 

 

University of Houston

College of Technology

4800 Calhoun Rd.

Houston, Texas 77204

See you all next semester!

University of Houston

 

 

wpe12.gif (1355 bytes)Back to top

 

 

TIME PERMITTING

Chapter 14

Structures

 

Structure

A structure consists of a number of data items-which need not be of the same type-grouped together.

Ex:

#include <stdio.h>

struct easy

{ int num;

char ch;

};

void main(void)

{ /*declares ‘ez1‘ to be of type "struct easy"*/

struct easy ez1;

ez1.num = 2; /*reference elements of ‘ez1‘*/

ez1.ch = ‘z‘;

printf("ez1.num=%d, ez1=%c\n", ez1.num, ez1.ch);

}

output

ez1.num = 2, ez1.ch = z

The structure consists of three parts

1) How to set up a template for a structure type

2) How to declare a variable to fit that template

3) How to gain access to the indvidual components of a structure variable

 

 

1) setting up the structure template

struct easy

{ int num;

char ch;

};

we can declare the tag later as following

struct easy ez1;

A structure is a data type whose format is defined by the programmer.

 

2) Declaring structure variables

struct easy ez1;

which declares ez1 to be a structure of the easy type this statement does set aside space in memory.

3_bytes: two for integer and one for character

struct easy{

int num;

char ch;

}ez1; /*follows template with variable name*/

without a tag

struct{

int num;

char ch;

}ez1;

3) Accessing structure elements

The "dot operator"(.); which is also called the "membership operator."

ez1.num ---> specific element in the structure.

|

-->structure’s name

ez1.num = 2;

ez1.ch = ‘z‘

The dot operator(.) connects a structure variable name with a member of the structure.

employee.salary is more comprehensible than employee[27].

Initializing a structure.

many pre-ANSI implementation limit initialization to external or static structure variables. The important point is where the variable is defined.

Ex: struct easy ez1={2, ‘z‘};

Multiple structure variables of the same type

Ex:

#include <stdio.h>

struct easy

{ int num;

char ch;

};

 

void main(void)

{ struct easy ez1;

struct easy ez2;

ez1.num = 2;

ez1.ch = ‘z‘;

ez2.num = 3;

ez2.ch = ‘y‘;

printf("ez1.num=%d, ez1.ch=%c\n",ez1.num,ez1.ch);

printf("ez2.num=%d, ez2.ch=%c\n",ez2.num,ez2.ch);

}

Output

ez1.num=2, ez1.ch=z

ez2.num=3, ez2.ch=y

Combining Declarations

struct easy

{ int num;

char ch;

}ez1, ez2;

Entering Data into Structure

Ex:

#include <stdio.h>

struct personnel

{ char name[30];

int agnum;

};

void main(void)

{ struct personnel agent1;

struct personnel agent2;

char numstr[81];

printf("\nAgent 1.\n Enter name: ");

gets(agent1.name);

printf("Enter agent number (3 digits): ");

gets(agnum);

agent1.agnum = atoi(numstr);

printf("\n Agent 2. \n Enter name: ");

gets(agent2.name);

print("Enter agent number (3 digit): ");

gets(numstr);

agent2.agnum = atoi(numstr);

printf("\n list of agents: \n");

printf(" Name:%s\n", agent1.name);

printf(" Agent number: %3d\n",agent1.agnum);

printf(" Name: %s\n", agent2.name);

printf(" Agent number: %3d\n", agent2.agnum);

}

 

atoi ( ): stands for "ASCII to integer"

- This function takes a string as an argument and returns an integer with the same value (less memory).

Agent1

Enter name: Harrison Tureenbury

Enter agent number (3 digit):102

Agent2

Enter name: James Bond

Enter agent number (3 digit): 007

List of agents:

Name: Harrison Tureenbury

Agent number 102

Name: James Bond

Agent number 007

 

 

Arrays of structure

 

struct book

{ char title[100];

char author[100];

float value;

};

 

Declaring an array of structure:

struct book libry[100];

 

Identifying Members of a Structure array

 

libry[0].value the value associated with first array element.

:

libry[5].title the title associated with sixth array element.

libry.value[2] is wrong.

libry[2].title[4] it’s the fifth element in the title(title[4]) of the

book described by the third structure(libry[2]).

 

wpe12.gif (1355 bytes)Back to top

 

© Copyright Laws Apply

Website designed by Dr. Heidar Malki and Chuck Umeh

University of Houston