Sie sind auf Seite 1von 77

rt Microsoft Visual C++ 6.0

nu: Datei -> Neu

->

Projekte: Win32 – Konsolenanwendung

Projektname: type in your project name, e.g. hello

Pfad: check the file path of your directory OK oose: eine einfache Anwendung tigstellen

orkingspace (leftmost middle window):

Choose: Dateien, not Klassen Click + of hello Dateien and + of Quellcode Dateien Double-click of hello.cpp ource window (rightmost middle window):

Edit the source file hello.cpp

nu: Erstellen

->

hello.exe erstellen

Read the messages in the bottom window. Errors?

Yes:

make corrections to the source;

No:

clicking the error message moves the cursor to the line. execute

nu: Erstellen

->

Ausführen von hello.exe

finish working this project:

nu: Datei

->

Click: Ja

Arbeitsbereich schliessen

open an existing project:

nu: Datei

->

Arbeitsbereich öffnen

Double-click on the directory, e.g. hello

Double-click on the file hello.dsw Start working again.

specify compile-options use Menu: Projekt

gistercard: C/C++

->

Einstellungen

debugging:

Kategorie: Allgemein Optimierungen: Deaktivieren (Debug)

optimization:

Kategorie: Allgemein Optimierungen: Geschwindigkeit erhöhen Kategorie: Optimierungen Optimierungen: Anpassen Check all the wanted features, e.g. Float-Konsistenz verbessern Schnellen Code bevorzugen Vollständige Optimierung

specify runtime-options use Menu: Projekt

->

Einstellungen

gistercard: Debug

mplete the following lines:

eitsverzeichnis

name of the directory of the input- and output-files

grammargumente

e.g. redirection arguments, like < input_file > output_file

handling

e Menu: Projekt

->

Dem Projekt hinzufügen

->

u

A window will open up: Dateien

->

Textdatei

Complete the file name, e.g. input.txt and type the contents.

eien:

One can choose an existing file which will be added to the project.

nning a program – within Visual C++

e Menu: Erstellen

->

Ausführen

with stdin and stdout are handled within an execution window. Enter EOF by way o

l z on a separate line.

run a program (without or with debugging) under redirection, complete the respect s in Registercard: Debug (s. page 5).

urious phenomenon

example, input is read from a file and output is written to a file. Before terminating program writes “Press any key to continue“ to stdout (which is bound to a file and be seen on this moment) and creates an execution window to receive the answer m stdin. Hitting any key will then terminate the program, after the above sentence w ten into the output file.

nning a program – outside Visual C++

to Start

->

Programme

->

Eingabeaufforderung

e DOS-commands dir (list files) and cd (change directory) to find the directory executable, e.g.

MyFiles\

\count\Debug

with executable

the directory of input and output files, e.g.

MyFiles\

\count

with input file

n run the program in this directory:

count.exe

words.txt

ug\count.exe < words.txt > output.txt

ad the output file with:

more < output.txt

bugging a project: be sure that the debug option is set!

nu: Erstellen

->

Debug starten

Ausführen In Aufruf springen Aufruf als ein Schritt Ausführen bis Rücksprung Ausführen bis Cursor

akpoints can be set by:

execute until breakpoint execute one line or stop at entry of function execute the function entirely execute until return statement execute until cursor in source window

Right mouse click menu in left bar of source window -> Haltepunkt Menu: Bearbeiten -> Haltepunkte

lowing actions can be executed:

Haltepunkt einführen/löschen create/delete a breakpoint

Haltepunkt entfernen Haltepunkt deaktivieren Haltepunkt aktivieren

delete a breakpoint inactivate a breakpoint activate an inactivated breakpoint

bugging

debug session is started, one can use the debug switch panel (activated by right mouse click) or Menu: Debug, or Debug Window; this can be activated by Menu: Extras Registercard: Symbolleisten; here one must check: Debug

->

Anpassen

ve the cursor over variable names to get little windows with their values.

