0% found this document useful (0 votes)
2 views

Week9Lab

This document serves as an introductory guide to programming in C++ for students at the University of the Witwatersrand. It covers the basics of C++ syntax, including compiling and executing code, variables, input/output operations, and basic operators, while drawing comparisons to Python. The document also provides practical examples and exercises to reinforce the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Week9Lab

This document serves as an introductory guide to programming in C++ for students at the University of the Witwatersrand. It covers the basics of C++ syntax, including compiling and executing code, variables, input/output operations, and basic operators, while drawing comparisons to Python. The document also provides practical examples and exercises to reinforce the concepts discussed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

U NIVERSITY OF THE W ITWATERSRAND , J OHANNESBURG

School of Computer Science & Applied Mathematics

Introduction to Algorithms & Programming

1 Preliminaries

In the document below, we assume that we are compiling and executing C++ code through
the terminal on Ubuntu. If you are using a different operating system or running your code
through something else, please follow those relevant instructions to compile and execute code
instead.

2 Aims

The aim of this lab is to introduce you to the C++ programming language. While C++ is a
new language, it is important to note that many of the concepts we have covered in Python
immediately extend to C++. It is only the syntax that is different. This lab will provide a
thorough description of all the basic building blocks of C++, so please refer to it when required.

3 Hello World

Unlike Python, C++ is a compiled language. Let’s begin by creating a simple C++ program to
see how we go about programming, compiling and running a C++ program. Create a new file
called helloWorld.cpp and type the following code into it:

1 #include <iostream>
2
3 using namespace std;
4
5 int main(){
6 cout << "Hello, world!" << endl;
7 return 0;
8 }

Open a terminal in the same directory as your file and enter the following to compile the
program:

g++ helloWorld.cpp -o helloWorld

1
The above command turns the text file into a program, and outputs an executable file called
helloWorld. If you receive any error messages in terminal, you will need to correct the errors
in your code, save the file, and rerun the command. Note that if everything has gone well, the
terminal will not display anything.

You should now have a new file in the directory called helloWorld. To run it, type the
following into the terminal and press Enter:

./helloWorld

The following output should now be displayed in the terminal window: Hello, world!
Note: every time you make a change to the code, you will need to save your file and run
the above g++ command before executing it.

Once you’re done, upload your file to the appropriate Moodle submission.

4 A First Look at C++

Let’s now have a look at the above program with comments added:

1 /*These are comments. They are used to assist the programmer.


2 They do not affect the program in any way.
3 Write whatever you want*/
4 #include <iostream> //preprocessor directive (use input/output)
5
6 using namespace std; //use standard definitions
7

8 //This is the "main" function. C++ will start executing code from here
9 int main(){ //bracket signals the start of the main function
10 cout << "Hello, world!" << endl; //display the text and a new line
11 return 0; //main must return an integer. 0 means success, fail otherwise
12 } //end of the main function

4.1 Comments

We have added comments to the program. Comments are annotations that can be made to the
code to explain exactly what’s going on, or to help with readability. They are ignored by the
compiler, and so do not affect the functionality of the program in any way. There is no need to
comment every single line — use them only when they help in understanding the code.

There are two types of comments: C++-style comments, which begin with // and span a
single line, and C-style comments, which wrap the comment in /* and */ and can span multiple
lines. Both are perfectly valid in C++. For more information about comments, see https://
www.tutorialspoint.com/cplusplus/cpp_comments.htm and http://en.cppreference.com/
w/cpp/comment

2
4.2 The Include Directive

Line 4 is a preprocessor directive. Before compilation actually occurs, the directive instructs
the compiler to replace the line with the entire contents of the specified file. In this case,
the contents of the standard library file iostream (which defines the standard C++ input and
output functions) is added to the file. Note that the included file may contain other #include
statements, which themselves may contain other #include statements, and so on. The contents
of all these files are all included (up to some limit).

4.3 Namespace

