C++ primer exercise 1.19, first attempt at the "if" statement - c++

In an earlier exercise i wrote a program that took two inputs and printed out the numbers between the two numbers. in exercise 1.19, i am asked to rewrite the program so that it can handle the issue of the first number being smaller than the second number. i am asking 2 questions:
i feel as though i played a dirty trick with the if statement that
just switches the numbers around in the correct order. is that bad
coding?
what i wrote works, it "handles" the issue of the user inputting a
number that is smaller than the second. however since i am very new to
programming and only in chapter 1 of C++ primer. am i missing
something important here that would cause me to write the code
"better" (EX: if i understood X concept then i would wrote the "if"
statement better/differently)
int main()
{
int v1 = 0, v2 = 0, e1 = 0, e2 = 0, sum = 0;
std::cout << "Input first integer: ";
std::cin >> v1; std::cout << std::endl;
e1 = v1;
std::cout << "Input secound integer: ";
std::cin >> v2; std::cout << std:: endl;
if (v1 > v2)
{
e1 = v1;
e2 = v2;
v1 = e2;
v2 = e1;
e1 = v1;
}
while (v1 <= v2)
{
sum += v1;
++v1;
}
std::cout << "The inclusive sum of " << e1 << " and " << v2 << " is "
<< sum;
return 0;
}

To answer your second question (and indirectly your first) I recommend that you use the swap function from the C++ Standard Library. You can check it out here. In general, using STL code is better than writing functions yourself (for obvious reasons).
So to implement it in your code, you'll need to first:
#include <algorithm>
Then in the body of that first if statement, just say:
std::swap(v1, v2);

You can use only a single extra variable, and simplify your if considerably.
int v1 = 0, v2 = 0, sum = 0;
std::cout << "Input first integer: ";
std::cin >> v1; std::cout << std::endl;
std::cout << "Input secound integer: ";
std::cin >> v2; std::cout << std:: endl;
if (v1 > v2)
{
int tmp = v1; // Store v1 in a temp variable
v1 = v2; // Move v2's value into v1
v2 = tmp; // Move temp variable into v2
}

What I did for this is used an if else
int main()
{
int val1 = 0, val2 = 0, sum = 0;
std::cout << "Enter in 2 numbers " << std::endl;
std::cin >> val1;
std::cin >> val2;
// if the first value is smaller than the second then do below
if(val1<val2)
{
sum = val1; // setting sum equal to the first value entered
while(val1<=val2) // run while val1 is less than or equal to val2
{
std::cout << sum << std::endl; // printing sum
sum++; // adding +1 to sum
val1++; // adding +1 to val1 otherwise it will print sum to infinity
}
}
else // If the second value is smaller than the first entered do below
{
sum = val2; // setting sum equal to the second value entered
while(val2<=val1)
{
std::cout << sum << std::endl;
sum++; // adding +1 to sum
val2++; // adding +1 to val2 otherwise it will print sum to infinity
}
}
std::cout << "woot!" << std::endl;
return 0;
}
It gets rid of the swapping. Took me a little while to get it. I didn't think I needed to add the val1++ or val2++ so it was just printing out numbers as fast as possible. Cool to look at, but not what I wanted. Hope this helps somebody!
Note: Mine is a little different from what the problem is asking for. Adding a set of numbers together but I believe the same logic can be used.

Related

Array- looping through secondary array

