Checking how many times a number has been entered - c++

I'm trying to solve one of the questions on a task sheet I've received, to help me further in my understanding of C++ code from my class.
It kept showing 100000 in output after I entered the values. Where is that 1 coming from?
I know there are better ways to write code for this but I just want to know were is my problem.
The question is
(and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen.
Creates a second array of size 5 and fills it with zeros.
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
Code:
int A1[10];
int A2[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
here:
cout << endl << i + 1 << "- enter a number between 1 and 5 for value : ";
cin >> A1[i];
if (A1[i] < 1 || A1[i]>5)
{
cout << "eror! enter a number between 1 and 5!";
goto here;
}
}
for (int i = 0; i < 10; i++)
{
for (int j = 1; j < 6; j++)
{
if (A1[i] = j)
{
A2[j - 1]++;
break;
}
}
}
for (int i = 0; i < 5; i++)
cout << A2[i];

The error is on the row 21 or 22, you are using a single = which is the assignment sign, inside the if statement, so you are overwriting the value of A[i] to the value of j, but want to check if the element of A[i] is equal to j... So you have to add a = in the if statement.

I don't recommend that you use goto:, it creates spaghetti code. you can put an i-- in your error clause, like so:
int temp;
for (int i = 0; i < count; i++){
cout << i + 1 << "- enter a number between 1 and 5 for value : " << endl;
cin >> temp;
if (temp >= 1 && temp <=5)
A1[i] = temp;
else
i--;
}
Also, if you want to compare 2 values, you should use the == operator. that is what's causing the problem in your second loop
like so:
for(int i = 0; i < count; i++){
for(int j = 1; j < 6; j++)
if(A1[i] == j)
A2[j-1]++;
}
This should work.

Related

program that reads an integer, and prints all the perfect numbers

int n;
int sum;
cout << "write a number";
cin >> n;
for (int i = 1; i < n; i++)
{
sum = 0;
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
sum = sum + j;
}
if (sum == i)
cout << i<< endl;
}
Why do I always get 1 as a result? I couldn't understand the logic of it. When I change the second for loop and make it i/2, I get the correct result, but I couldn't understand how it worked.
input 1000
expected result = 6 28 496
Remind about mathematics. Refer to wiki
In number theory, a perfect number is a positive integer that is equal
to the sum of its positive divisors, excluding the number itself.
So, in your code, you are making sum of ALL divisors of i include itself. That's why you only get result 1.
You should change it simply.
for (int j = 1; j < i; j++)

Can't find path in Minimum Cost Path using Dynamic Programming

The algorithm is supposed to find the minimum cost path in NxN matrix given as an input. The starting cell is always left bottom and the destination is right top.
Each cell of the matrix represents a cost to traverse through that cell.
You can only move up and right.
I have managed to find the cost, however, I still struggle to backtrack the path.
I tried to start from top right cell and use the greedy algorithm to find my "way back", but the output was either completely wrong or skipping random columns/rows. I also tried to keep track of decisions I was making by creating an additional matrix, but I always end up stuck in the loop.
So how do I find the path?
Here's the code that works well (counts the cost and that's it):
#include <iostream>
using namespace std;
int main()
{
int tab[101][101], N, cost[101][101], backtrack[101][101];
cout << "N (size of NxN matrix) :" << endl;
cin >> N;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
cin >> tab[i][j];
cost[i][j] = 0;
backtrack[i][j] = 0;
}
}
cost[N-1][0] = tab[N-1][0];
int a = N-1;
for(int i = N-2; i >= 0; i--) // column 0 can be chosen only in 1 way
{
cost[i][0] = cost[i+1][0] + tab[i][0];
backtrack[i][0] = 4; // came from down
}
for(int j = 1; j < N; j++) // row N-1 can be chosen only in 1 way
{
cost[a][j] = cost[a][j-1] + tab[a][j];
backtrack[a][j] = 3; // came from right
}
for(int i = N-2; i >= 0; i--)
{
for(int j = 1; j < N; j++)
{
if(cost[i][j-1] <= cost[i+1][j])
{
cost[i][j] = tab[i][j] + cost[i][j-1];
backtrack[i][j] = 3;
}
else
{
cost[i][j] = tab[i][j]+cost[i+1][j];
backtrack[i][j] = 4;
}
}
}
cout << "Cost: " << cost[0][a] << endl;
return 0;
}
Now, here's the function with flawed additional matrix that's supposed to give me the path, but ends up in an infinite loop:
(matrix backtrack from previous code was given as track here)
void path(int track[101][101], int N)
{
int help[101][101];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
help[i][j] = 0;
}
int w = 0, k = N-1;
help[w][k] = 1; // top right argument is included in the output
while(w < N || k >= 0)
{
if(track[w][k] == 3)
{
help[w][k-1] = 1; // 3 means I came from the previous column k-1
k--;
}
else if(track[w][k] == 4)
{
help[w+1][k] = 1; //4 means I came from the previous row w+1
w++;
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(help[i][j] != 0)
cout << i << " " << j << endl;
}
}
}
Example input:
5
2 3 4 2 5
5 2 1 2 2
2 4 2 2 3
1 2 2 4 3
3 2 1 2 3
Expected output:
Cost: 20
4 0
4 1
4 2
3 2
2 2
1 2
1 3
0 3
0 4
Actual output
Cost: 20
And no path at all since it ends up in an infinite loop.
You have written the while loop in path() incorrectly:
while(w < N || k >= 0)
...
You intend this loop to continue until w = N-1 and k=0, which it does, but the loop doesn't terminate there, it just runs in place. (You could see this yourself by adding cout << w << " " << k << endl; to the loop.) The conditional I think you want is:
while(w < N-1 || k > 0)