Line 6 tells the compiler we’ll be using the standard namespace. All this really means is that
standard library files and definitions are going to be used. It is possible to define your own
namespace if you want to make sure that your variables and definitions do not conflict with
either the standard ones, or someone else’s. Both cout and endl reside in the standard names-
pace. If we omitted Line 6, we’d have to change Line 10 to read:

std::cout << "Hello, world!" << std::endl;

For our purposes, it is simply easier to use the standard namespace and not have to worry
about typing the std:: qualifier every time.

4.4 The Main Function

All C++ programs begin processing at the first executable statement in main. The int in front
of main declares main to be a function that is expected to return an integer. The lines of code
between the curly brackets is called the function body. It is considered good programming
practice to indent the text in the function body by a certain amount of space.

Line 11 specifies that the function returns the integer 0. The operating system expects all
C++ programs to return an integer indicating whether they have successfully completed, or
whether they terminated with some error. 0 indicates that the program completed success-
fully, while any other integer indicates some error occurred. For example, if your program had
prompted for user input and the user typed in something that the program was not prepared
to process, one could signify this to the operating system by returning a 1. When this line is
encountered, processing in the CPU returns to the operating system.

4.5 Output

Line 10 instructs the C++ standard input/output library to print the series of characters Hello,
world! to the screen (using the cout stream), and then positions the cursor at the beginning of
the next line. The positioning is effected by the endl function.

We could have achieved the same result by writing

3
1 cout << "Hello, world!\n";

Question: Given the above, what then is the difference between \n and endl?

\n represents a special sequence of characters called an escape sequence. Escape sequences


are translated into another character (or sequence of characters) that may be difficuly or im-
possible to represent directly. Here is a list of some escape sequences commonly used in cout
statements:

Characters Name Function


\n Newline Move cursor to beginning of next line
\t Horizontal Tab Move cursor to next tab stop
\r Carriage Return Move cursor to beginning of current line
\a Alert Sound the bell
\\ Backslash Print a single backslash
\" Double Quote Print a double quote

See http://en.cppreference.com/w/cpp/language/escape for more.

4.6 Semi-colons

All statements in C++ are terminated by a semi-colon. Preprocessor directives and function
definitions are not statements, and therefore do not end with a semi-colon.

5 Variables

As in Python, C++ supports the concept of a variable. A variable is used to store (“remember”)
a particular value in memory, to which we can then refer to perform computations. For more
reading on variables, see http://www.cplusplus.com/doc/tutorial/variables/.

5.1 Name

A variable is identified by its name, which consists of a series of one or more of letters, digits or
underscores. Variables should be given meaningful names to aid in readability — short names
can indeed be meaningful, while overly long names can annoy. There are certain keywords
which cannot be used as variable names, and are listed here: http://en.cppreference.com/
w/cpp/keyword

5.2 Type

In C++, each variable has an associated type, which tells the compiler what kind of data the
variable will store. This allows the compiler to reserve the appropriate amount of memory.

4
C++ provides a set of built-in types, and offers users the ability to define new types themselves
(user-defined types). Some of the more important built-in types include int (integer), double
(real number), char (a single character) and bool (a boolean: either true or false).

string, which stores text, is not a built-in data type (i.e. it is not part of the core language),
but is universally supported and can almost be treated as such.

5.3 Assignment

Variables are assigned a value using the = operator. Note that to prevent unwanted behaviour,
the right-hand side of the equals sign should match the type of the variable on the left-hand side.
Variables can be assigned values when they are first declared, or at any point after declaration.

5.4 Example

The following snippet of code illustrates some of the above points. First, try predict what the
code will output when run, then actually run the code and see if you were correct.

1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 int main(){
7 int x; //declare variable x. It holds an integer, but has no value
8 int y = 2; //declare and assign 2 to the variable y.
9 x = 4; //x's value is now 4
10 y = x; //y's value is now 4
11 x = -1; //x's value is -1. What is y's?
12 double z = 1.9; // a new variable z is assigned with a decimal value
13 string str; //a string variable is declared.
14 str = "Hello"; //str gets the value within the quotes.
15 int q = z; //q is an int, but z is a double. I wonder what happens here?
16 return 0;
17 }

6 Input

