adding digits in an array c++ - c++

I'm new to C++ and i was trying to understand how to work with arrays. The idea I have is:
I wanted a user to input an array, the program to output the
array
Double all the values in the array and output that
And for each of the doubled values, add the digits of the doubled number
(1 digit number would remain the same), then output the new numbers as
well.
(e.g. if the array was [5, 6, 7, 8], the doubled values would be [10, 12, 14, 16] and then you would add each values digits like, [1+0, 1+2, 1+4, 1+6] to get [1, 3, 5, 7].
I put my code to show my progress, feel free to point out any errors along the way!
Any help is appreciated!
p.s. The nested loop didn't work :(
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i];
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j];
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
for (int k=0;k<maxNum;k++)
{
for (int l=0;l<maxNum;l++)
{
int sum[20];
while (num[k]!=0)
{
sum[l]=sum[l]+num[k]%10;
num[k]=num[k]/10;
}
}
cout << sum[l];
}
cout << endl;
}

A few things:
maxNum and num[] are never initialized, it's dangerous.
that is not how you scan input. Ideally you woud do smth like while(cin >> tem_var){}. Or you could modify it to be if( !(cin >> num[i]) ) break;. That way you don't need to do maxNum-1 later too. (cin>>) will be True if it reads a variable succesfully and False otherwise. That way you can stop scanning by entering any non-number string, instead of running the loop for the rest of iterations, but leaving num[i] uninitialized if that happens.
you forget to output delimeters between array numbers which makes it hard to read.
cout << num[i] << "|"; or smth.
In the last part you make 3 loops: a k for loop that you never use, a l for loop to iterate num, and a k while loop to sum the digits. One of them is not necessary.
In the last part sum[] array, though filled correctly, is not outputted. You declare it inside the l loop, meaning it's deleted when you exit it. And even if you declared it outside. your cout << sum[l]; is outside the l loop, meaning it will only try to do the cout << sum[maxNum]; (the value of l the loop finishes with) while you only have [0:(maxNum-1)] elements in num and sum filled.
I'd suggest you try smth like for(k=1;k<num[l];k*=10) sum[l]+= num[l] / k % 10; instead of that while loop. It's shorter, gets the job done and leaves num[l] unchaged in case you decide to use it again afterwards.

You need to initialize sum array with all zeros first. You don't need nested loop.
Create a sum array to store the sum of each number and initialize it with 0's. First write a loop to traverse through the elements of the doubled array. For each element write a loop(you chose while loop) to traverse through the digits of each number and them to the corresponding sum element.
I've modified your code a little bit, go through it once.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum-1;i++)
cout << num[i]<<' ';
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum-1;j++)
{
num[j]*=2;
cout << num[j]<<' ';
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int sum[20];
for (int i=0;i<maxNum-1;i++)
sum[i]=0;
for (int k=0;k<maxNum-1;k++)
{
// for (int l=0;l<maxNum;l++)
// {
while (num[k]!=0)
{
sum[k]=sum[k]+num[k]%10;
num[k]=num[k]/10;
}
cout << sum[k]<<' ';
// }
}
cout << endl;
}

You don't need nested loop for that ,while making logic behind any program take a simple example and get the result,Don't jump directly to code. This will help you to building logics.
#include <iostream>
#include <string>
using namespace std;
int maxNum;
int num[20];
int main()
{
int sum=0;
cout << "Enter an Array" << endl;
for (int i=0;i<20;i++)
{
cin >> num[i];
maxNum++;
if (num[i]==-1)
break;
}
cout <<"Your array is: " << endl;
for (int i=0;i<maxNum;i++)
cout << num[i]<<ends;
cout << endl;
cout << "Your doubled array is:" << endl;
for (int j=0;j<maxNum;j++)
{
num[j]*=2;
cout << num[j]<<ends;
}
cout << endl;
cout << "When the digits of each seat are added..." << endl;
int r=0;
for (int k=0;k<maxNum;k++)
{
while (num[k]>0)
{
r=num[k]%10;
sum+=r;
num[k]=num[k]/10;
}
cout<<sum<<ends;
sum=0;
r=0;
}
cout << endl;
}

Related

How to loop the program's asking for new set of inputs in c++?