ra information windows with Menu: Ansicht

->

Debug-Fenster

->

erwachung

tracing

rufliste

call hierarchy

eicher

memory addresses

iablen

variables with values

gister

contents of registers

assemblierung

disassembly

bugging

re are two extra windows with variable names and their values:

at left the variables-window with Auto, Lokal and this at right the tracing-window with Überwachung: one can change values!

nu: Debug

->

Schnellüberwachung

Possibility to see and change values of variables.

->

Variable is added into watch-window.

Zur Überwachung hinzufügen

re are more options under:

Menu: Extras

->

Anpassen

Menu: Extras

->

Optionen

ndow-management

ome windows are badly arranged or have disappeared:

Menu: Fenster -> Nebeneinander Menu: Ansicht -> Debug-Fenster -> choose your window Click on symbolpanel “Arbeitsbereich“ to toggle the window “Arbeitsbereich“, which appears in the middle left. Click on symbolpanel “Ausgabe“ to toggle the window “Ausgabe“, which appe in the lower part of the Visual C++-Window.

cution Window

s can be enlarged the following way:

right mouse click on upperbar

registercard Layout

click OK click “Eigenschaften gelten für alle Fenster mit gleichem Namen“ and OK

->

Eigenschaften

->

adjust the values in “Fenstergröße“

w commands – see also http://hlrwm.rhrk.uni-kl.de/home/kursunterlagen/Einfuehrung _in_

command

action

example

pwd

print working directory

pwd

mkdir

make directory

mkdir src

cd

change directory

cd

src

cd

rmdir

remove directory

rmdir src

ls

list filenames

ls

-al

cp

copy file

cp

oldfile newfile

mv

move file

mv

oldfile newfile

rm

remove file

rm

file

more

list file

more file

less

list file

less file

tor

nedit

with e.g. keywords highlighting indentation

 

ompiler

cc

IBM

File-Suffix

.c

gcc

GNU project

+-Compiler

xlC

IBM

File-Suffix

.C

g++

GNU project

ions: see manpages.

ice: use xlC or g++ with .C-files, also for C-sources.

mark:

with the command lpr –Pd21asc filename one can use the non-PS printer in Dialograum 1

oke the compiler:

hello.C –O3 hello.C hello.C

–g –o hello.exe hello.C

rt program:

ut

or

./a.out

-> executable a.out -> optimized executable a.out -> debugging executable a.out -> executable hello.exe

direction of stdin (keyboard), stdout (screen) and stderr (screen):

ut < input_filename > output_filename 2> error_filename

headerfiles, like stdio.h, are to be found in the directory /usr/include

ir contents, for example definitions of macros and prototypes of functions, can be d with e.g.

e /usr/include/stdio.h

bugging with GUI

xldb

IBM

ddd

University of Braunschweig

rmation with the Help features.

- ddd

rting the debugger:

ddd a.out

run the program click Run: look at the output in the lower part of the window.

o

o

read input from stdin and write to stdout one can activate the menu Program in Execution Window and then click Run: an additional window will open u

o halt the program at certain lines one must activate breakpoints: right mouse clic he line to be investigated.

o investigate values: mark the variable name in the source text and use the right use button.

o input EOF in stdin, use Ctrl d

read from files and write into files activate Program -> Run Run with arguments (without quotes).

marks:

Hit the F1 button to get position sensitive help. Apply the menu View -> Command Tool. The ddd debugger is not very robust!

and complete t

- xldb

rting the debugger:

xldb a.out

o run the program click Continue.

o read input from stdin and write to stdout one uses the window in which the ugger was started.

o halt the program at certain lines one must activate breakpoints: left mouse click line to be investigated.

o input EOF in stdin, use Ctrl d

read from files and write into files start

db a.out < input_filename > output_filename

most important windows are for: local variables, global variables, source code, akpoints and commands. t mouse click the icon to activate the window or the upper bar of the corresponding dow to activate the window control.