We have already covered output, and input looks very similar. In order to accept input from the
user, we first need to declare an appropriate variable and then use the cin stream to read the
user-entered value into the variable. Note that the value being read in must match the type of
the variable it will be stored in. As an example, the following code asks the user to enter their
name and outputs an appropriate greeting. Run the code, type your name and hit Enter.

5
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 int main(){
7 cout << "Enter your name:" << endl;
8 string name;
9 cin >> name; //note that the arrows point TOWARDS the variable!
10 cout << "Hello " << name << "!" << endl;
11 return 0;
12 }

Note that C++ does not differentiate between spaces and new lines for input. So
inputting two integers on the same line separated by a space is equivalent to two integers
separated by a new line.

7 Basic Operators

Now that we have variables, we can begin to perform operations on them. C++ offers 5
arithmetic operations that can be performed on numeric variables:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo (remainder)

The operators all adhere to the BODMAS principal in terms of precedence, and brackets can be
used just as they would in regular mathematical expressions.

Additionally, the C++ standard library offers some additional mathematical functions, such
as square rooting and exponentiation. The following code illustrates some basic usage. Again,
try predict the output of the code and then run it to see what happens.

6
1 #include <iostream>
2 #include <cmath> //need this for math functions like sqrt, pow
3
4 using namespace std;
5
6 int main(){
7 int x = 4;
8 x = x + 3;
9 cout << "x = " << x << endl;
10 double z = 9.5 * 2 + 1;
11 cout << "z = " << z << endl;
12 int y = x * x; //y is 49
13 cout << "y = " << y << endl;
14 y = sqrt(y); //take the square root of y
15 cout << "y = " << y << endl;
16 x = y % (x-1); //divide y by one less than x and take remainder
17 cout << "x = " << x << endl;
18 x = pow(x, 4); //raise x to the power of 4
19 cout << "x = " << x << endl;
20 double p = 9.0 / 2; //p is 4.5
21 cout << "p = " << p << endl;
22 double q = 9/2; // integer division!!
23 cout << "q = " << q << endl;
24 return 0;
25 }

8 Reading Error Messages

Oftentimes, there will be some error in the source code which prevents the compiler from
creating the object file. In this case, it will produce messages that indicate the nature of the
error. Below is a sample program and the error message it produces:

1 //File: faulty.cpp
2 #include <iostream>
3 using namespace std;
4 int main(void)
5 {
6 int x;
7 cout << "Enter a number: ";
8 cin >> x
9 cout << "The number you entered was: " << x << endl;
10 return 0;
11 }

faulty.cpp:In function `int main()':


faulty.cpp:9:1:error: expected `;' before cout

This message indicates that at line 9, the compiler expected to see a semicolon before phrase
cout. And indeed, on the previous line (line 8), a semicolon has been left out. While this
error message was fairly straightforward, others may not be. However, all will indicate the

7
line number (9 in this case) where the error occurred. Be aware that while the error message
suggested line 9, it was actually a mistake on line 8 that caused this error which was only
noticed by the compiler on the following line.

Before asking someone for help, please check the compiler output to see if it offers informa-
tion on how to fix your problem.

9 Submissions

For this lab, the submissions will consist of all the labs you’ve previously done and solved, but
now implemented in C++ instead of Python! Feel free to use your old Python code to assist
with these. For each task, submit the appropriate .cpp file to the online marker.

Submission 1: Doubling
Write a program that reads from input a single integer, and outputs twice its value.

Input
Input consists of a single integer N .

Output
Output 2N .

Example Input-Output Pairs


Sample Input #1
12

Sample Output #1
24

8
Submission 2: Difference
Write a program that reads from input two real numbers (of type double) and outputs their
difference.

Input
Input consists of two real-valued numbers x and y, separated by a single space. Note that C++
does not differentiate between spaces and new lines for input. So inputting two integers
on the same line separated by a space is equivalent to two integers separated by a new
line.

Output
Output x − y.

Example Input-Output Pairs


Sample Input #1
1.9 2.7

Sample Output #1
-0.8

9
10 If-Else

