Friday, February 26, 2010

Intro to Computer Programming - Chapter 4: Communicating with the User


Chapter 4: Communicating with the User

Introduction

    One of the most common and basic of things a computer program can do is print information to the screen. With the exclusion of sound output, output to the printer, or graphics, information printed to the screen is the only way to communicate with the user. Every language (with the exclusion of assembly) has at least one specific command to print information to the screen, most have several.

Nearly all of the commands of the HTML language are for displaying information in one form or another, whether it be in the form of text, audio, or in the form of graphics. This is an advantage when displaying pre-processed information is the only thing the computer needs to deal with, but this is not usually the case. For instance, in HTML alone, the programmer cannot ask the user for two numbers and add them together. In other words, HTML cannot do any type of information processing. This is where the other computer languages such as BASIC, C++, and Java come in.

The next most common task that a computer does is ask the user for information and then process that information. For instance, the older computers when turned on would ask the user for the current date and time and then they would act upon that information accordingly. Even with modern computers running the Windows Operating System, the computer is constantly displaying information, asking the user for input, and doing background processing of the input.

In an attempt to keep the programs simple at first, I'll only explain how to do text output and input. The more advanced topics such as sound and graphics will be covered at a later time.

Displaying Text in Qbasic

Introduction

    Qbasic is one of the easier languages to write programs in. Qbasic is based on the BASIC family of languages. The BASIC language itself was created in the late 1960's for beginners so they could learn how to program (BASIC stands for Beginners All-Purpose Symbolic Instruction Code).

Unlike other languages, including HTML, Qbasic does not require any special requirements such as the requirements at the beginning or end of the program (like HTML requires the <html> and </html> tags at the beginning and end of the program). With Qbasic, the programmer can just start solving the problem. Qbasic also is not an extremely strict language in that commands do not have to be capitalized and the language is not case-sensitive (for example, Name is the same thing as NAME and name).

    Qbasic programs do require the Qbasic interpreter, which is included on the enclosed CD under the Qbasic directory. Microsoft created Qbasic as a free version of their compiler called QB. The only difference is that any program created in Qbasic must be run within Qbasic because Qbasic must interpret each of the commands into something the computer can understand (similar to how a Spanish interpreter interprets English into Spanish). QB, on the other hand, converts the program straight into a language the computer can understand so the program can be ran from Dos or from within Windows without the need for QB. Any programs written in Qbasic will also work correctly in QB without problems, but not necessarily the other way around.

    There are at least two main reasons why Qbasic is not used to do much programming. The first reason is because Qbasic is extremely slow in processing information. The main reason for this is because it is an interpreted language and the process of interpreting one language into another is always slow, even when talking about human spoken languages. The other reason why Qbasic is not used much is that it has limits as to how large the programs can be and how much data the program can handle. Qbasic can only handle programs up to 64 kilobytes (one kilobyte is equal to 1,024 bytes) or roughly 64 typed pages. Many programs are in order of several thousand typed pages long and Qbasic would not be able to even load the program, must less run it.

The Print Statement

    In Qbasic, the Print statement is used to display text to the screen. It can be used to print strings, numbers, and even the answers to formulas. The format of the command is the command itself [i.e. PRINT] followed by what the programmer wishes to print. If the programmer wants a certain piece of information printed "as is", the information must be enclosed in quotes (" "). To print a blank line, use a print statement by itself with nothing after it. See Program 7 for examples of the print statement.

PRINT "Hello"
PRINT 2.14
PRINT 2+2
PRINT "2+2"
PRINT
PRINT –2
PRINT 2/.5
PRINT 2.0 
Hello
2.14
4
2+2

 
-2
4
2 
Program 7 - Qbasic Program Showing Print Statement and Output
    Qbasic is one of the few languages that actually helps its programmers out by giving them shortcuts. One of the most famous shortcuts in the Qbasic is instead of always typing PRINT for each print statement, the programmer can just type a question mark and Qbasic will replace the question mark automatically with the print command. Also helpful is the way Qbasic automatically capitalizes its commands as the programmer types them.

    Notice that each print statement prints its output on a single line and then automatically goes to the next line. If the programmer wishes to keep the output of the next print statement on the same line, just add a semicolon (;) to the end of the statement and Qbasic will keep any more output on the same line. Another use of the semicolon option is to string several print statements into a single statement. This could be useful if the type of data is different or if variables are involved (will explain variables in the next chapter).

    Another useful option with the print statement is the comma (,). The comma is used just like the semicolon except that the comma adds a 16-space tab along with keeping everything on the same line. The comma option is useful for doing tables.