Consider the following code:
#include <iostream>
using namespace std;
int main(){
int a,b;
cout << "Enter two positive numbers:" <<endl;
cin >> a >> b;
if (a<b) cout <<a<<" is less than "<< b<<endl;
else if (a>b) cout <<a<<" is greater than " <<b<<endl;
}
How can I make the program endlessly repeat asking for a new set of numbers as input?
Here's the simplest way of doing what you want (there are other ways). Basically, you just need to 'wrap' the code that you want to repeat in a loop, where the 'test' condition for the loop will always evaluate to true.
Note the comments with "///" I've given:
#include <iostream>
//using namespace std; /// Search this site for "Why using namespace std is bad"
using std::cout;/// Just declare usage of those feature you ACTUALLY use...
using std::cin;
using std::endl;
int main() {
int a, b;
while (true) { /// The test condition will always be "TRUE" so the loop will never end!
cout << "Enter two positive numbers:" << endl;
cin >> a >> b;
if (a < b) cout << a << " is less than " << b << endl;
else if (a > b) cout << a << " is greater than " << b << endl;
// cout /// This line is wrong!
}
}
Feel free to ask for further clarification and/or explanation.
Depends on what exactly do you want your program to do. If you want it to "deny access". For example lets say you have want a number K > 3 always for the program to continue. The all you have to do is use a do- while loop:
do
{
cout << "Enter the value for the sequence: ";
cin >> K;
if ( K <= 3)
{
cout << "Write a bigger number!" << endl;
}
} while(K <= 3);
Otherwise just use a normal loop with the condition suitable for the task.
Suppose your program is to find the Factorial of number and you want it to loop such that it ask for new value from the user
int main()
{
int n;
while (true) {
int factorial = 1;
cin >> n;
if (n==0) {
cout << 0;
}
else {
for (int i=n;i>0;i--) {
factorial = factorial*i;
}
cout << factorial;
}
}
return 0;
}

How to add numbers bigger than long long, long, int and etc C+11

forum!
I have a project where we are supposed to add numbers that are length 14 or greater. I did some digging and realized that there is no current type that takes numbers this big. So, I have the user enter the numbers as a string and the numbers they would like to add are stored in a static string array.
I would like to add the numbers from the static array together. The issue is I have no idea how to deal with numbers this large. I am assuming you would have to convert the string values into int's and add them up one by one? I am having a big issue coming up with the logic for this. Any help would be appreciated.
If not, if you can provide some context which could help me come up with some logic.
The only library functions I can use is iostream and string.
Here is my code if you'll like to see my logic! I have some test cases I am trying to figure out so please ignore the comment outs. But, if you run the code you should get a better sense of what I am trying to get out. I am trying to sum up the numbers the user enters.
#include <iostream>
#include <string>
using namespace std;
void amountOfNumbers(string &userAmount, int MIN_AMOUNT, int MAX_AMOUNT){
//string alpha = "abcdefghijklmnopqrstuvwxyz";
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
while(!userAmount.find("abcdefghijklmnopqrstuvwxyz")){
cout << "ERROR: must be a number, try again ->";
cout << userAmount;
//cin.clear();
//cin.ignore(1000, '\n');
cin >> userAmount;
cout << endl;
}
int temp = stoi(userAmount);
while((temp < MIN_AMOUNT) or (temp > MAX_AMOUNT)){
cout << "ERROR: Program can only take in " << MIN_AMOUNT << " - "<< MAX_AMOUNT << " numbers. Try again ->";
cin >> userAmount;
cout << endl;
temp = stoi(userAmount);
}
}
void takeNumbers(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << "Input number #" << i+1 << " ->";
cin >> numberArray[i];
cout << endl;
}
}
void display(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << numberArray[i];
cout << endl;
}
}
void addNumber(string &userAmount, string (&numberArray)[11]){
}
int main() {
const int MIN_AMOUNT = 2, MAX_AMOUNT = 11, MAX_INPUT = 14;
string userAmount = "0";
string numberInput;
// static array
string numberArray [MAX_AMOUNT];
amountOfNumbers(userAmount, MIN_AMOUNT, MAX_AMOUNT);
takeNumbers(userAmount, numberArray);
display(userAmount, numberArray);
}

Nested loops C++