C++ if statements are very similar to that of Python. To see this, have a look at the code below:

1 #include <iostream>
2
3 using namespace std;
4
5 int main(){
6
7 double x;
8 double y;
9 double min;
10
11 cin >> x;
12 cin >> y;
13
14 if (x <= y){
15 min = x;
16 }
17 else{
18 min = y;
19 }
20

21 cout << min << endl;


22
23 return 0;
24 }

Note that the statements within the if and else sections are surrounded by curly brackets.

We can also combine several if-else structures together if we wish to test a range of con-
ditions. For instance, we may wish to check whether a number is positive, negative or zero. We
would then have:

1 if (x == 0){ //double equals!


2 cout << "x is zero" << endl;
3 }
4 else if (x > 0){
5 cout << "x is positive" << endl;
6 }
7 else{
8 //the only other option
9 cout << "x is negative" << endl;
10 }

11 Examples

Here are some more examples of if-statements:

10
11.1 If-else

1 //Calculate min and max of 2 numbers


2 #include <iostream>
3 using namespace std;
4 int main(){
5 double x, y, smaller, larger;
6 cin >> x >> y;
7 if (x < y){
8 smaller = x;
9 larger = y;
10 }
11 else{
12 smaller = y;
13 larger = x;
14 }
15 cout << "The smaller number is " << smaller <<
16 " and the larger is " << larger << endl;
17 return 0;
18 }

11.2 Multi-way Decisions

1 //Display whether x is positive or negative


2 #include <iostream>
3 using namespace std;
4 int main(){
5 double x;
6 cin >> x;
7 if (x < 0){
8 cout << "x is negative" << endl;
9 }
10 else if (x > 0){
11 cout << "x is positive" << endl;
12 }
13 else{
14 cout << "x is zero" < <endl;
15 }
16 return 0;
17 }

11
11.3 Comparisons

1 #include <iostream>
2 using namespace std;
3 int main(){
4 double x, y;
5 cin >> x >> y;
6 if (x > y){
7 cout << "x is greater than y" << endl;
8 }
9 if (x < y){
10 cout << "x is less than y" << endl;
11 }
12 if (x >= y){
13 cout << "x is greater than or equal to y" << endl;
14 }
15 if (x <= y){
16 cout << "x is less than or equal to y" << endl;
17 }
18 if (x == y){
19 cout << "x is equal to y" << endl;
20 }
21 if (x != y){
22 cout << "x is not equal to y" << endl;
23 }
24 if (x % 2 == 0){
25 cout << "x is even" << endl;
26 }
27 if (x % 2 != 0){
28 cout << "x is odd" << endl;
29 }
30 if (x < 0 || y < 0){
31 cout << "Either x or y is negative (or both are)" << endl;
32 }
33 return 0;
34 }

12
11.4 Nested if-statements

Note that we can also “nest” if-statements; that is, if-statements within if-statements:

1 //Calculate max of three numbers


2 #include <iostream>
3 using namespace std;
4 int main(){
5 double x, y, z, max;
6 cin >> x >> y >> z;
7 if (x > y){
8 if (x > z){
9 max = x;
10 }
11 else{
12 max = z;
13 }
14 }
15 else{
16 if (y > z){
17 max = y;
18 }
19 else{
20 max = z;
21 }
22 }
23 cout << "The largest number is " << max << endl;
24 return 0;
25 }

13
Submission 3: Grading
Write a program that accepts an integer in the range [0, 100] and outputs the corresponding
grade. Use the table below to match the mark with the correct grade. Be sure to output your
answer exactly as it is written in the table.

Grade Mark
First 75+
Upper second 70 − 74
Lower second 60 − 69
Third 50 − 59
Fail < 50

Input
Input consists of a single integer specifying the mark.

Output
Output the corresponding grade.

Example Input-Output Pairs


Sample Input #1
70

Sample Output #1
Upper second

14
Submission 4: Leap Year
A leap year is a calendar year that contains one extra day.a Write a program that accepts a year
and outputs whether that year is a leap year or not. The following rules determine leap years:

• Years that are exactly divisible by 100 are only leap years if they are also divisible by 400

• Years that are not divisible by 100 but are divisible by 4 are leap years

• No other years are leap years

To accomplish this, you need to define what we mean by “divisible”. [Hint: You might need the
modulus operator]

Input
The input consists of a single year (a non-negative integer) y read from the user.

Output
If the given year y is a leap year, output [y] is a leap year; otherwise, output
[y] is not a leap year
See the example output below if this is unclear.

Example Input-Output Pairs


Sample Input #1
2017

Sample Output #1
2017 is not a leap year

Sample Input #2
1900

Sample Output #2
1900 is not a leap year

Sample Input #3
2016

Sample Output #3
2016 is a leap year
a
We are fans of leap years, as they give us one extra day to do some more programming!

15
Submission 5: Rock-Paper-Scissors
In the popular game Rock-Paper-Scissors (RPS) two players compete against one another by
simultaneously making one of three hand symbols: rock, paper or scissors. The outcome of
the game depends on the symbols both players have chosen: a player who decides to play rock
beats another player who has chosen scissors (“rock crushes scissors”) but will lose to one who
has played paper (“paper covers rock”); a play of paper will lose to a play of scissors (“scissors
cuts paper”). If both players choose the same shape, the game is tied.
Your task is to write a program that takes as input the choices made by two players (Player 1
and Player 2), and outputs the result.

Input
Your program will receive 2 lines of input: the first line is Player 1’s choice (either rock, paper,
or scissors), while the second line is Player 2’s choice.

Output
Given the above input, you should output the result of the game. There are only three possible
outcomes:

1. Player 1 wins

2. Player 2 wins

3. Tie

Example Input-Output Pairs


Sample Input #1 Sample Input #2 Sample Input #3
rock scissors paper
paper paper paper

Sample Output #1 Sample Output #2 Sample Output #3


Player 2 wins Player 1 wins Tie

12 Loops in C++

In C++, there are three types of loops: for loops, while loops and do...while loops.

12.1 For Loop

In C++, the general form of the for loop looks like this:

for (<variable initialisation>; <condition>; <variable update>){


<code to execute while the condition holds>
}

16
The initialisation expression allows you to declare and initialise a control variable before the
loop begins (or assign a value to an existing variable). This expression is executed only once
before the loop, and never again. The condition expression is a boolean test that determines
whether the body of the loop should be executed. Finally, the variable update expression allows
us to modify the control variable in some manner. After the first execution of the loop body, the
variable is updated, and the condition is checked. If the condition is still true, the loop body
repeats, after which the variable is updated, and so forth.

Each of the above three expressions is optional and so can be omitted, but the semicolons
are mandatory. Note that if the condition is empty, it is evaluated as true and the loop will
repeat indefinitely (unless we stop it some other way).

An example of a simple for loop is given below.

1 #include <iostream>
2

3 using namespace std;


4
5 int main(){
6 int sum = 0;
7 cout << "Please enter 8 numbers: " << endl;
8 for (int i = 0; i < 8; ++i){
9 int number;
10 cin >> number;
11 sum = sum + number;
12 }
13 cout << "The sum of your numbers is " << sum << endl;
14 return 0;
15 }

12.2 While Loop

The while loop is similar to the for loop, but does not have an explicit initialisation or variable
update section. The form of the while loop looks like this:

while (<condition>){
<code to execute while the condition holds>
}

Again, the condition is any kind of boolean expression (of any complexity), and as long as
it is true, the loop body will execute. An example of a while loop is given below.

17
1 #include <iostream>
2

3 using namespace std;


4
5 int main(){
6 int sum = 0;
7 int x;
8 cout << "Enter some numbers. Type -1 to stop" << endl;
9 cin >> x;
10 while (x != -1){
11 sum = sum + x;
12 cin >> x;
13 }
14 cout << "The sum of your numbers is " << sum << endl;
15 return 0;
16 }

12.3 Do...While Loop

The do...while loop is useful when we want the loop body to always execute at least once.
The general form of the loop in C++ looks like this:

do{
<code to execute while the condition holds>
} while (<condition>);

The condition is tested at the end of the loop body, instead of the beginning, so the loop
body is always executed at least once. It is essentially a reversed while loop: a while loop
says “loop while the condition is true, and execute this block of code”, and a do...while loop
says “execute this block of code, and loop while the condition is true”. Take note of the trailing
semicolon — this is the only loop that requires it (the other loops should never be terminated
with one). An example of a while loop is given below.

1 #include <iostream>
2
3 using namespace std;
4
5 int main(){
6 int sum = 0;
7 int x;
8 cout << "Enter some numbers. Type 0 to stop" << endl;
9 do{
10 cin >> x;
11 sum = sum + x;
12 } while (x != 0);
13 cout << "The sum of your numbers is " << sum << endl;
14 return 0;
15 }

18
Question: in the explanation of the while loop, we read in numbers until the user en-
tered −1. If we wanted the above code to stop when we enter −1, can we simply change
line 12 to read while (x != -1); ?

Submission 6: Minimum
Your task here is to write a program that accepts many integers as input, and outputs the
smallest one.

Input
The input consists of a series of integers, one per line. You can assume that there will always
be at least one number given. The end of the input will be signalled by the number −1. When
you receive a −1, your program should then output the smallest number it has seen so far.
Note that −1 should be completely ignored and so should not be taken into consideration when
calculating the smallest number.

Output
Print out the minimum value of the numbers.

Sample Input
2
3
4
5
6
7
1
-1

Sample Output
1

19
Submission 7: Mean
Write a program that accepts many real numbers as input, and outputs their average.

Input
The input consists of a series of numbers, one per line. You can assume that there will always
be at least one number given. The end of the input will be signalled by the number −1. When
you receive a −1, your program should then output the average of all numbers received. Note
that −1 should be completely ignored and so should not be taken into consideration when
calculating the average.

Output
Print out the mean of the numbers.

Sample Input
1.2
1.9
2
5
0
-1

Sample Output
2.02

13 String Handling

The section provides an in-depth look at the concept of strings.

13.1 Characters

Before we look at strings, let’s first discuss characters: the individual units that make up strings.
Characters are declared using the char keyword, and each variable can hold a single character.
A character literal (constant) is a character surrounded by single quotes. For instance, the
following assigns the upper-case letter zed to the variable c:

char c = 'Z';

Each character has its own integer representation, known as it’s ASCII code. This means we
can easily treat characters as integers, applying arithmetic and comparison operators to them
as you would an integer. Unlike Python, C++ automatically handles the conversion between
characters and integers. To illustrate, see the following code:

20
1 #include <iostream>
2

3 using namespace std;


4
5 int main(){
6 int x = 65;
7 char c1 = x; //assign an int to a char
8 cout << "The character value of " << x << " is " << c1 << endl;
9 char c2 = 'a';
10 char c3 = c2 + 1; //add one to a char
11 cout << "The character after " << c2 << " is " << c3 << endl;
12 int y = c3; //assign a char to an int
13 cout << "The integer value of " << c3 << " is " << y << endl;
14 return 0;
15 }

which produces the following output:

The character value of 65 is A


The character after a is b
The integer value of b is 98

There are also special class of characters that correspond to characters that are neither digits,
punctuation or letters. These require an escape sequence to represent, an example of which is
the newline character ’\n’.

13.2 Introduction to Strings

Strings are a series of characters that constitute text. In contract to characters which use single
quotes, string literals are represented by double quotation marks.

C++ provides rich functionality when it comes to dealing with strings; however, strings are
not built-in data types (like int or double). Rather, they are provided by the standard library.
In order to use them, we must ensure we are operating in the standard namespace. Once we’ve
done this, we can simply use strings as if they were a built-in data type. There is one difference,
however, in that if we declare a string without assigning it a value, it will be guaranteed to be
initialised to an empty string1 — built-in data types provide no such guarantee.

13.3 Operators