Unable to get the index from the second array to match the first array
// array constants
const int people = 7;
const int phoneNumbers = 7;
int main() {
char person, family;
int index;
string found;
int size =7;
//array declaration and set values
string people [] ={"Darryl","Jasmine","Brian","Duane","Ayana","Mia","Maya"};
// const char phoneNumbers = 7;
string phoneNumbers[] = {"678-281-7649", "818-933-1158", "212-898-2022",
"361-345-3782","817-399-3750","313-589-0460","818-634-4660"};
//set boolean value
found = "False";
//initialize index
index = 0;
// search variable and user input
cout << "who are you looking for? " << endl;
cin >> people[index];
for (index=0; index<=6; index--) {
if (people[index] == people[index] )
cout << "phone num for " << people[index] << " is "<<
phoneNumbers[index] << endl;
}
return 0;
}
When I put in Jasmine which is the people[] array, the phoneNumbers[] array brings back the first index of phoneNumbers[] which it should bring back the second index on phoneNumbers[] array
There are two problems here.
You are replacing content of the people[0] with the cin - so first item of the array will be always user's input.
You are decrement index, so the FOR cycle goes to the indexes 0,-1,-2... This is problem as arrays in C and C++ goes from 0 to upper values.
I would prefer to add one variable:
string input;
then:
cin >> input;
for cycle should be used:
for (index = 0; index < 6; index++)
and in your condition I would use:
if (person[index] == input) ...
A much cleaner way of doing this would be too use std::map provided by the C++ standard template library. Below is my take on what you're trying to achieve:
// phoneNumber.cpp
#include <iostream>
#include <map>
int main()
{
// delcare a map variable that maps people's names to phone numbers
std::map <std::string,std::string> lookUpPhoneNumber = {
{"Darryl", "678-281-7649"},
{"Jasmine", "818-933-1158"},
{"Brian", "212-898-2022"},
{"Duane", "361-345-3782"},
{"Ayana", "817-399-3750"},
{"Mia", "313-589-0460"},
{"Maya", "818-634-4660"}
};
// take input name
std::string inputName;
// user prompt
std::cout << "who are you looking for?: ";
std::cin >> inputName;
// look up name in map
if(lookUpPhoneNumber.find(inputName) != lookUpPhoneNumber.end()){
std::cout << "Phone num for " << inputName << " is: " << lookUpPhoneNumber[inputName] << "\n";
} else{
std::cout << "Name does not exist!\n";
}
return 0;
}
To compile and run, use the following command:
g++ -std=c++11 -o phoneNumber phoneNumber.cpp
./phoneNumber
Or check your compiler option to enable compiling with c++11 standard or higher.

Creating an array