X

tor

nedit

with e.g. keywords highlighting, indentation

xemacs

ditto

ompiler

cc

SGI

File-Suffix

.c

gcc

GNU project

+-Compiler

CC

SGI

File-Suffix

.C

g++

GNU project

ions: see manpages.

ice: use CC or g++ with .C-files, also for C-sources.

mark: cost-free printing with the command lpr –Pd21asc filename

X - cvd

rting the debugger:

d a.out

see output to stdout and to read input from stdin uniconify Execution Window. input EOF in stdin, use Ctrl d

ad in the desired source by specifying the name of the source file in the Source nue. Activate the wanted breakpoints: left mouse click in the line to be investigated is is denied, start (Run button) the program and stop (Stop button) it. Use the ws menue to open the Variable Browser and the Array Browser.

read from files and write into files, complete the line Command in the usual way hout quotes).

ply the menu Admin with submenue Load/switch to Executable witch to a newly compiled program.

evelop

s is a convenient environment for developing C- and C++-programs on PCs with ux.

more information, see the URL http://www.kdevelop.org

+-Builder

s is a convenient environment for developing C- and C++-programs on PCs with dows.

://www.steckenborn.de/ in the SSL-program:

ndard

v5.0

DM 149,-

fessional

v5.0

DM 259,-

s://rhrk.asknet.de/ im Katalog – Borland:

ndard

v5.0

DM 149,-

fessional

v6.0

DM 249,-

.

Run the “hello, world“ program of Ch. 1.

Leave out or add things, to find out about error messages.

Change the argument of the function printf and experiment with escape sequences like \a, \b, \n, \r, \t, \\, \?, \‘, \“, \077, \x77

.

Run the example program 1 of Ch. 3, using the printf function.

Run it using cout

What happens when you replace the string endl by “\n“ or ‘\n‘ ?

.

Run the example program 2 of Ch. 3.

Read the description of printf (manpage or Kernighan&Ritchie § 7.2 or use th Help function) and try some formats.

What to do, if you want to print the % character?

Try to replace the call to the printf function by a statement applying cout.

.

Run the example program 3.1 of Ch. 3, which will display a Fahrenheit to Celsius table.

Write a program to print the corresponding Celsius to Fahrenheit table.

Rewrite the program with the help of the for statement:

for (expr1; expr2; expr3) statement

expr1:

expr2:

expr3:

starting point of the iteration; after having been executed expr2 will be executed; a conditional expression; being true statement will be executed being false the iteration is stopped and the program continues AFTER statement; after statement has been executed, expr3 is executed, usually updating the iteration variable;

AFTER statement; after statement has been executed, expr3 is executed, usually updating the iteration variable;
AFTER statement; after statement has been executed, expr3 is executed, usually updating the iteration variable;

statement: one statement or a block of statements within braces, being the loop body.

.

Run the example program 5 of Ch. 3, counting the characters in the input.

Modify it to count blanks, tabs and newlines in the input.

.

Run the example program 7 of Ch. 3

Modify it to count digits, white space (e.g. blank, tab and newline) and others (as a group). Use for the digits an array ndigit[10] so that ndigit[0] counts the zeros, ndigit[1] the ones, etc. Replace the if statements with if (c >= ‘0‘ && c <= ‘9‘)

++ndigit[c - ´0´];

/* Why does this work? */

else if (c == ‘ ‘ || c == ‘\n‘ || c == ‘\t‘) ++nwhite; else ++nother;

Take care of the printing.

.

te a program that will compute your Body Mass Index and that of at least two othe ple. The BMI is the mass in kilograms divided by the square of the height in meter derweight is defined by BMI < 18.5 and overweight by BMI > 24.9. Please do NOT upset if your BMI is not within the range of normal weight [18.5, 24.9].

e arrays of appropriate length for the weights, heights and BMI’s. Read in the value the weights and heights. If you use the function scanf please be sure to use nters as arguments. If the array types are float use the conversion specification if they are double use %le.