So I am making a program that will create a square based on the users desired size. My code so far reads the value, prints out the top of the square but i'm getting caught up on how to set up the sides because of a nested loop I've created. The issue here is that I need for the loop to reset it's values every time it exists.
Here's my code so far:
#include <iostream>
using namespace std;
int main(int,char**) {
int x;
int z=1;
int l=0;
int n=0;
int q=1;
int m=0;
int o=0;
do{
cout << "Enter length between 0 and 64 (-1 to exit): ";
cin >> x;
if (x>-1&&x<64){
cout << "+";
for (;x-2!=n;++n){
cout << "-";
}
cout << "+" << endl;
}
else{
cout << "Length must be between 0 and 64 inclusive, or enter -1 to exit.";
}
do {
cout << "|";
do {
//cout << " ";
//++m;
//}while (x-2!=m);
cout << "|" << endl;
++o;
}
while (x-2!=o);
++z;
}
while (z!=5);
}
The commented out portion is where the program is getting caught up at, it seems that when I increment m until it exits the do while loop, it holds onto the value that it was incremented to. I know that a continue statement breaks from the loop and begins a new iteration of the loop but it doesn't seem to want to fit inside the do-while loop even if i create an if statement such as
if (x-2==m){
continue;
}
Any help would be appreciated
Just put m = 0; before the loop.
m = 0;
do {
cout << ' ';
++m;
} while (x-2 != m);
Or use a for loop instead;
for (int m = 0; m != x-2; m++) {
cout << ' ';
}
This is the more common idiom for repeating something a certain number of times, since you can see all the conditions related to the loop in a single place.

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

Sudoku game design problems C++

I have (yet another) question about chars. Thanks to those who helped me with this before. I'm trying to do mainly 4 things at this point in the program. That is:
Build a 2D array 9x9 and fill it with underscores.
Ask for a row/column and then the number that the user wishes to go into that row/column as many times as the user wants.
Replace the specified blanks with the specified numbers.
Output the entire 9x9 char array on an ASCII art Sudoku board.
(Solving will come later.)
My problem is that when I enter the row/column and the number that I want to go into that row/column the dash that was originally in that spot disappears, but the number I entered does not appear in its place.
Here is the code so far:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main () {
//Builds 9x9 char array.
char dash[9][9];
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2]='_';
}
}
cout << "Input the row #, then the column #, then the number that you wish to fill that spot." << endl;
cout << "Remember that a Sudoku board is 9x9." << endl;
cout << "When you wish to finish input and solve, type all 0's and press enter." << endl;
int rowb;
char row[99];
int columnb;
char column[99];
int numb;
char num[99];
//Inputs the row/column and number to go into specified row/column.
int control=0;
while (rowb!=0){
control++;
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
}
int length;
length=strlen(row);
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control];
}
//Builds the Sudoko board and outputs the full 9x9 array.
cout << "╔═══════════╦═══════════╦═══════════╗" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=3; count<6; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=6; count<9; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╚═══════════╩═══════════╩═══════════╝" << endl;
return 0;
}
There is a problem assignment of the number entered in the loop.
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control]; //<<<--- Assignment issue.
}
You are assigning an integer value in a character array & thus when you display you will get the corresponding char for the ascii value & not the integer. Try changing the assignment as follows:
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control] + '0'; // Convert to ascii value of the integer, but will fail if not b/w 0 & 9.
}
Checking if the number entered in is between 1 & 9 is also advised if you choose to use the above observation.
Please add checks for the row & column entered as enter values which are not b/w 1 & 9 will lead to undefined behaviour due to accessing out of bound array elements if the values entered are not b/w 1 & 9.
Also as mentioned by Benjamin Lindley please update strlen code.
Hope this helps!
length=strlen(row);
This is undefined behavior, because row[0] was never initialized, and you never null terminate the string.
char row[99];
...
int control=0;
while (rowb!=0){
control++;
...
row[control]=rowb-1;
...
Notice that the first time through the loop, control is 1. So, you're setting the value of row[1], but not row[0]. Move the increment to the end of the loop. There may be some other problems, but this is the primary one responsible for the behavior you're seeing.
Also, for strlen to work, you need to null terminate the string.
And finally, you're making the same mistake you've made in this question and this question. Why aren't you seeming to get that? Chars display differently than ints. The following code will not display the number 1:
char c = 1;
std::cout << c;
Look at the answers to those other two questions.