It is also useful to notice that positive numbers have a space inserted in front of them, but negative numbers to not have this additional space. There is a way to get rid of this additional space, but you'll have to wait a couple chapters for the solution to that problem J.

The next program shows the use of the semicolon option as well as the question mark shortcut. Notice how the words "is" and "Raleigh" do not have a space between them. This is because the information enclosed within quotes is printed exactly as it is within the quotes. To correct this apparent error, just add a space between the word is and the end quotation mark or before the quotation mark and the word Raleigh.


 

? "The sum of 2+2=";2+2
?
? "The capital of North Carolina is";
? "Raleigh";" with a population of";
? 200000 
The sum of 2+2= 4   

 
The capital of North Carolina isRaleigh with a population of 200000
Program 8 - Qbasic Program Showing the use of ; and ?
    The print statement will come in handy in other forms of output in the Qbasic language. You'll see the print statement again at a later time.

Displaying Text in C

Introduction

    The C language is what some consider to be a professional language. Most of todays programs are written in C or C++ (C++ is an advanced version of C). C is not a beginners language like BASIC is but it doesn't suffer from the same restrictions as BASIC suffers from such as program size limits or data size limits. For instance, the Windows Operating System is written mainly in C and C++ and contains several million lines of code.

    In order to write and compile C programs, the programmer must have a C compiler such as Microsoft Visual C++, Bloodshead's DevC++, or the GNU C compiler (the latter two are free). The Bloodshead DevC++ compiler is located on the CD under the DevC directory.

Unlike Qbasic, C is not an interpreted language but it is a compiled language. This means that the compiler itself is not required after the first compile. In other words, once the translation to the computer's native language is finished, it does not have to be translated again unless the program is changed. This allows C compiled programs to be extremely fast when they are executed.

    C, like HTML and most other programming languages, has a minimum requirement for all of its programs. This requirement does have a few parts that can be changed, but the beginning C programmer will not usually need these advanced features. The requirements for C are exactly the same as those for its advanced version, C++. Program 9 shows the minimum C/C++ program. It is best to ignore what each line in Program 9 does at this time as each line will be explained later.

int main( )
{
return 0;
} 
Program 9 - Minimum C/C++ Program
    Unlike Qbasic, C is case sensitive in both its commands as well as variables. This means that main is not the same thing as Main or MAIN. This is a common error for many beginning programmers.

    Formatting is also fairly specific in C. Nearly every line in C will require a semicolon at the end of the line. There are a few exceptions and these will be covered in a later chapter. Think of the requirement of the semicolon in C to be like the requirement of a period at the end of a sentence in the English language. For now, just follow the examples on the uses of the semicolon placement. They'll be explained soon.

The printf Function

    The C command to print information to the screen is somewhat similar to the print statement in Qbasic. The printf function, with a few exceptions, will print text that is enclosed in quotes exactly as is, just like Qbasic. The prinf function will also print numbers, but it requires some special formatting commands in order to work correctly. Unlike print in Qbasic, printf automatically keeps all information on the same line unless told otherwise (this is the exact opposite of Qbasic).

    There is one requirement to add to the program before the printf statement can be used, #include <stdio.h>. This additional line of code only needs to be added once and should be added at the beginning of the program. The reason this additional line of code must be added is because C is a very small language and only has about 30 statements in the language [In comparison, Qbasic has over 200 statements]. In C, statements are automatically included in the language, but functions are not included unless you specifically tell C to add the function by using the #include directive. As an example, let's say someone is trying to cook a specific kind of cake and they have ten different recipe books, all of which have different cakes in them and the recipe they want is in only one of these recipe books. They would either have to search through all the books manually, be told by someone else which book its in, or look at an index. The easiest way is for someone else who already knows the recipe books to tell them which book the specific cake recipe is located in (maybe the cook is in a hurry and needs the recipe quickly). This is the case with the C language, the language (more specifically the compiler itself) must be told where the function is located. In our case, the printf function is located in the file stdio.h. The #include directive will be covered in depth later. Program 10 demonstrates the printf statement and the #include directive.

#include <stdio.h>

 
int main ( )
{
printf("This is C.");
return 0;
} 
This is C. 
Program 10 - Simple printf Statement
    The printf function allows special formatting characters within quoted information. As a contrast, Qbasic prints the quoted information exactly as is. These special formatting characters force the printf statement to force a new line, insert a tab, among several others. The most common of these are forcing a new line (\n) and the tab (\t) character. Table 4 lists some of the special formatting characters that are available within the quoted text of the printf function and Program 11 demonstrates how they can be used in printf statements.

