Übungsblatt 02 Angabe WS1718 PDF

Title Übungsblatt 02 Angabe WS1718
Course Informatik 1 für Ingenieurwissenschaften (MSE)
Institution Technische Universität München
Pages 9
File Size 209.1 KB
File Type PDF
Total Downloads 25
Total Views 182

Summary

Übungsblatt 02 Angabe WS1718, die Tutorien orientieren sich an diesen Aufgaben....


Description

Technische Universit¨ at M¨ unchen

Institut f¨ ur Informatik WS 2017/2018 Exercise 2 3rd November 2017

MSE IN8011 Prof. B. H. Menze, Dr. K. Shi

Exercise 2 - I/O and Control Flow 2.1 Basic source file structure Following we show you the general structure of source code. You’ve discussed this already in the lecture, but we’ll go over this again quickly here, as you’ll be asked to do it in your assignment. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / // The fil e u su a ll y b eg in s w ith a s ec ti on c o ns is t in g of th e l ib r ar ie s // we nee d to i nc lu d e in our p ro gr am . Li br ar i es p ro vi de fu n ct i on a li t y // tha t the C la ng u ag e d oe sn ’t p ro vi de by i ts el f . In th is case , we // inc lud e st di o .h , w hi ch p ro vid es ba si c inp ut / o ut pu t fu nc ti ons fo r // C ( li ke pr in tf and ge ts ) , whi ch you ’ ll use in your a s si g nm en t . /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / # i nc lu de < std io .h > /* * * *

" m ain " is the en tr y po in t to y ou r p ro gra m : W he n the o per at in g s ys te m st ar ts e xe c ut in g the pro gra m , th is fu n ct io n is be ing c al le d . An e xe cut ab le C p rog ram s ho uld a lw ays p os ses s a " main " f un ct io n . We ’ll ge t to w hat ar gc a nd a rgv me an la ter in th is co ur se . */