C++ For loops and multidimensional arrays

So I have an assignment for my C++ class. Basically we have to create a 3x3 multidimensional array, calculate the sum of rows, sum of columns, sum of diagonal values and sum of anti-diagonal values, I usually just input 1 2 3 4 5 6 7 8 9 as values as a starting point.
Now, I'm not trying to be rude but my teacher is not very good, we basically spend 2 hours on a single problem without her doing much explaining. Other than that I started with C++ Primer and Programming: Principles and Practice Using C++ so I believe I'll be able to learn a lot on my own.
Anyhow my questions are probably quite stupid, but if anyone feels like helping, here they are:
My /**/ commented for loop for anti-diagonal value gives me a wrong sum. I'm assuming it has something to do with the nature of for-loops or I just type it out wrong, but I didn't figure it out yet.
2.The teacher's solution for calculating the anti-diagonal values is the following:
for (i = 0; i < row_num; ++i)
for (j = 0; j < col_num; ++j)
if (i + j == row_num - 1)
anti-diagonal += A[i][j];
How is it different from my approach? I believe mine is simpler and works better.
3.In line:
int sumRows[row_num] = { 0 };
Why do {} have to be used? Our teacher didn't bother with explaining that. I tried without {} but I got an error.
Here is the full code for my version:
#include "../../std_lib_facilities.h"
#include <iostream>
using namespace std;
#define row_num 3 //no. of rows
#define col_num 3 //no. of columns
int main()
{
int i = 0;
int j = 0;
int diagonal = 0;
int antidiagonal = 0;
int sumRows[row_num] = { 0 };
int sumCol[col_num] = { 0 };
int A[row_num][col_num];
//Input to matrix
for(i=0; i<row_num; i++)
for (j = 0; j < col_num; j++)
{
cout << "A[" << i << "]" << "[" << j << "]: ";
cin >> A[i][j];
sumRows[i] += A[i][j];
sumCol[j] += A[i][j];
}
cout << endl;
//Print out the matrix
for (i = 0; i < row_num; i++)
{
for (j = 0; j < col_num; j++)
cout << A[i][j] << '\t';
cout << endl;
}
//prints sum of rows
for (i = 0; i < row_num; i++)
cout << "Sum of row " << i + 1 << " "<< sumRows[i] << endl;
//prints sum of columns
for (j = 0; j < row_num; j++)
cout << "Sum of column " << j + 1 << " " << sumCol[j] << endl;
//Sum of diagonal values
for (i = 0; i < row_num; i++)
diagonal += A[i][i];
//Sum of antidiagonal values
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
antidiagonal += A[i][j];
/*for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
*/
cout << "\nSum of diagonal values: " << diagonal << endl;
cout << "Sum of antdiagonal values: " << antidiagonal << endl;
return 0;
}
1) Your commented out loop sums all values, not just those along the antidiagonal.
2) It is different from your approach in that it will iterate over every value in the matrix, but then it will only add to the total if it detects it is in one of the appropriate cells. Your solution only iterates over the appropriate cells and doesn't have to evaluate any ifs, so it will be more efficient. However, you need to change your loop condition to i < row_num && j >= 0. Using a comma here will discard the result of one of the checks.
3) int sumRows[row_num] = { 0 }; initializes the whole sumRows array with 0's.
1) This
for(i=0; i<row_num; i++)
for (j = 2; j >= 0; j--)
{
antidiagonal += A[i][j];
}
is wrong, because for i=0 you iterate through all j values, ie
i=0 , j=2,1,0 then i=1
2) Your teachers loop is easier to read and correct. Yours has a wrong break condition:
for (i = 0, j = 2; i < row_num, j >= 0; i++, j--)
^------------------------ WRONG
Read about the comma operator to understand what is actually going on here. You just didnt realize the problem, because the two conditions are by chance equivalent.
3) You dont have to use it, it is just a new and fancy way to initialize the array.