Format CharacterMeaning in C 
\n 
Insert a new line 
\t Insert a tab 
\\ Print out a \ 
\" Print a " 
Table 4 - Printf format characters
#include <stdio.h>

 
int main( )
{
printf("The capital of North Carolina is");
printf("Raleigh\n");
printf("\tThis sentence has a tab in front\n\n");
printf("\n");
printf("The file is located in C:\\My Files\n\n");
printf("C is \"fun\"\n");
return 0;
} 
The capital of North Carolina isRaleigh
This sentence has a tab in front

 

 
The file is located at C:\My Files

 
C is "fun"  
Program 11 - printf statement with format characters
    The printf function can print numbers but it requires more formatting characters in order to do it. [What, did you actually expect C to be as easy as Qbasic? L Just wait, C++ is easier than C, I promise!] In order to print numbers, a format specifier must be used. This feature of the printf function will be covered later in this chapter.

Displaying Text in C++

Introduction

    As stated earlier, the C++ language is just an advanced version of C. This does not necessarily mean that C++ I harder to learn than C, but it mainly means that C++ has advanced features, some of which make the language easier to understand and some that make it harder to understand.

    Just like C, C++ is also not a beginners language and also just like C, C++ does not have the program size limits like BASIC does. A C++ compiler must also be used to compile the C++ programs such as Visual C++, Blodshead's DevC++, or the GNU C++ compiler (Bloodshead DevC++ is included on the CD).

    C++, like C and most other programming languages, has a minimum requirement for all of its programs. The requirements for C++ are exactly the same as those for C. Program 12 shows the minimum C/C++ program. It is best to ignore what each line in Program 12 does at this time as each line will be explained later.

int main( )
{
return 0;
} 
Program 12 - Minimum C/C++ Program
    Like C, C++ is case sensitive in both its commands as well as variables. This means that main is not the same thing as Main or MAIN. This is a common error for many beginning programmers.

    Formatting is also fairly specific in C++. Nearly every line in C++ will require a semicolon at the end of the line. There are a few exceptions and these will be covered in a later chapter. Think of the requirement of the semicolon in C++ to be like the requirement of a period at the end of a sentence in the English language. Not all sentences in English have a period after them, some have a question mark or an exclamation mark. For now, just follow the examples of semicolon placement. They'll be explained soon.

The cout Statement

    The cout statement in C++ is similar to the Qbasic print statement and it is also similar to the C printf function. The cout statement prints quoted text similar to the way the C printf function does in that the cout statement uses the C formatting characters for new line, tab, and so forth (see Table 5). This is different from the Qbasic print statement as quoted text is printed exactly as is. The cout statement does differ from the C printf function in that numbers are easily printed, just as they are in Qbasic (i.e. no special formatting characters are required) [see, told you C++ is easier than C, at least cout will let you print numbers easily J]. Basically, the cout statement combines the best of C's printf function and Qbasic's print statement into one statement [kind of].

Format CharacterMeaning in C++
\n 
Insert a new line 
\t Insert a tab 
\\ Print out a \ 
\" Print a "
Table 5 - Cout format characters
    Just like the printf function in C required the #include directive, so also does the cout statement in C++. The cout statement is located in the iosteam.h file so the #include statement should look like #include <iostream.h>. It should be noted that just because cout is a statement, C++ must still be told where to find cout. This is because the cout statement is not part of the C++ language.

    Because the cout statement is a statement and not a function, it does not require a set of parenthesis like the printf function requires, but it does require another form of punctuation known as the double less-than operator (<<). The double less-than operator is required for each piece of data to be outputted to the screen. For example, if the programmer wanted to print a word, then a number, and then another word using only one cout statement, then the cout would require three double less-than operators. An example of this is shown in Program 13. This same program can also be written by using three separate cout statements but this still requires three double less-than operators as shown in Program 14.

#include <iostream.h>

 
int main( )
{
cout<<"2+2="<<4<<".";
return 0;
} 
2+2=4.
Program 13 - C++ Program showing use of cout double less-than
#include <iostream.h>

 
int main( )
{
cout<<"2+2=";
cout<<4;
cout<<".";
return 0;
} 
2+2=4. 
Program 14 - C++ Program showing use of cout Statements
    There are two main things to notice about the cout statement. First, if you remember the output from the Qbasic print statement, you'll remember that any non-negative numbers had a space before them. This space is removed in C++ by using the cout statement (there is still a way to get rid of the space in Qbasic). The second thing to notice is how everything is automatically printed on the same line as is done in C with the printf statement. To change this, the formatting characters must be used in the printed output. The following program demonstrates the use of the cout statement with these formatting characters. Also, notice in the program how the letters "endl" (which stands for end line) can be used to simulate using "\n" outside of quoted text.