int ma in ( int argc , cha r ** a rgv ) { /* /* /* /* /*

It is o ft en us ef ul to d ec la re y our v ar i ab le s all in on e pl ac e . If y ou do , th is is c al le d a de c la ra t io n s ec ti on . B ec au se al l v a ri ab l es ha ve to be d ec la re d b ef ore t hey are used , th is is one go od wa y of ma ki ng s ure th at h ap pe ns . Also , it ma ke s t hem e as ie r to fin d .

int k , m ; un si gne d sho rt foo = 0; fl oa t x , y ;

*/ */ */ */ */

// Sa mp le d e cl a ra t io ns // S am pl e d e cl a ra t io n // Sa mp le d e cl a ra t io ns

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Do s tu ff h ere - thi s is th e p ro gr am bo dy * ******************************************************************* */ return 0; // Th is is of te n t he " e xit co de " fo r a prog ram , i nd i ca ti n g // how the p ro gr am te rm i na t ed . 0 us ua ll y m ean s it t er m in at e d // n or ma ll y . O the r co des are d ef in ed by the p ro gra mme r . }

1

Pretty much every program you write, regardless of what it does, will have a main function which is structured this way.

2.1.1 Exercises (a) Write a simple program, like the one above with gcc. If you don’t indicate an output file with the -o switch, it will create a.out. (b) Run your program with ./program name. (c) To see the exit code returned right after you’ve run a program, type echo ?. (d) Change the value in the return statement in the code to a different integer. Compile it and see if the exit code changes. Exit codes can be useful for letting the user know that a particular kind of error happened when they ran a program.

2.2 A little bit of I/O As you probably noticed in the last example, it’s hard to do much if you can’t take input from outside a program.

2.2.1 Character buffers One of the things you will learn again and again programming in C is that if you have data you need to represent, you need to make space for it. This is what we do when we declare variables. If we declare an int, we tell the compiler to allocate space for an integer. We can then use this space to assign values. As you may recall, a string (such as “Hello world”) is a sequence of characters. When we want to store a string somewhere, we have to tell the compiler to allocate a certain amount of space for those characters. We will not get into strings and arrays in greater detail here, but one thing you need to know is that when collecting input, you have to tell the compiler to give you a place to store it. For your assignment (and these exercises), we’ll create a character buffer1 (also referred to here as a string buffer) to store the input from the user. A character buffer declaration looks like this: char buff er_name [ < buffer_size >];

The buffer size is an integer indicating how many characters the buffer can hold. So if I want a buffer size of 100, I might declare it as follows. Note, that a character string always has to end with a character that is 0 thus of those 100 slots only 99 are really usable. char my_buffer [100] = {0}; 1 Those

of you with programming experience may recognize them already as char arrays - we’ll talk about them from that point of view once we’ve gotten to arrays.

2

2.2.2 Getting input from the command line C has a lot of functions to get input from the command line, and they work in a number of different ways. This week, we will only focus on one of them: gets() takes input from the command line up until the user presses Enter, and puts it into the string, which is passed as an argument. So if I want to wait on some user input from the command line and put it into my buffer, I’d use: gets ( my_buffer ) ;

Once the user has entered something, my buffer will contain the text. If you call gets(my buffer) again with the same buffer, the buffer will be overwritten with new user input once he has entered it.

2.2.3 Working with the input Now that we have a place to put the input (the buffer) and have gets() to fill it, there are two things we’ll quickly discuss here in order to work it: (a) Converting the input to an integer with atoi() (b) Accessing individual characters in the string buffer Getting an integer from a string Any text the user enters on the command line when using gets() will be interpreted as a string — that is, a sequence of characters. This is not very helpful to us if we need an integer, so we have to have some way to convert it. There is a function called atoi() which will convert strings to actual integer values (the rather obscure function name stands for ASCII to integer conversion). It has the following properties: It takes a string (in this case, your character buffer) as an argument. It returns an integer as its return value. If the string contains non-integer values, it simply returns 0. If we have used gets(input buffer) to store a string in the buffer, we can get its integer value by calling atoi() on input buffer: atoi ( input_buffer );

Of course, you want to store that integer somewhere, so make sure you’ve declared an integer somewhere and assign the value of atoi() to it. In addition you need to include to use atoi(). Accessing individual characters in the string buffer For now, we will give you two facts about the string buffer, as we discuss this in more detail later: (a) You can access individual characters in the string buffer by using an index.

3

(b) There is a special character which tells you you are at the end of a string. Computer scientists count starting with 0, not 1. That is also the way most modern programming languages work. This is also the case with our string buffer. If you want the first character in the string buffer, you have to ask for the character at index 0. In order to ask for a character at a certain point in the buffer, you use square brackets ([ ]). The following code returns the first character of the buffer. You can immediately store that in your own variable. input_buffer [0];

Note that you have to use the index 2 to get the third character and the index 99 to get the hundredth. As you may recall from Section 2.2.1, when we declared our character buffer, we made it a certain size. That is the maximum that buffer can hold. gets() will put a special character at the end of the string called the null character. In source code, the null character is represented as follows: ’\0’. So if you look at your string buffer character by character, you need to see if you have hit the end by checking for ’\0’. The numeric value of the character is 0, hence the symbol and the name. Compiler options with gets() You’ll probably get a compiler complaint if you try to compile a source file that uses gets() similar to the following: warn ing : ’ gets ’ is deprecated ( declar ed at / usr / includ e / stdio . h :638) [ - Wdeprecated - declarations ]

This is because there are better options than gets() and the compiler wants to discourage us from using gets() in general. If the warnings bother you, add the -Wno-deprecated-declarations option to your gcc command2 .

2.2.4 Printing output with printf We have already seen printf in the lecture and in our past assignments. If you have a simple fixed string3 you want to print, printf() is pretty easy to use. You simply put the string in quotes inside the call to printf(), and it will get printed. Newlines, tabs, and other escape sequences While there are some times where we might use multiple printf() statements for output on a single line, most of the time, you want to go to a new line after we’ve printed something. For that, you need to include a special character in your string — the newline character. The newline character is simply \n.

2 i.e.

gcc -Wno-deprecated-declarations myfile.c a string literal

3 called

4

So if you want to ensure the line goes to a new line, you need to add \n to the end of it, inside the quotes: printf ( " Hello World \n ") ;

This \n is what is known as an escape sequence. Some escape sequences are simply ways of representing special characters that can’t be easily represented in other ways. For example, newlines or tabs (\t). Other escape sequences are there so that you can use characters which normally have special meaning. For example, let’s say you want to change the statement above from “Hello World” to ‘The program’s output is: “Hello World”’. It is not directly possible to print that string. printf ( "The program ’s output is : " Hello World " ");

Obviously, the compiler will get confused by all of the double-quotes and there will be a parse error. For characters like the double-quotes above, we can escape them in order to tell the compiler to treat them as a part of the string. We do so by preceding them with a backslash (\): pri nt f ( " The p ro gr am ’s o ut put is : \" Hel lo Wor ld \" " ) ;

Some important escape sequences are: Desired character " ’ \ newline tab null character

Escape sequence \" \’ \\ \n \t \0

Format strings In addition to escape sequences there are also format-strings, that you use to output data. These were also covered by the lecture. The basic principle behind how we can print the values of variables is that we create a string inside the printf() statement as we did above, but we add some placeholders inside the string for the values we wish to add to it. Thus instead of using the string to output directly as the format string, you pass a dedicated format-string to printf and provide the string you want to output as another argument. pri nt f ( " %s \ n" , " H el lo W orld " ) ;

Or if you have an integer variable the answer in your program, and you wish to print its value after the string “The answer to life, the universe, and everything is”. So if its value were 42, what I want to see is: The answer to life, the universe and everything is 42.

5

You can do this using a special placeholder called a format specifier. A format specifier indicates that we are going to replace it with some value, as well as the type of the value that will replace it. Strings which contain these format specifiers are called format strings. %d is the format specifier for an integer. So I put it in as a placeholder in the printf() string: pri nt f ( " Th e a ns we r to life , the u ni ve rs e an d eve rything is % d .\ n " , the_answer );

You’ll note that in addition to putting in the placeholder %d, I also put the answer as the second argument to printf(), just following the format string. This tells the compiler that the value of the answer will replace the first placeholder in the string. In general, if there are several format specifiers, their replacement variables/values appear as arguments after the string corresponding to the listed in the order they appear in the format string. Some useful format specifiers4 : Format specifier %d %f %c %s

Description integer float or double single character string

Printing the % character - As you’ve noticed, the % character is used for the placeholders in format strings, so printing one by itself may confuse the compiler. In order to print the actual % character, use %% instead. This will print a single % character.

2.2.5 Exercises (a) Write a short program that declares a string buffer and uses gets() to take input from the command line and directly print that output back to the user.5 (b) Write a short program which takes a number from the command line, turns it into an integer, and stores it in an integer variable. Also print the number to the user. (c) Write a short program which takes a string from the command line, stores the first character in a character variable and then prints that character.

2.3 switch We’ve covered switch in the lecture and we’ll play around with them now in the context of real programs. As discussed in the lecture, sometimes, when there are a lot of different possibilities based upon the value of one variable, writing it out as a bunch of if-else statements is tedious. A better way to do this is to use a switch statement. Switch statements have the following form: 4 There 5 If

are many more - we’ll discuss them with I/O later in the course you get funny compiler warnings, see section 2.2.3.

6

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

... int m y_ va lu e ; // ... S om et hi ng ha ppe ns wh er e a va lu e is as sig ne d h ere . // An d not e tha t the v alu e d oes n ’t have to be an in te ge r . // ... sw itc h ( m y_ va lu e ) { case 0: // Do s tuf f tha t we w an te d to do if my _ va lu e w as 0 bre ak ; // T his is i mp or t an t . See b elo w . case 150: // Do wh at we wa nt ed to do if m y _v al ue wa s 150 bre ak ; case 987: // Do wh at we wa nt ed to do if m y _v al ue wa s 987 bre ak ; case 928317: // Do wh at we wa nt ed to do if m y _v al ue wa s 9 28 31 7 bre ak ; default : // Do wh at we wa nt ed to do if m y _v al ue ha d any ot he r v al ue bre ak ; } ...

This is much nicer than having to write out if-else statements for each case above. It’s easier to read, easier to code, and thus reduces the risk of making mistakes. Line 8 is where we indicate which variable’s value we care about. The case statements in lines 9, 12, 15 and 18 match particular potential values of my value and are followed by the code we want to execute if my value is equal to those constants. The break statements inside the case statements are important. If they are there, they tell the program “I’m done doing what I was supposed to do for this case.” Otherwise, the program will also execute the statements in the cases below the desired case, even if they do not match!

2.3.1 Exercise Write a program which takes a string from the user and prints “A is for apple” if the first character is ‘a’ or ‘A’, “B is for bear” if the first character is ‘b’ or ‘B’, “C is for cat” if the first character is ‘c’ or ‘C’, and “Now I know my ABCs” in all other cases, using a switch statement.

2.4 break and continue We’ve already talked about while loops, and you’ve seen one sort of behavior of the break statement when we talked about switch. Here, we’ll talk about how break and another kind of statement, continue, impact the execution of loops. Sometimes, we want to be able to interrupt the execution of code in a loop. The break statement tells the program to exit the loop immediately, and to continue execution with the code that comes after the loop. The continue statement, on the other hand, tells the program to stop what it’s doing in the loop

7

immediately, and go back to the top of the loop (the while condition), and continue execution from there.

2.4.1 break We’ll look at a break example using gets() in just a moment. But first, remembering the discussion of 0/1 and true/false from the lecture, what happens in this loop? 1 2 3

whi le (1 ) { pr int f ( " T his is no t th e pri nt st at em en t you are lo oki ng for .\ n " ); }

So now let’s try an example using gets(). What we want to do is to keep asking the user to type in strings until we find one that starts with ‘s’. Once he does, we’ll exit the loop. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

char i np ut _b uf fe r [1 00] ; whi le (1 ) { pr int f ( " En te r a s tr in g s ta rt in g w it h s :\ n ") ; g e ts ( i n p u t _ b u f f e r ) ; if ( i n pu t _b uf fe r [0] == ’s ’) { pr int f ( " Fi nally , you fo und a s tri ng th at st art s with s !\ n " ) ; bre ak ; } pr int f ( " No ! Th at d oe sn ’t st ar t w it h s . Tr y aga in .\ n ") ; } ...

As you can see, if the user doesn’t type a string starting with ‘s’, which gets checked in line 35, the loop will just keep going, because the condition is never false. break will stop the loop and will let execution continue from line 15.

2.4.2 continue Here’s a simple example using continue. We want to count from 1 to 20, but skip 13 (these could be the floor numbers of a hotel): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

int c ou n te r = 0; wh il e ( co unt er < 2 0) { ++ c o un t er ; if ( c o un te r == 13) { continue ; } pr in tf ( " %d " , c oun te r ) ; } pr i nt f ( " \ n " ) ; ...

8

Walk through this example to see that it works. When the counter is anything except 13, the if body is skipped and we print the number. But when the counter is 13, we skip to the top of the loop without printing. Now in this simple case, you might have also wrapped the printf in a loop with the opposite condition. But if the actual processing gets more complicated than a simple printing instruction, it can be more readable if you exit the loop iteration early. continue is often good to use for error conditions, or when there is no clean way to avoid executing the rest of the loop otherwise. It is also a natural choice if only a few specific iterations need to be skipped in a loop. Important notes if you have a switch statement inside of a while loop: continue will jump out of the switch block to the top of the loop. break, if within the switch statement, will only break out of the switch statement, not the entire loop.

9...


Similar Free PDFs