2D Array and File Handling [C++]

Background:
I'm attempting to read through a 2d array and find values that coincide with row numbers and column numbers.
Question:
How do I read values off a file and acquire, for example, 1 and 4 vs. 14?
Here's what I have so far...
All constructive criticism is welcome.
int arrayOfNum[5][5] = {
{34,21,32,41,25},
{14,42,43,14,31},
{54,45,52,42,23},
{33,15,51,31,35},
{21,52,33,13,23}};
ofstream arrayFile;
arrayFile.open("arrays.txt");
if (arrayFile.is_open()) {
cout << "File opened successfully..." << endl;
}
for (int i = 0; i <= 4; i++) {
arrayFile << endl;
for (int j = 0; j <= 4; j++) {
arrayFile << arrayOfNum[j][i] << ' ';
}
}
You are writing rows in columns as you wrote "arrayOfNum[j][i]", but I'm writing the code for correct direction. You can change the condition in following code but it's working perfect if you write "arrayOfNum[i][j]" while outputting in 'array.txt'
ifstream arrayFile;
arrayFile.open("arrays.txt");
for (int i = 0; i <= 4; i++)
{
for (int j = 0; j <= 4; j++)
{
arrayFile >> arrayOfNum[i][j];
cout<<arrayOfNum[i][j]<<" ";
if(i+1 == arrayOfNum[i][j] / 10 && j+1 == arrayOfNum[i][j] % 10)
{
cout<<"\n Matched: "<<arrayOfNum[i][j]<<endl;
}
}
cout<<endl;
}
And yes it will work for only 2 digit numbers, if you want for N digit numbers then I can do it for you too! :)

Why is my loop executed too often?

I am designing a program for a C++ class that I am taking and the professor wants us to make a program that outputs a diamond shape using "*". The thing I am stuck on is that my program is outputting too many lines.
Instead of
*
***
*
It is outputting
*
***
*****
***
*
How would I modify my code to get this to work? I have been searching online for an answer all morning with no luck.
Here is my code:
#include <iostream>
using namespace std;
int main () {
//Define Varaible
int N;
cout << "Please enter a postitive integer: ";
cin >> N;
cout << "Here is your diamond." << endl << endl;
for (int i = 0; i <= 2 * N; i++) {
for (int j = 0; j <= 2 * N; j++) {
if (i <= N) {
if (j < N - i || j > N + i) {
cout << ' ';
}
else {
cout << '*';
}
}
else {
if (j < i - N || j > 3 * N - i) {
cout << ' ';
}
else {
cout << '*';
}
}
}
cout << endl;
}
return 0;
}
The reason you get more rows than you expect is that you are creating 2 * N + 1 number of rows, when you actually want 2 * N - 1.
The fix is simple: Decrement N by one after you read the input.
cin >> N;
assert(N > 0);
--N;
This way, the rest of your code won't have to change.
You should remember that in range [0,5] (both inclusive) there are 6 elements, not 5. So when you do loops and you want to do 5 iterations you usually do either:
for( int i = 0; i < 5; ++i ) // do stuff
or
for( int i = 1; i <= 5; ++i ) // do stuff
When programming in C or C++ first version is used more often as it fits array indexes and programmers have habit to use that form.
But as I said before if you do:
for( int i = 0; i <= 5; ++i ) // do stuff
That would be 6 iterations.