te the results in a nice tabular form.

te also a table of heights in the range [1.60, 2.05] with steps of 0.05 meters showin corresponding weights for underweight and overweight. Use symbolic constants f se:

fine UNDERWEIGHT 18.5 fine OVERWEIGHT 24.9

.

Run the example program 9 of Ch. 3, which will print the longest input line. Use as input some textfile with the name-suffix .txt or create one with the program Editor (Windows) or nedit (UNIX). Write into a file, e.g. output.txt Compare the contents of the input file with that of the output file. What happens when all lines have the same lengths? What happens when there are trailing blanks and tabs? What happens when the input line has a length longer than the value of MAXLINE

Write a function remove() to remove trailing blanks and tabs from an input line. Adapt the function main() so that the program will read in lines, pass them to th function remove() and have them printed. Take care that entirely blank lines ar not printed. Hints: Assume that the value of MAXLINE is large enough that the character arra will be sufficiently long for the entire input line inclusive the ‘\n‘. Assume also that the EOF-character is at the beginning of a line.

Modify the function getline() so that it can read arbitrary long lines. All characters read in excess as to the number provided for by the value of MAXLINE should be discarded, except an eventual ‘\n‘. Do not forget the string terminati character.

.

Write a function reverse(s) that reverses the character string s without applying the function strlen as in the example of Ch. 5.

Adapt the example program 9 of Ch. 3 and use the function reverse(s) to writ program that reverses its input a line at a time. If you use the unmodified function getline() be sure to have lines short enoug to fit into the character array. Otherwise apply the modified function of Solution 3.9.

.

te a program detab that replaces left-aligned tabs in the input with the proper num lanks to space to the next tab stop. Assume a fixed set of tab stops, say every n umns. Should n be a variable or a symbolic constant?

ra information: if a left-aligned tab stop is at column M, the next character will be itioned in column M+1.

t: Use the functions getchar() and putchar() as used in Ch. 3 Example 4.

.

lain the validity of the function atoi(s).

atoi: convert a string s to an integer atoi(char s[])

int i, n = 0; for (i = 0; s[i] >= ‘0‘ && s[i] <= ‘9‘; ++i) n = 10 * n + (s[i] – ‘0‘); return n;

te a program that will read strings with digits and will output the corresponding ger values.