#include <iostream.h>

 
int main()
{
    cout<<"2+2="<<2+2;
    cout<<endl<<endl;
    cout<<"The capital of North Carolina is";
    cout<<"Raleigh\n"<<"with a population of";
    cout<<200000<<endl;
    return 0;
}
2+2=4

 
The capital of North Carolina isRaleigh
with a population of200000
Program 15 - C++ program showing cout statements

Conclusion

    Each language in this chapter (Qbasic, C, and C++) has a specific statement or function to display information to the screen. In Qbasic, the print statement is used. In C the printf function can be used and in C++ the cout statement can be used to display information. A comparison of the languages so far and also a comparison of the display statements is shown in Table 6. A comparison of programs is shown in Table 7.


 

QBasic 
C 
C++ 
Output 
PRINT "Hello"
printf("Hello\n");
cout<<"Hello\n";
Hello
PRINT "Hello";
printf("Hello");
cout<<"Hello";
Hello
PRINT 2+2;
n/a
cout<<2+2;
4 (in Qbasic)
4 (in C++) 
PRINT -4;
n/a
cout<<-4;
-4 
PRINT "A";"B" 
printf("A");
printf("B");
printf("\n"); 
cout<<"A";
cout<<"B";
cout<<endl; 
AB 
Table 6 - Language Comparison

 

Purpose 
Qbasic 
C 
C++ 
minimum
program
int main()
{
return 0;
} 
int main()
{
return 0;
}
program with
command used
in this chapter
PRINT "Hello"
#include <stdio.h>

 
int main()
{
printf("Hello\n");
return 0;
}
#include <iostream.h>

 
int main()
{
cout<<"Hello"<<endl;
return 0;
}
Table 7 - Program Comparison
    The print statement in Qbasic prints quoted text as is without any special formatting and can also display numbers. It automatically prints all information on a line by itself unless told otherwise by use of the semicolon or the comma options. The semicolon option forces the print statement to print the next piece of information on the same line while the comma option inserts a 16-space tab. The shortcut for typing the print statement is the question mark (?).

    In C, the printf function can print quoted information. Special formatting codes can be inserted within the quoted text and printf will act on these formatting characters. Printf can also display numbers but is more complicated than Qbasic's print statement. Printf will print all information on the same line unless told otherwise by the carriage return special characters (\n). A list of special formatting characters is shown in Table 8. In order for printf to be used within a C program, the stdio.h file must be included.


 

Format Character 
Meaning in C++ 
\n 
Insert a new line
\t 
Insert a tab 
\\ 
Print out a \
\" 
Print a " 
Table 8 - C/C++ Special Formatting Characters
    The cout statement in C++ is similar to the printf function as well as the print statement. Cout will print quoted text as printf and uses the same formatting codes (see Table 8). Cout also has the capability of printing numbers easily, as the print statement in Qbasic can do. Similar to printf, the cout statement prints all information on the same line unless specified otherwise by the carriage return code (\n) or the end line code (endl). In order for the cout statement to be used within a C++ program, the iostream.h file must be included.

Problems

    [What, you thought I was going to let you get out of doing some problems? Yeah, right! J They'll be fairly easy, I promise…at least for now J]

Since there were three languages covered in this chapter, each of these problems should have three answers, one for each language unless otherwise specified. Also, assume that the problem requires a complete program unless the problem states otherwise. Also, the quotes in the problem dictate the desired output therefore do not include the quotes in the program output.


  1. Write a program to print "Hello" on the screen on a line by itself.

  2. Write a program to display the sum of 4+8 on the screen in the languages that allow displaying numbers on the screen.

  3. Modify problem 2 to display a prompt as well as the output. Keep the prompt and output on the same line. [Hint: A prompt is a description of the output, in this case the prompt is "4+8="]

  4. Write a program to display the numbers from 1 to 5 on the same line. For languages that require it, insert a space between each number.

  5. Do problem 4 using only a single print statement or the equivalent.

  6. Write a program to display the numbers from 5 to 10 on the same line. In addition, display the numbers 1 to 5 on a line by themselves and then finish the program by displaying the numbers 5 to 10 on the same line. [Hint: This should look similar to a box except the right side will be missing]

  7. Write a program to display the numbers from 1 to 25 using a tab between each number. Use between five and eight rows to display the numbers.

No comments:

Post a Comment