Much like built-in types, we can apply appropriate operators to two or more strings. For in-
stance, we can assign a string just as we would an integer with the = operator, and we can add
(concatenate) two strings with the + operator. Furthermore, we can also apply various logical
operators: we can test for equality, and check if one string is greater than another (alphabeti-
cally).
1
a string with zero characters.

21
The following illustrates some of these operators being applied to strings:

1 #include <iostream>
2
3 using namespace std;
4
5 int main(){
6 string s1;
7 if (s1 == ""){
8 cout << "s1 is empty" << endl;
9 }
10 string s2 = "hello ";
11 string s3 = "world";
12 string result = s2 + s3;
13 cout << "Concatenating s2 and s3 gives " << result << endl;
14 if (s2 == s3){
15 cout << "s2 and s3 are equal" << endl;
16 }
17 else if (s2 > s3){
18 cout << "s2 is greater than s3" << endl;
19 }
20 else {
21 cout << "s3 is greater than s2" << endl;
22 }
23 return 0;
24 }

and produces the following output:

s1 is empty
Concatenating s2 and s3 gives hello world
s3 is greater than s2

Question: how does the comparison of two strings work? Does it have anything to do
with the ASCII value of their characters?

13.4 Input

Until now, we’ve seen examples of reading input into a string as follows:

1 string name;
2 cin >> name;

What you’ll find, however, is that if we enter a name containing a space, only the characters
up to that space are stored in the variable — the rest are discarded. In order to read an entire
line (including spaces) into a string, use the following:

22
1 string name;
2 getline(cin, name);

13.5 Basic Functionality

Indexing

Because strings are simply a sequence of characters, we can access any character of a given
string at a specific index (position). This is done using the notation <string>[<index>]. For
instance, if we wish to access the first and last character of a string, we’d do the following:

1 string s = "Hello";
2 char firstChar = s[0]; //We start indexing from 0; firstChar is now 'H'
3 char lastChar = s[4]; //The last index is one less than the length of s

We can also change the individual characters of a string by assigning a value to the indexed
character. For instance, to change the first character to an ’A’, we’d have:

1 string s = "Hello";
2 s[0] = 'A'; //s now stores the string "Aello"

Iterating

We can also loop over each character of a string. To do so, we first need to know how many
characters are in a string (so we know when to stop the loop). To do this, we make use of the
length() function that returns an integer specifying the number of characters in a string. The
following example loops over each character in a string and outputs the character along with
its index:

1 #include <iostream>
2

3 using namespace std;


4
5 int main(){
6 cout << "Enter a string " << endl;
7 string s;
8 getline(cin, s);
9 int length = s.length(); //get the length of the string
10 for (int index = 0; index < length; ++index){
11 char c =s[index];
12 cout << "Character " << c << " is at index " << index << endl;
13 }
14 return 0;
15 }

23
Submission 8: Upshift
In the film 2001: A Space Odyssey, the artificially intelligent computer is given the name HAL.
Many people believe this is because if you shift each letter of HAL one more place in the alpha-
bet, you get IBM — the multi-bazillion dollar company.
We would like to know if there are other names with this interesting property. As such, we need
you to write a program that accepts a string, shifts each of its characters to the next one in the
alphabet, and outputs the resulting string.

Input
The input consists of a single string. You may assume that the string contains neither the
character ’Z’ nor ’z’, nor does it contain any spaces.

Output
Display the string that results when each character in the given string is shifted to its following
letter in the alphabet.

Sample Input
HellO

Sample Output
IfmmP

24
Submission 9: Vowel Count
Vowels are a useful feature of the English language[Citation required] . Write a program that counts
how many vowels there are in a bunch of words. For our purposes, the letter ’y’ is not a vowel.
(And, for any Welsh students, neither is ’w’.)

Input
The input consists of lines of text, terminated by a line with the value end. Each line may
contain both upper- and lower-case letters, as well as spaces. Your program should terminate
when it accepts end as input.

Output
For each line, print out the number of vowels the given line contained.

Example Input-Output
Sample Input
Abba Rules!
rhythm
COMS is better than CAM :)
end

Sample Output
4
0
6

25

You might also like