te a function htoi(s), which converts a string of hexadecimal digits (including ional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through rough f, and A through F.

.

blo invests EUR 100,- at 10% simple interest. That is, every year, the investment ns 10% of the original investment, or EUR 10,- each year:

rest = 0.10 * original balance

he same time Zhenni invests EUR 100,- at 5% compound interest. That is, interes of the current balance, including previous additions of interest:

rest = 0.05 * current balance

nni earns 5% of EUR 100,- the first year, giving her EUR 105,-. The next year she ns 5% of EUR 105,-, or EUR 5,25, and so on.

te a program that finds how many years it takes for the value of Zhenni‘s investme xceed the value of Pablo‘s investment and then displays the value of both estments at that time.

.

te a program that prints the sizes of all basic data types and all corresponding poin

es. example for the type int the corresponding pointer type is int*.

e the sizeof operator

eof (type-name)

elds the number of bytes required to store an object of the type. It returns a value

e size_t defined as unsigned integer, so that the appropriate conversion charact

e used in printf is

u.

ine the following enumeration type

m day {SUN = 1, MON, TUE, WED, THU, FRI, SAT}

at is the length of this type and of the corresponding pointer?

.

n the program and discuss the results.

main()

int i; short n; unsigned short m;

n = pow(2,15) - 10;

for (i = 1; i < 20; ++i) {

n += 1;

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

}

m

= pow(2,16) - 10;

for (i = 1; i < 20; ++i) {

m += 1;

printf(" m = %u \n", m);

}

return 0;

Do not forget:

#include "stdafx.h" //only V

#include <stdio.h>

#include <math.h>

Remark: In the compile command t option -lm must be supplied to lin with the mathematical library.

.

te a program that will read two strings of text, and then compares them character f racter. It should output the result of one string being smaller or greater than or equ he other one.

ine a comparing function strcmp1 which will be passed two strings which are pared lexicographically as in a dictionary: e.g. “aaa“ < “aaaa“, “ab“ < “ac“, aa“ < “x“. e the fact that the letters in the ASCII set are ordered lexicographically. Consider ers of upper or lower case only.

function should return the value:

when the strings are identical, when the first string is less than the second one, in the other case.

nsider several pairs of strings in sequence (use a loop) and find a neat way to minate the loop.

This function read

ut fields which are defined as strings of non-white space characters. Hence the ngs will not contain blanks, horizontal tabs, newlines, carriage returns, vertical tabs formfeeds.

reading the two strings use a call to scanf("%s%s",

).

.

te a program that will read two strings of text and an integer number k. It should ert the second string at position k of the first one. The program should output the dified string and also its length.

ine a function insert1 which will be passed two strings and an integer. Use the ction strlen() declared in the header file string.h to find the lengths of the ngs. First move the part of the first line that is displaced by the insertion, then inser second string (without its Null-byte) onto its place of the first line.

This function read

ut fields which are defined as strings of non-white space characters. Hence the ngs will not contain blanks, horizontal tabs, newlines, carriage returns, vertical tabs formfeeds.

reading the two strings use a call to scanf("%s%s",

).

.

te a program that will read two strings of text, and then takes away any character m the first string appearing in the second one. It should output the modified string a o its length.

ine a function squeeze1(s1, s2) that deletes each character in s1 that match character in the string s2.

e cin and cout for input resp. output. The object cin reads input fields whic defined as strings of non-white space characters. Hence the strings will not contai nks, horizontal tabs, newlines, carriage returns, vertical tabs and formfeeds.

te a similar program handling whole lines, which contain white-space characters.

t: Use the getline() function as it was modified in Solution 3.9.

.

ve the following:

igned char i = 1;

<= 3;

/* i := 8 */

>= 2;

/* i := 2 */

= 5;

/* i := 7 */

= 3;

/* i := 3 */

= 5;

~i;

/* i := 6 */ /* i := 249 */

.

ve that getbits(x, 4, 3) returns from the word x the three bits in positions 4 2. Bit position 0 is at the right end.

getbits: get n bits from position p (right adjusted) */ igned getbits(unsigned x, int p, int n)

return (x >> (p+1-n)) & ~(~0 << n);

.

te a function setbits(x, p, n, y) that returns x with the n bits that begin at ition p set to the rightmost n bits of y, leaving the other bits unchanged.

.

write the following function with a conditional expression instead of if-else.

lower: convert c to lower case; ASCI only */ lower(int c)

if (c >= ´A´ && c <= ´Z´) return c + ´a´- ´A´; else return c;

.

ine a function binom(n, k) with return value type double and two integer ameters. It calculates the binomial coefficient n over k, which is the number of way hoosing k objects from a collection of n distinct objects without regard to order.

e this function to calculate and print the binomial coefficient of two integer values, e probability of getting 6 right out of 49 (Lotto): binom(49, 6)

t: The binomial coefficient n over k is defined by

/ ((n-k)! * k!)

ch can be calculated by

k+1) * (n-k+2) * (n-k+3) *

* n / (1 * 2 * 3 *

* k)

products usually are so big that one needs to define the result value to be of type ble.

.

e a switch to write a function escape(s, t) that converts characters like newlin tab into visible escapes like \n and \t as it copies the string t to s.

.

ell invented in 1959 a sort algorithm. Explain why it is so efficient.

shellsort: sort v[0]

v[n-1]

d shellsort(int v[], int n)

int gap, i, j, temp;

into increasing order */

