By the way, happy 3.14 day.
Is there a program that can calculate pi to xx number of digits? Haven't heard of one yet...
Recently I came across some old newbie-code I had done to determine min and max between two inputted numbers. It wasn't very fancy, and I was initially stumped as to why it kept assigning the wrong numbers to min and max, only to realize it was me who was labeling the maximum/minimum wrong in the strings. go figure.
Thankfully, it's easier to find the max and min of any number within a given array (suppose the size = N). The logic flows like this: going through each number in the array, check the number (using if) to confirm if it is greater than the starting number, array[0], if so then the max number is the number at position array[a]. Next check the same number (using if) to confirm if it is less than min (which is also assigned array[0]), if so the min number is the position at array[a]. If neither condition passes, the loop moves on to the next number in the array.
For instance if the array was: int array[N] = {5, 9, 2, 6, 10, 1} and N = 5;
int max = array[0];
int min = array[0];
The loop would assign max and min as follows:
iteration 0
5 (array[0]) larger than max (array[0])? 5 !> 5, so max = array[0].
5 (array[0]) smaller than min (array[0])? 5 !< 5, so min = array[0].
iteration 1
9 (array[1]) larger than max (array[0])? 9 > 5, so max is now assigned array[1].
9 (array[1]) smaller than min (array[0])? 9 !< 5, so min remains as array[0].
iteration 2
2 !> 9, max = array[1].
2 < 5, min is now assigned array[2].
iteration 3
6 !> 9, max = array[1].
6 !< 2, min = array[2].
iteration 4
10 > 9, max is now assigned array[4].
10 !< 2, min = array[2].
iteration 5
1 !> 10, max = array[4].
1 < 10, min is now assigned array[5].
So the maximum integer is 10, and minimum integer is now 1.
Note that max and min are passed by reference & so the function can directly modify their contents using the loop. This is a kinda roundabout way to return two different variables from a function without using return, if the two variables are introduced in the main program before calling the function, as return can only return one variable per function.
Showing posts with label snafu. Show all posts
Showing posts with label snafu. Show all posts
Sunday, March 15, 2015
Saturday, March 7, 2015
Post #6 - Random numbers
I usually end up being behind a post if I have homework or other life stuff going on that needs to get done, so here's a program that was going to be posted yesterday.
Using the libraries cstdlib for the srand() and rand() functions, and ctime for the time() function, the program displays a random year within the range 1985 - 2015. The range limit is achieved by setting the random year to display equal to the remainder of the randomly generated number divided by 31, resulting in an integer between 0 and 30 (the computer counts starting from 0, not starting from 1, so in our counting style 0-30 would be 1-31).
We want the difference of the years (2015 - 1985 = 30) plus the starting year (1985) to be the range of the random year, but if 30 was used as the divisor, the range would be one year off from 2015 (since in computer numbers, (0 + 29) = 1-30, it would count from (0 + 1985) to (29 + 1985) which is 1985 - 2014). The off-by-one error can be fixed, because another 1 was not added to 30 to account for 2015 as one of the years, just change 30 to 31, thus raising the range to 1-31 and including 2015 in the computer's random years selection.
This sounds confusing but try reading the 0 of the modulus (%) results as a 1, and adding 1 to every integer in the range including the last number. This kinda converts it to human-range starting with 1, and to convert back, subtract 1 from every number for counting from 0.
Here's the output:
This program randomly chooses a year between 1985 and 2015.
The random year is 1985
Using the libraries cstdlib for the srand() and rand() functions, and ctime for the time() function, the program displays a random year within the range 1985 - 2015. The range limit is achieved by setting the random year to display equal to the remainder of the randomly generated number divided by 31, resulting in an integer between 0 and 30 (the computer counts starting from 0, not starting from 1, so in our counting style 0-30 would be 1-31).
We want the difference of the years (2015 - 1985 = 30) plus the starting year (1985) to be the range of the random year, but if 30 was used as the divisor, the range would be one year off from 2015 (since in computer numbers, (0 + 29) = 1-30, it would count from (0 + 1985) to (29 + 1985) which is 1985 - 2014). The off-by-one error can be fixed, because another 1 was not added to 30 to account for 2015 as one of the years, just change 30 to 31, thus raising the range to 1-31 and including 2015 in the computer's random years selection.
This sounds confusing but try reading the 0 of the modulus (%) results as a 1, and adding 1 to every integer in the range including the last number. This kinda converts it to human-range starting with 1, and to convert back, subtract 1 from every number for counting from 0.
Here's the output:
This program randomly chooses a year between 1985 and 2015.
The random year is 1985
This program randomly chooses a year between 1985 and 2015.
The random year is 2000
This program randomly chooses a year between 1985 and 2015.
The random year is 2015
After re-running this one for a while, 2015 finally appeared (1/30% chance...) (thought something was wrong with my logic for a sec. turns out it just needed more chances to occur).
The off-by-one is easy to miss, so when in doubt, know that the computer almost always starts counting from 0 and a simple overlooked thing like adding 1 can cause the range to fall into place correctly.
Wednesday, March 4, 2015
Post #3 - More on cin
Ok, so I wasn't able to get a post up yesterday because I had other obligations and there was no wi-fi where I was at, and I was too tired to start up a computer at 11PM when I had to get up early in the morning today. So here's a continuation post, even if it's not on the 3rd (which would have been a great way to track these, corresponding the day to the post and whatever. Post #4 will come right after this one, so getting back on track here lol.)
Where was that program at? Oh I was going to put in the city and country too. After testing it out from the previous post, it looks like I was a bit mixed up myself lol. getlines do work following each other; it's interchanging cin and getline that causes input skips (more on that below).
For instance I added additional input prompts to the last one, 3 getlines and 1 cin to show how this works:
With a do-while loop, the program continues to prompt the user to continue and repeats if 'y' for yes is entered (think videogame ending menus). Mine is a bit simplified - the logic behind getting it to continue on 'y', quit on 'n' but repeat the continue statement for any other letter is a bit tricky to implement, so for now it only looks for a 'y' to continue, any other letter causes it to quit.
do{ [...] cin >> confirm [...] }while(confirm == 'y' || confirm == 'Y');
The program continues as long as the user enters y or Y for confirm because of the loop's check condition - it "does" the code inside the loop "while" the condition remains true.
The highlighted cin.ignore(); is particularly important - without this, the program skips any input of the prompt at the beginning of the loop. Upon returning to the start of this loop with the name prompt, it will read the '\n' inside the input buffer instead. When a letter is entered for confirm through cin, the new line from the [Enter] key is added to the end of the char input. When the loop returns to the beginning, getline() reads the new line still held as input and interprets it as the user pressing the [Enter] without giving any input. To the tester, it looks like the program skipped the user's turn to input their name and went straight to the city prompt, because the program still has the leftover newline in the buffer from the end of the loop.
cin >> confirm;
cin.ignore();
To fix this, cin.ignore(); should be un-commented. cin.ignore() can work with several parameters (for example, cin.ignore(5) "ignores 5 characters", or cin.ignore(12, 'u') to "ignore 12 characters or until character 'u' is found"). However the default behavior of cin.ignore() - with nothing in the parentheses - is to skip the next immediate character in the buffer. If the user enters 'y', 'y' is stored in confirm, and the '\n' from the [Enter] is ignored. Since 'y' makes the loop true, the loop returns to the beginning, and since the input buffer has nothing in it after the ignored newline, the program will correctly prompt the user with a getline() for their name again without getting the newline unintentionally.
With this added, the program will now continue to prompt three times and display the inputs until the user enters anything other than 'y' or 'Y' at "Continue".
output without ignore:
Enter your name: Enter your city: Los angeles
Enter your country: California
Hi! My name is .
I live in Los angeles, California.
Continue? (Y/N): n
output with ignore:
Enter your name: Suika-chan
Enter your city: a tree
Enter your country: near Hakurei Shrine
Hi! My name is Suika-chan.
I live in a tree, near Hakurei Shrine.
Continue? (Y/N): n
Where was that program at? Oh I was going to put in the city and country too. After testing it out from the previous post, it looks like I was a bit mixed up myself lol. getlines do work following each other; it's interchanging cin and getline that causes input skips (more on that below).
For instance I added additional input prompts to the last one, 3 getlines and 1 cin to show how this works:
With a do-while loop, the program continues to prompt the user to continue and repeats if 'y' for yes is entered (think videogame ending menus). Mine is a bit simplified - the logic behind getting it to continue on 'y', quit on 'n' but repeat the continue statement for any other letter is a bit tricky to implement, so for now it only looks for a 'y' to continue, any other letter causes it to quit.
do{ [...] cin >> confirm [...] }while(confirm == 'y' || confirm == 'Y');
The program continues as long as the user enters y or Y for confirm because of the loop's check condition - it "does" the code inside the loop "while" the condition remains true.
The highlighted cin.ignore(); is particularly important - without this, the program skips any input of the prompt at the beginning of the loop. Upon returning to the start of this loop with the name prompt, it will read the '\n' inside the input buffer instead. When a letter is entered for confirm through cin, the new line from the [Enter] key is added to the end of the char input. When the loop returns to the beginning, getline() reads the new line still held as input and interprets it as the user pressing the [Enter] without giving any input. To the tester, it looks like the program skipped the user's turn to input their name and went straight to the city prompt, because the program still has the leftover newline in the buffer from the end of the loop.
cin >> confirm;
cin.ignore();
To fix this, cin.ignore(); should be un-commented. cin.ignore() can work with several parameters (for example, cin.ignore(5) "ignores 5 characters", or cin.ignore(12, 'u') to "ignore 12 characters or until character 'u' is found"). However the default behavior of cin.ignore() - with nothing in the parentheses - is to skip the next immediate character in the buffer. If the user enters 'y', 'y' is stored in confirm, and the '\n' from the [Enter] is ignored. Since 'y' makes the loop true, the loop returns to the beginning, and since the input buffer has nothing in it after the ignored newline, the program will correctly prompt the user with a getline() for their name again without getting the newline unintentionally.
With this added, the program will now continue to prompt three times and display the inputs until the user enters anything other than 'y' or 'Y' at "Continue".
output without ignore:
Enter your name: Enter your city: Los angeles
Enter your country: California
Hi! My name is .
I live in Los angeles, California.
Continue? (Y/N): n
output with ignore:
Enter your name: Suika-chan
Enter your city: a tree
Enter your country: near Hakurei Shrine
Hi! My name is Suika-chan.
I live in a tree, near Hakurei Shrine.
Continue? (Y/N): n
Monday, March 2, 2015
Post #2 - Last names
Images are now externally hosted on my imgur. please tell me if an image is unavailiable.
Here's a modification to the last one - what if the user wants to enter his/her last name too?
But entering a full name into the previous program results in an output problem - because cin is designed to stop when it reaches a whitespace in the input buffer, it places whatever string up until the whitespace into the variable, and leaves the rest in the input buffer. This can cause additional snafus as, when reading in multiple characters or strings, variables may not be given the full string that they are supposed to receive.
For example if I wanted to type out Have a nice day and display the entire line, there are a few options:
I would have to assign a variable to each word and show each string within a cout statement. However, since cin skips whitespace, the message all runs together.
cin >> part1 >> part2 >> part3 >> part4;
cout << part1 << part2 << part3 << part4;
The same output is also displayed when altering cout to be:
cout << part1 + part2 + part3 + part4;
in: Have a nice day
out: Haveaniceday
To fix the display, I could add spaces to the cout statement to make things look better.
cin >> part1 >> part2 >> part3 >> part4;
cout << part1 << " " << part2 << " " << part3 << " " << part4;
in: Have a nice day
out: Have a nice day
But this uses up more variables than necessary. To display everything at once using a single string variable, the full string also needs to be read into a single string variable.
We can use the function getline(a, b); to save the entire input read from a into the string variable b. getline picks up any whitespace it finds in the string, until it reaches the end of the string (marked invisibly by '\n' which is automatically appended to the end when the [Enter] key is pressed to submit the string). In most cases a will almost always be cin, as input is actually read into the standard input stream and then saved to b, an appropriate type variable, usually a string.
Now since cin is included within the getline function, the cin >> operator can be removed, since cin is already being called by the function.
getline(cin, name);
And to display the full input, just output the variable.
cout >> name;
The previous program with line 8 changed:
Here's the previous program's output when given two names:
Enter your name: Yukkuri Reimu
Hi! My name is Yukkuri.
Here's the modified version using getline, displaying both names.
Enter your name: Yukkuri Reimu
Hi! My name is Yukkuri Reimu.
For the next post, the program will read in a city and country along with the full name. This makes use of several getlines, which often run into problems with continued input. We'll see how the ignore member function can be used to keep input from becoming mixed up.
Here's a modification to the last one - what if the user wants to enter his/her last name too?
But entering a full name into the previous program results in an output problem - because cin is designed to stop when it reaches a whitespace in the input buffer, it places whatever string up until the whitespace into the variable, and leaves the rest in the input buffer. This can cause additional snafus as, when reading in multiple characters or strings, variables may not be given the full string that they are supposed to receive.
For example if I wanted to type out Have a nice day and display the entire line, there are a few options:
I would have to assign a variable to each word and show each string within a cout statement. However, since cin skips whitespace, the message all runs together.
cin >> part1 >> part2 >> part3 >> part4;
cout << part1 << part2 << part3 << part4;
The same output is also displayed when altering cout to be:
cout << part1 + part2 + part3 + part4;
in: Have a nice day
out: Haveaniceday
To fix the display, I could add spaces to the cout statement to make things look better.
cin >> part1 >> part2 >> part3 >> part4;
cout << part1 << " " << part2 << " " << part3 << " " << part4;
in: Have a nice day
out: Have a nice day
But this uses up more variables than necessary. To display everything at once using a single string variable, the full string also needs to be read into a single string variable.
We can use the function getline(a, b); to save the entire input read from a into the string variable b. getline picks up any whitespace it finds in the string, until it reaches the end of the string (marked invisibly by '\n' which is automatically appended to the end when the [Enter] key is pressed to submit the string). In most cases a will almost always be cin, as input is actually read into the standard input stream and then saved to b, an appropriate type variable, usually a string.
Now since cin is included within the getline function, the cin >> operator can be removed, since cin is already being called by the function.
getline(cin, name);
And to display the full input, just output the variable.
cout >> name;
The previous program with line 8 changed:
Here's the previous program's output when given two names:
Enter your name: Yukkuri Reimu
Hi! My name is Yukkuri.
Here's the modified version using getline, displaying both names.
Enter your name: Yukkuri Reimu
Hi! My name is Yukkuri Reimu.
For the next post, the program will read in a city and country along with the full name. This makes use of several getlines, which often run into problems with continued input. We'll see how the ignore member function can be used to keep input from becoming mixed up.
Subscribe to:
Posts (Atom)