write a program that let's the user enter 10 numbers into an array. The program should then display the largest number as and the smallest number stored in the array.
I am very confused on this question that was on a previous exam and will be on the final. Any help would be appreciated! This is what I had on the test and got 3/15 points, and the code was almost completely wrong but I can post what I had if necessary, thanks! For creating the array, i can at least get that started, so like this?
#include <iostream>
using namespace std;
int main()
{
int array(10); // the array with 10 numbers, which the user will enter
cout << "Please enter 10 numbers which will be stored in this array" << endl;
cin >> array;
int smallest=0; //accounting for int data type and the actual smallest number
int largest=0; //accounting for int data type and the actual largest number
//-both of these starting at 0 to show accurate results-
And then on my test, i started using for loops and it got messy from there on out, so my big problem here i think is how to actually compare/find the smallest and largest numbers, in the best way possible. I'm also just in computer science 1 at university so we keep it pretty simple, or i like to. We also know binary search and one other search method, if either of those would be a good way to use here to write code for doing this. Thanks!
Start by declaring an array correctly. int array(10) initializes a single integer variable named array to have the value 10. (Same as saying int array = 10)
You declare an array of 10 integers as follows:
int array[10];
Anyway, two simple loops and you are done.
int array[10];
cout << "Enter 10 numbers" << endl;
for (int x = 0; x < 10; x++)
{
cin >> array[x];
}
int smallest=array[0];
int largest=array[0];
for (int x = 1; x < 10; x++)
{
if (array[x] < smallest)
{
smallest = array[x];
}
else if (array[x] > largest)
{
largest = array[x];
}
}
cout << "Largest: " << largest << endl;
cout << "Smallest: " << smallest << endl;
You can actually combine the two for loops above into a single loop. That's an exercise in an optimization that I'll leave up to you.
In this case, you don't actually have to do a binary search, or search the array. Since you will be receiving the input directly from the user, you can keep track of minimum and maximum as you encounter them, as show below. You know the first number you receive will be both the min and max. Then you compare the next number you get with those ones. If it's bigger or smaller, you store it as the max or min respectively. And then so on. I included code to store the number in an array, to check errors and to output the array back to the user, but that's probably not necessary on an exam due to the limited time. I included it as a little bit of extra info for you.
#include <cctype> // required for isdigit, error checking
#include <cstdlib> // required for atoi, convert text to an int
#include <iostream> // required for cout, cin, user input and output
#include <string> // required for string type, easier manipulation of text
int main()
{
// The number of numbers we need from the user.
int maxNumbers = 10;
// A variable to store the user's input before we can check for errors
std::string userInput;
// An array to store the user's input
int userNumbers[maxNumbers];
// store the largest and smallest number
int max, min;
// Counter variables, i is used for the two main loops in the program,
// while j is used in a loop for error checking
int i;
unsigned int j;
// Prompt the user for input.
std::cout << "Please enter " << maxNumbers << " numbers: " << std::endl;
// i is used to keep track of the number of valid numbers inputted
i = 0;
// Keep waiting for user input until the user enters the maxNumber valid
// numbers
while (i < maxNumbers)
{
// Get the user's next number, store it as string so we can check
// for errors
std::cout << "Number " << (i+1) << ": ";
std::cin >> userInput;
// This variable is used to keep track of whether or not there is
// an error in the user's input.
bool validInput = true;
// Loop through the entire inputted string and check they are all
// valid digits
for (j = 0; j < userInput.length(); j++)
{
// Check if the character at pos j in the input is a digit.
if (!isdigit(userInput.at(j)))
{
// This is not a digit, we found an error so we can stop looping
validInput = false;
break;
}
}
// If it is a valid number, store it in the array of
// numbers inputted by the user.
if (validInput)
{
// We store this number in the array, and increment the number
// of valid numbers we got.
userNumbers[i] = atoi(userInput.c_str());
// If this is the first valid input we got, then we have nothing
// to compare to yet, so store the input as the max and min
if (i == 0)
{
min = userNumbers[i];
max = userNumbers[i];
}
else {
// Is this the smallest int we have seen?
if (min < userNumbers[i])
{
min = userNumbers[i];
}
// Is this the largest int we have seen?
if (max < userNumbers[i])
{
max = userNumbers[i];
}
}
i++;
}
else
{
// This is not a valid number, inform the user of their error.
std::cout << "Invalid number, please enter a valid number." << std::endl;
}
}
// Output the user's numbers to them.
std::cout << "Your numbers are: " << userNumbers[0];
for (i = 1; i < maxNumbers; i++)
{
std::cout << "," << userNumbers[i];
}
std::cout << "." << std::endl;
// Output the min and max
std::cout << "Smallest int: " << min << std::endl;
std::cout << "Largest int: " << max << std::endl;
return 0;
}

An exercise asks me to change the body of the loop. What does it mean?

I am fairly new to C++ still, as well as programming and the terms used. I'm learning off of "Programming: Principles and Practice Using C++" (as was gifted to me) and I ran into a problem on a Drill at the end of chapter four. The drill is split into twelve exercises, where the first five are as follows:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
I've dealt with those exercises, but now I don't quite get what to do in the next exercise:
Now change the body of the loop so that it reads just one double each time around. Define two variables to keep track of which is the smallest and which is the largest value you have
seen so far. Each time through the loop write out the value entered. If it’s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number.
I don't get it. What should I do with the loop? What's exercise 6 actually about?
My code I have made up so far from step five is as follows:
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
double one = 0.0;
double two = 0.0;
int one_i = one;
int two_i = two;
while (terminate != '|')
{
std::cout << "Input two numbers, follow each one by enter: " << std::endl;
std::cin >> one;
std::cin >> two;
if (one == two)
{
std::cout << "The two numbers are equal to each other." << std::endl;
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
if (terminate == '|')
{
break;
}
}
std::cout << "Here is the larger value: ";
if (one > two)
{
std::cout << one << std::endl;
}
else
{
if (two > one)
{
std::cout << two << std::endl;
}
}
std::cout << "Here is the smaller value: ";
if (one < two)
{
std::cout << one << std::endl;
if (one_i == two_i || two_i == one_i)
{
std::wcout << "The numbers are almost equal." << std::endl;
}
}
else
{
if (two < one)
{
std::cout << two << std::endl;
if (one_i == two_i || two_i == one_i)
{
std::wcout << "The numbers are almost equal." << std::endl;
}
}
}
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
}
}
I attempted to figure out the problem if this code helps any of you see as to what degree I'm confused on.
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
std::vector<double>num_size;
while (terminate != '|')
{
std::cout << "Type in a number: " << std::endl;
for (double num; std::cin >> num;)
{
num_size.push_back(num);
std::sort(num_size.begin(), num_size.end());
}
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
}
}
Well, you didn't finish step 5. 999 and 1000 are almost equal (difference < 1%).
Ignoring that, your second fragment is a good start at producing the behavior wanted in step 6 but ignores the prescribed method. Yes, a sorted vector has a .front() and a .back() which are the respective minimum and maximum, but step 6 specifically told you to use two variables instead of a whole vector.
So double max = std::numeric_limits<double>::max(); double min = -max; and from there on you should be able to figure it out.
You want something like:
double my_max = numeric_limits<double>::max();
double my_min = -1 * numeric_limits<double>::max();
while (...) {
...
my_min = min(my_min, one);
my_min = min(my_min, two);
my_max = max(my_max, one);
my_max = max(my_max, two);

Addition and subtraction of arrays

I have been working on this all day but just cant get the output right.
What I want to do is input two numbers, which would be pushed into two arrays so we can subtract or add them and display the result. Seems simple, but there are few catches
Input must be pushed into the array, from the user, one by one.
In case I don't enter a value, code should assume it to be '0' or 'null'. '0' if its in the beginning and 'null' if its in the end. for example if 1st number is 234 and second number is 23 then code should make it into '023' and if I enter first number as 2, 2nd number as 3 but don't enter anything in the end then code should assume it to be null.
Problems
I cant take 'carry' to the next set, in case the sum is greater than 10. Which means the value I m getting is just addition of two numbers doesn't matter if its greater than 10 or not. for example addition of 234 and 890 is giving me [10, 12, 4]
Here is the code.....
#include<iostream>
using namespace std;
main() {
int first[10], second[10], result[10], c, n;
cout << "Enter the number of elements in the array ";
cin >> n;
if (n > 10 || n < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
cout << "Enter elements of first array " << endl;
for (c = 0; c < n; c++) {
cin >> first[c];
if (first[c] > 9 || first[c] < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
}
cout << "Enter elements of second array " << endl;
for (c = 0; c < n; c++)
cin >> second[c];
cout << "Sum of elements of two arrays " << endl;
for (c = 0; c < n; c++)
cout << first[c] + second[c] << endl;
if ((first[c] + second[c]) > 9) {
cout << "overflow" << endl;
}
//result[c] = first[c] + second [c];
//cout << result[c] <<endl;
system("PAUSE");
return 0;
}
I would really appreciate some suggestions.
In case your intention is to have the result of e.g.
234 + 890 = 1124
then your summation loop should be in reverse order.
(Since you are reading number of elements of the array from the prompt, you may use this information to input first/second numbers into each array in the order preferred for the following summation loop.)
For the carry problem, you need to setup a variable and use it in the loop like this, for example.
int sum[10] = {0};
int c;
int carry = 0;
for (c = 0; c < n; c++)
{
sum[c] = first[c] + second[c] + carry;
carry = sum[c] / 10;
}
if (c < n)
sum[c] = carry;
else
cout << "overflow";
Use std::vector and learn how to use reverse iterators. So if someone enters 234 you push_back(2), push_back(3), push_back(4) and have [0]=2,[1]=3,[2]=4. Then if the next number is 23 you have [0]=2,[1]=3. Now walk both vector with reverse iterators so the first call to rbegin() will give a pointer to [2]=4 and the other vector will give [1]=3. Now add and carry using push_back into a third vector to store the result. Output the result using reverse iterators to print the result.
This looks like homework, so no sample code.

Print numbers in range of two user-input values with while loop

I feel like I might be missing something here, but something is telling me that I might just be making this more difficult that it has to be, but from the book, "C++ Primer, 5th ed.," I'm stuck on this problem:
Exercise 1.11: Write a program that prompts the user for two integers.
Print each number in the range specified by those two integers.
Up until this time in the book, the only loop being used is the while loop, and no conditional expressions, like if, have been introduced. The problem would be simple if it were not for the fact that a user could put the values into the integers asked for in ascending or descending order, so simple subtraction WOULD find the difference, but without testing which way to increment.
How could I absolutely print the range between the numbers, guaranteeing not to just increment towards infinity without testing the outcome of such math and/or without comparing the two numbers? This is what I have; it works when the first value: v1 is less than or equal to the second: v2, but not otherwise:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): "
<< endl;
std::cin >> v1 >> v2;
while (v1 <= v2)
{
std::cout << v1;
++ v1;
}
return 0;
}
Any help would be greatly appreciated!
Here is a simple rewrite where you use min and max to determine the range you want to iterate on:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): " << std::endl;
std::cin >> v1 >> v2;
int current = std::min(v1, v2);
int max = std::max(v1, v2);
while (current <= max)
{
std::cout << current << std::endl;
++ current;
}
return 0;
}
This also allows you to keep the two inputs "intact", because you're using another variable to iterate on the values.
Also note that the ++current could be done on the exact same line it is printed if it was replaced by current++. The later would return the current value of current and THEN increment it.
Edit
Here's what Michael suggested I believe, in working code:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter two integers to find numbers in their range (inclusive): " << std::endl;
std::cin >> v1 >> v2;
int increment = (v2 - v1) / std::abs(v2 - v1);
int current = v1;
int max = v2 + increment;
while (current != max)
{
std::cout << current << std::endl;
current += increment;
}
return 0;
}
You can use (v2-v1)/abs(v2-v1) or some such for increment. (provided they're not equal). And for loop condition you may check if current number is still in between, like (v1<=v && v<=v2) || (v2<=v && v<=v1).
And to avoid the case of zero, I'd turn it into do while loop and use v1!=v2 && ... as a condition.
To sum it all up:
int v = v1;
do {
std::cout << v << std::endl;
}while( v1!=v2 && ( (v1<=(v+=(v2-v1)/std::abs(v2-v1)) && v<=v2) || (v2<=v && v<=v1) ) );
P.S. I trust you can resolve the input issue mentioned in comments and in the other answer on your own.
I tried my amateur way and got the result. I hope it will be helpful.
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int val;
cout << "Please enter small value "<< endl;
cin >> a;
cout << "Please enter bigger value than the last one " << endl;
cin >> b;
while (val>a)
{
val = --b;
cout << "The numbers between a & b are "<< val << endl;
}
return 0;
}
Since I still remember this problem from the C++ Primer, I think the way they wanted you to solve it was with the basics of programming they provided you until then.
In my opinion it should have been solved like this, if this was this exact problem from this book:
#include <iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cout << "Enter 2 numbers" << std::endl;
std::cin >> v1 >> v2;
while (v1 < v2) {
std::cout << v1 << std::endl;
++v1;
}
}