for (gap = n/2; gap > 0; gap /= 2) for (i = gap; i < n; i++) for (j = i-gap; j >= 0 && v[j] > v[j+gap]; j -= gap) { temp = v[j]; v[j] = v[j+gap]; v[j+gap] = temp;

}

.

te a function expand(s1, s2) that expands shorthand notations like a-z in the

ng s1 into the complete list abc

be prepared to handle cases like a-b-c and a-z0-9 and -a-z. Arrange that a leadin railing - is taken literally.

xyz

in s2. Allow for letters of either case and digit

.

te a version of itoa (Example page 15 Ch. 6) that accepts three arguments ead of two. The third argument is a minimum field width; the converted number m padded with blanks on the left if necessary to make it wide enough.

.

te a program that reads integers from a stream of input into an integer array, e.g.

–456

#23##98 into 12 23 98

-456+789 into 123

789

given function getint performs free-format input conversion by breaking a am of characters into integer values, one integer per call.

he given function getint has a flaw, since it does not jump over characters bei

digits, EOF, a plus or minus sign. Modify getint aviour.

to get the above described

What happens with a + or a – not followed by a digit? Modify the function to have it ore a + or a – not followed by a digit.

efine a function getfloat to handle floating-point numbers (no exponential par make it easy assume that there is at least one digit to the left of the decimal point.

.

following version of getint returns EOF for end of file, zero if the next input is umber, and a positive value if the input contains a valid number. A pointer argume sed to store the converted integer back in the calling function.

clude <stdio.h> clude <ctype.h>

getch(); d ungetch(int);

getint: get next integer from input stream into *pn */ getint(int *pn)

int c, sign;

while (isspace(c = getch()))

;

// skip white space

.

if (!isdigit(c) && c != EOF && c != '+' && c != '-') {

}

ungetch(c); return 0;

/* it is not a number */

sign = (c == '-') ? -1 : 1; if (c == '+' || c == '-') c = getch(); for (*pn = 0; isdigit(c); c = getch()) *pn = 10 * *pn + (c - '0'); *pn *= sign; if (c != EOF) ungetch(c); return c;

.

fine BUFSIZE 100

r buf[BUFSIZE]; bufp = 0;

/* buffer for ungetch */ /* next free position in buf *

getch: get a (possibly pushed back) character */ getch()

return (bufp > 0) ? buf[--bufp] : getchar();

ungetch: push character back on input */

d ungetch(int c)

if (bufp >= BUFSIZE)

printf("ungetch: too many characters\n");

else

buf[bufp++] = c;

.

te a pointer version of the function strcat(s, t): it copies the string t to the e

.

strcat: concatenate t to end of s; s must be big enough */ d strcat(char s[], char t[])

int i, j; i

=

j

=

0;

while (s[i] != ´\0´)

i++; if (s[i-1] == ´\n´) i--;

while ((s[i++] = t[j++]) != ´\0´)

;

// find end of s

// overwrite NL

// copy t

.

te a program that will read two strings of text. It should check whether the second ng occurs at the end of the first one.

ine a function strend(char *s, char *t) which will be passed two strings. rns 1 if the string t occurs at the end of the string s, and zero otherwise. In the ction body only pointer handling is allowed.

dify this program, that it will read the two strings from the command line.

.

ve a look at the values of pointers relevant to the two-dimensional matrix a define

a[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

te a program that will print the values of some of the pointers and dereferenced nters.

cuss the difference between a + 1 and a[1] on one hand and 1] on the other hand.

*(a + 1) a

.

mples pages 43/44 Ch. 7

day_of_year and month_day

There is no error checking in day_of_year or month_day. Provide for this.

Rewrite these functions with pointers instead of indexing.

te a program that will apply these functions. Read in the necessary data.

.

nsider Exercise 4.3 again. Rewrite the function strcmp1 so that it will handle nters only:

strcmp1(char *s1, char *s2)

{

}

.

nsider Exercise 4.4 again. Rewrite the function insert1 so that it will handle nters only:

insert1(char *s1, char *s2, int n)

{

}

.

ine a function strcpy1(char *s, char *t) which will be passed two strings ies string t onto string s. It returns as a value the address of the NULL byte in t tination string s with the type pointer to char. In the function body only pointer dling is allowed.

te a program that will copy the strings “Hallo, you “ and “guys“ after one ther into one character array. It should print the result.

.

sider Exercise 3.11 again. Write a program detab to accept a list of tab stops as argumen

ab 23 51

the default settings if there are no arguments.

function detab must be modified to replace the characters ‘\t‘ with the appropiate ber of spaces until a tab stop is reached.

ne a function settab which will define the tab stops in an array called tab. Each element array corresponds with a position of the (maximal) input line, having the value true for a tab and the value false otherwise. Use the function atoi to convert the command line uments to integers (header file stdlib.h).

the UNIX environment:

o have the name polish1 for the executable (per default a.out) use the compiler option

olish1

nclose operators like * by double quotes. Everything enclosed this way is passed unchanged shell to the underlying program (the double quotes are stripped off). Otherwise * is interprete wildcard.

.

te a program that will create a two-dimensional matrix with ROW rows and COL umns of type double. Initialize it with values of your choice, or alternatively, assi itrary values to it. Do not use malloc in this case.

ine a function matrix_max_1 with the prototype ble matrix_max_1(double [][COL], int, int *, int *) hich the first parameter designates a two-dimensional array and the second one ses the number of rows (ROW). The other parameters are pointers used for passin k the indices of the element with the biggest value, which itself will be returned by ction value.

ewise define a function matrix_max_2 with the prototype d matrix_max_2(double *, int, double **) t will receive the beginning address of the matrix and the total number of elements third parameter is used for passing back the pointer to the element with the bigge ue.

main there should be provisions (for both cases!) for printing the indices of the ment with the biggest value as well as this value itself.

.

te a program that will create a pointer matrix of type double with row rows and

l columns, which values are to be input. Assign arbitrary values to the matrix ments.

ine a function matrix_max with the prototype d matrix_max(double **, int, int, int *, int *)

t will receive the beginning address of the pointer matrix and the number of rows a umns. The pointers are used for passing back the indices of the element with the gest value.

main there should be provisions for printing the indices of the element with the gest value as well as this value itself.

.

nsider the following definitions:

r

*asia[] = { "India", "Pakistan", "China", "Singapore" };

r

*europe[] = { "Bulgaria", "Poland", "Germany" };

r

**continents[] = { asia, europe };

ermine type and value of the following expressions:

tinents, continents + 1, ntinents, **continents, continents, continents[1], tinents[1][2], continents[1][2][4], ntinents[1], (*continents)[1], continents)[1], **continents[1]

.

py the program of the reverse Polish calculator and make it run.

clude <stdio.h> clude <stdlib.h>

fine MAXOP 100 fine NUMBER

'0'

getop(char []); d push(double); ble pop();

/* for atof() */

/* max size of operand or operator */ /* signal that a number was found */

reverse Polish calculator */ check it with e.g. 1 2 - 4 5 + * (Polish notation) */ the answer should be -9 */ main()

.

int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER:

push(atof(s)); break; case '+':

push(pop() + pop()); break; case '*':

push(pop() * pop()); break; case '-':

op2 = pop(); push(pop() - op2); break;

.

case '/':

op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor\n"); break; case '\n':

printf("\t%.8g\n", pop()); break; default:

printf("error: unknown command %s\n", s); break;

}

}

fine MAXVAL

.

100

sp = 0; ble val[MAXVAL];

/* maximum depth of val stack */

/* next free stack position */ /* value stack */

push: push f onto value stack */ d push(double f)

if (sp < MAXVAL) val[sp++] = f; else printf("error: stack full, can't push %g\n", f);

.

pop: pop and return top value from stack */ ble pop()

if (sp > 0) return val[--sp]; /* remember: p is free stack position */ else { printf("error: stack empty\n"); return 0.0;

}

.

clude <ctype.h>

getch(); d ungetch(int);

getop: get next operator or numeric operand */ getop(char s[])

int i, c;

while ((s[0] = c = getch()) == ' ' || c == '\t')

;

s[1] = '\0'; if (!isdigit(c) && c != '.') return c;

/* not a number */

.

i = 0; if (isdigit(c))

/* collect integer part */

while (isdigit(s[++i] = c = getch()))

;

if (c == '.')

/* collect fraction part */

while (isdigit(s[++i] = c = getch()))

;

s[i] = '\0'; if (c != EOF) ungetch(c); return NUMBER;

.

fine BUFSIZE 100

r buf[BUFSIZE]; bufp = 0;

/* buffer for ungetch */ /* next free position in buf *

getch: get a (possibly pushed back) character */ getch()

return (bufp > 0) ? buf[--bufp] : getchar();

ungetch: push character back on input */

d ungetch(int c)

if (bufp >= BUFSIZE)

printf("ungetch: too many characters\n");

else

buf[bufp++] = c;

.

Add the modulus (%) operator: use the function fmod(x, y) of the math library for double variables x and y. Information: man fmod Add provisions for negative numbers. Hint: modify the function getop()

Add commands (i.c. operators) to print the top element of the stack without poppin to duplicate it, and to swap the top two elements. Add a command to clear the stack. Hint: write a function that will do this. Modify the original program so as to add access to math library functions like sin(x), exp(x) and pow(x, y) for double variables x and y. Write a function ungets(s) that will push back an entire string onto the input. Should it know about buf and bufp, or should it just use ungetch?

mark: The functions like fmod, sin, exp and pow are declared in the file h.h. In the compile command the option –lm must be supplied to link with the thematical library.

.

te a program polish1 which evaluates a reverse Polish expression from the mand line, where each operator or operand is a separate argument. For example

polish1 12 3 4 + *

luates 12 * (3 + 4). Use the two arguments to the function main to read the ression (see Chapter 7 p. 31-33). You may use all functions you need from Solutio , especially the function ungets. Use it to store the read arguments in the stack m which the function getop will fetch them.

the UNIX environment:

o have the name polish1 for the executable (per default a.out) use the piler option: -o polish1

Enclose operators like * by double quotes. Everything enclosed this way is passed hanged by the shell to the underlying program (the double quotes are stripped off) erwise * is interpreted as a wildcard.

pp

.

te a program to concatenate files: copy the program of the following pages.

Compile the code and have it run. Modify the program so that the file of the last filename will receive the contents of the preceding files. If there are no filenames, copy stdin to stdout. If there is one filename, copy stdin into this file. Count the characters copied. After that this number passes a certain value, finish t copying of the actual file and then terminate. Print the names of the files copied an of those not copied to stdout.

pp

.

clude <stdio.h> cat: concatenate files and output them to stdout */ main(int argc, char *argv[])

FILE *fp;

void filecopy(FILE *, FILE *);

if (argc == 1)

filecopy(stdin, stdout); else while (--argc > 0) if ((fp = fopen(*++argv, “r“)) == NULL) { printf(“cat: can´t open %s\n“, *argv); return 1; } else { filecopy(fp, stdout); fclose(fp);

/* no args; copy standard input */

}

pp

.

filecopy: copy file ifp to file ofp */ d filecopy(FILE *ifp, FILE *ofp)

int c;

while ((c = fgetc(ifp)) != EOF) fputc(c, ofp);

pp

.

te a program to copy the contents of one file to another file. Read in the names of s, open one for reading and the other for writing. Take care of error situations.

Apply fscanf and fprintf with %c-format. Apply fgets and fputs with a character array.

pp

.

te a program to compare two files, printing the first line where they differ. Read in t mes of the files. Take care of error situations.