C++ Matrix values of - c++

I want to create a matrix of 5 lines and 5 columns which contains values from 1 to 9. The following programs displays numbers from 1 to 25 instead, when I input 5 to the program..
#include <iostream>
using namespace std;
int a[20][20], n, x = 0;
int main()
{
cout << "n=";
cin >> n;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
a[i][j] = x+1;
x = x+1;
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
I'm a c++ beginner, so maybe it's simple to do but i don't know how to make it show values from 1 to 9. This is the matrix I except:
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7

There are some issues in your code.
C arrays or STL containers?
First off, a your matrix may only hold matrices as big as 20x20. Your program will silently fail if you enter n bigger than 20, because you will access memory out of bounds; which causes an undefined behavior (see other common UB cases here).
You may want to use a dynamic size array - A good way to achieve this is to use std::vector. Unfortunately, this isn't as comfortable to use as a C-style array with two dimensions - you can achieve the same access syntax using a std::vector<std::vector<int>>, but this is not very efficient (see this answer if you are interested why) nor quite comfortable.
The Boost C++ library provides a multidimensional array library. Once you get experienced enough, you may find an use in it.
<= or <? 0-index or 1-indexed?
Many programming languages today uses 0-indexing for arrays. This means the first element of the array is located at index 0, not 1. Some languages, such as Lua, doesn't do this.
This means you should iterate i and j from 0 to n. This also means n is excluded, so you should use <, not <=.
Filling the matrix with numbers from 1 to 9
Your code doesn't do anything so you get numbers from 1 to 9 - it only fills the matrix with numbers from 1 to n * n. You could change this using an if clause to set x every time it goes above 9:
if (x > 9) { x = 0; } // x = 0 because it will be 1 on the next iteration
That being said, there is more convenient, as #PMar's answer says. The modulo operator % will do the task as well.
a[i][j] = (x % 9) + 1;
x = (x % 9) + 1;
This way, you will get every number from 1 to 9.
Now, you can also do another cleanup: Why are you calculating x's next value, and only then setting it? You could assign the new x value before the assignment to your matrix's cell. This allows having clearer code, with less copy pasting, which implies better maintainability.
x = (x % 9) + 1;
a[i][j] = x;
Another code quality consideration
I cannot say if your original code source was indented like your question (before it was edited), but you should really indent your code, for the future you and other people that will have to read your code. It allows for much better readability.
Same goes for different parts of your code : Add some space! It only can get more readable if you make a clear distinction between even just expressions.

You need to use the modulus operator (%). If you want the values in the matrix to be as you have computed them, but only need to change the display, you would output the matrix values as follows:
cout << (a[i][j] % 10) << " ";
If you want the one-digit values to be in the matrix itself, you would instead change the increment on 'x' to the following:
x = (x+1) % 10;}

#include <iostream>
int main()
{
int a[5][5];
int x = 1;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(x > 9)
x = 1;
a[i][j] = x;
x++;
}
}
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(a[i][j] < 10)
std::cout << " ";
std::cout << a[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
return 0;
}

Related

Why are variable length arrays in C++ overlapping on some sizes?

After providing an answer to a question here, I was testing this code that I edited and noticed some strange behavior:
#include <iostream>
#define MAX 100
using namespace std;
int main()
{
int size = 0;
int array[MAX];
int i, j;
int input;
cout << "Array: ";
for(i = 0; i < MAX; i++)
{
cin >> input;
if(input == -1)
break;
else
{
array[i] = input;
size++;
}
}
cout << "Size: " << size << "\n\n";
int left[size / 2];
int right[size / 2];
for(i = 0; i < size / 2; i++)
left[i] = array[i];
for(i = size / 2, j = 0; i < size; i++, j++)
right[j] = array[i];
cout << "Left: ";
for(i = 0; i < size / 2; i++)
cout << left[i] << ' ';
cout << '\n';
cout << "Right: ";
for(i = 0; i < size - size / 2; i++)
cout << right[i] << ' ';
cout << '\n';
return 0;
}
This code is supposed to split the array into two separate arrays. Somehow the output is wrong when these are the input:
1 2 3 4 5 6 7 8 9 -1
Left: 9 2 3 4
Right: 5 6 7 8 9
After debugging If the elements of left were printed like this:
for(i = size / 2, j = 0; i < size; i++, j++)
{
right[j] = array[i];
cout << left[0] << ' ';
}
cout << '\n';
It says that the value of left[0] is modified after the 5th iteration:
1 1 1 1 9
Left: 9 2 3 4
Right: 5 6 7 8 9
This only happens when the array size is 9. I haven't tested beyond 16 yet. I could fix the code so that it would have the correct size
int right[size - size / 2];
or use malloc() to adhere to the C++ Standard,
int *left = (int *) malloc(sizeof(*left) * n / 2);
int *right = (int *) malloc(sizeof(*left) * n / 2);
so that left wouldn't be affected, but that's not what I'm asking. Why does it only happen when splitting an array size of 9? Why was left[0] overwritten? Is this is a bug in g++ that should be reported or is the problem something else?
It says that the value of left[0] is modified after the 5th iteration:
That is your answer. The problem occurs in the fifth iteration over an array with four elements.
When size is odd, the calculation of size/2 rounds down. So the sum size/2 + size/2 is strictly less than size, yet your loops ensure that all size elements from the original array are assigned somewhere. Something has to be assigned to an unexpected location. We call this "undefined behavior", and whatever the compiler does at that point is correct according to the C++ standard. (Whatever happens, the compiler gets to blame your code for it.) It just happens that when size is 9, the compiler used left[0] as the location for right[4].
Behind the scenes, the left and right arrays are probably more-or-less adjacent in memory. The layout would have right[0] through right[size/2], then possibly some unused space (also known as "padding"), then left[0] through left[size/2]. When you access one-past the last element of right, you end up either in the unused space or in left[0]. When you overwrite the unused space, you see no symptoms since that space is otherwise unused. However, when you overwrite left[0] you definitely see a symptom.
Your compiler apparently uses padding to make sure the arrays are aligned to 4*sizeof(int). (Must be faster that way, as compilers rarely introduce waste without a reason. Still, I am surprised it's not 2*sizeof(int) instead.) That is, there is no padding when size/2 is a multiple of 4. If this guesswork is accurate, you should see this behavior when size is odd and size/2 is a multiple of 4; that is when size is one more than a multiple of 8, as in 9, 17, 25, 33, etc.

C++ Largest number in array. Positive and negative

I have a task to print maximum int of matrix second line.
Example input:
3 2 (n, m)
-1 -2 <- 1 line
4 5 <- 2 line
2 6 <- 3 line
Max int in second line is 5. My program prints it. But if second line would be -100 -150, it not works. Sure it is because I have max = 0, but I don't know how to use it properly. I'm a student. Thanks in advance.
It is my code:
#include <iostream>
using namespace std;
int main() {
int n, m, max = 0;
cin >> n >> m;
int matrix[10][10];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[1][j] > max) {
max = matrix[1][j];
}
}
}
if (max == 0 || n == 1) {
cout << "No";
} else {
cout << max;
}
}
And code works pretty good, unless there are negative numbers in second line
You are correct to suspect max = 0;. Why is that a problem? Well, first, perhaps you should try to explain to your rubber duck why it is correct. As you try to do so, you are likely to express an intent along the lines of "this value will not make it through the checks" or "this value will be replaced in the first iteration of the loop". Why? "Because matrix[1][j] > max will be true, so... Hold on, wasn't the problem when matrix[1][j] > 0 is false? So when max is 0, um... problem?"
The overall strategy is valid, but there is a requirement that max be initialized to a low enough value. There are two common strategies I can think of at the moment.
Use a value that is as low as possible for the type you are using. That is:
int max = std::numeric_limits<int>::lowest();
Use the value from the first iteration of the loop. No need to provide a value that is just going to be replaced anyway. There are some caveats for this, though. The most relevant for your example can be expressed as a question: what if there is no first iteration? (Perhaps there is only one row? Perhaps there are no columns?) Also, you would need to initialize max between your loops, after the matrix has been given values.
int max = (n > 1 && m > 0) ? matrix[1][0] : /* what value do you want here? */;

Error trying to find all the prime numbers from 2 to n using Sieve of Eratosthenes in C++

I need to find all the prime numbers from 2 to n using the Sieve of Eratosthenes. I looked on Wikipedia(Sieve of Eratosthenes) to find out what the Sieve of Eratosthenes was, and it gave me this pseudocode:
Input: an integer n > 1
Let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n:
if A[i] is true:
for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n :
A[j] := false
Output: all i such that A[i] is true.
So I used this and translated it to C++. It looks fine to me, but I have a couple errors. Firstly, if I input 2 or 3 into n, it says:
terminate called after throwing an instance of 'Range_error'
what(): Range_error: 2
Also, whenever I enter a 100 or anything else (4, 234, 149, 22, anything), it accepts the input for n, and doesn't do anything. Here is my C++ translation:
#include "std_lib_facilities.h"
int main()
{
/* this program will take in an input 'n' as the maximum value. Then it will calculate
all the prime numbers between 2 and n. It follows the Sieve of Eratosthenes with
the algorithms from Wikipedia's pseudocode translated by me into C++*/
int n;
cin >> n;
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
The issue is coming from the fact that the indexes are not in line with the value they are representing, i.e., they are moved down by 2. By doing this operation, they no longer have the same mathematical properties.
Basically, the value 3 is at position 1 and the value 4 is at position 2. When you are testing for division, you are using the positions as they were values. So instead of testing if 4%3==0, you are testing that 2%1=0.
In order to make your program works, you have to remove the -2 shifting of the indexes:
int main()
{
int n;
cin >> n;
vector<string>A;
for(int i = 0; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
for(int i = 2; i <= sqrt(n); ++i)
{
if(A[i] == "true")
{
for(int j = pow(i, 2); j <= n; j += i)
{
A[j] = "false";
}
}
}
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
return 0;
}
I agree with other comments, you could use a vector of bools. And directly initialize them with the right size and value:
std::vector<bool> A(n, false);
Here you push back n-1 elements
vector<string>A;
for(int i = 2; i <= n; ++i) // fills the whole table with "true" from 0 to n-2
A.push_back("true");
but here you access your vector from A[2] to A[n].
//print the prime numbers
for(int i = 2; i <= n; ++i)
{
if(A[i] == "true")
cout << i << '\n';
}
A has elements at positions A[0] to A[n-2]. You might correct this defect by initializing your vector differently. For example as
vector<string> A(n+1, "true");
This creates a vector A with n+1 strings with default values "true" which can be accessed through A[0] to A[n]. With this your code should run, even if it has more deficits. But I think you learn most if you just try to successfully implement the sieve and then look for (good) alternatives in the internet.
This is painful. Why are you using a string array to store boolean values, and not, let's say, an array of boolean values? Why are you leaving out the first two array elements, forcing you to do some adjustment of all indices? Which you then forget half the time, totally breaking your code? At least you should change this line:
i -= 2; // because I built the vector from 0 to n-2, i need to reflect that here.
to:
i -= 2; // because I left the first two elements out, I that here.
// But only here, doing it everywhere is too annoying.
As a result of that design decision, when you execute this line:
for(int j = pow(i, 2); j <= n; j += i)
i is actually zero which means j will stay zero forever.

c++:Hackerank:Error in taking input

This is a part of my question.I tried many times but couldn't get the answer
Problem Statement
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.
Note Suppose a, b, and c are three different people, then (a,b) and (b,c) are counted as two different teams.
Input Format
The first line contains two integers, N and M, separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow.
Each line contains a binary string of length M. If the ith line's jth character is 1, then the ith person knows the jth topic; otherwise, he doesn't know the topic.
Constraints
2≤N≤500
1≤M≤500
Output Format
On the first line, print the maximum number of topics a 2-person team can know.
On the second line, print the number of 2-person teams that can know the maximum number of topics.
Sample Input
4 5
10101
11100
11010
00101
Sample Output
5
2
Explanation
(1, 3) and (3, 4) know all the 5 topics. So the maximal topics a 2-person team knows is 5, and only 2 teams can achieve this.
this is a a part of my work.Any clue how can i get this to work
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, m, max = 0, max1 = 0, count = 0;
cin >> n >> m; //for input of N and M
int a[n][m];
for (int i = 0; i<n; i++) //for input of N integers of digit size M
for (int j = 0; j<m; j + >>
cin >> a[i][j];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
max = 0;
for (int k = 0; k<m; k++)
{
if (a[i][k] == 1 || a[j][k] == 1) max++;
cout << k;
if (k = m - 1 && max>max1) max1 = max;
if (k == m - 1 && max == max1) count++;;
}
}
}
cout << max1 << endl << count;
return 0;
}
I think the way of taking my input logic is wrong.could you please help me out.I am stuck in this question from 5 days.
PLease only help me on how should i take input and how to read the digit of integer.
Don't have a compiler with me so there's probably a syntax boner or two in there, but the logic walks through on paper.
Builds the storage:
std::cin >> n >> m; //for input of N and M
std::vector<std::vector<bool>>list(n,std::vector<bool>(m, false));
Loads the storage:
char temp;
for (int i = 0; i < n; i++) //for input of N integers of digit size M
{
for (int j = 0; j < m; j++)
{
std::cin >> temp;
if (temp == 1)
{
list[i][j] = true;
}
}
}
Runs the algorithm
for (int a = 0; a < n; a++)
{
for (int b = a+1; b < n; b++)
{
int knowcount = 0;
for (int j = 0; j < m; j++)
{
if (list[a][j] | list[b][j])
{
knowcount ++;
}
}
if (knowcount > max)
{
groupcount = 1;
max = know;
}
else if(knowcount == max)
{
groupcount ++;
}
}
}
Your method of input is wrong. According to your method, the input will have to be given like this (with spaces between individual numbers):
1 0 1 0 1
1 1 1 0 0
1 1 0 1 0
0 0 1 0 1
Only then it makes sense to create a matrix. But since the format in the question does not contain any space between a number in the same row, thus this method will fail. Taking into consideration the test case, you might be tempted to store the 'N' numbers in a single dimensional integer array, but keep in mind the constraints ('M' can be as big as 500 and int or even unsigned long long int data type cannot store such a big number).

I tried coding my own simple moving average in C++

I want a function that works.
I believe my logic is correct, thus my (vector out of range error) must be coming from the lack of familiarity and using the code correctly.
I do know that there is long code out there for this fairly simple algorithm.
Please help if you can.
Basically, I take the length as the "moving" window as it loops through j to the end of the size of the vector. This vector is filled with stock prices.
If the length equaled 2 for a 2 day moving average for numbers 1 2 3 4. I should be able to output 1.5, 2.5, and 3.5. However, I get an out of range error.
The logic is shown in the code. If an expert could help me with this simple moving average function that I am trying to create that would be great! Thanks.
void Analysis::SMA()
{
double length;
cout << "Enter number days for your Simple Moving Average:" << endl;
cin >> length;
double sum = 0;
double a;
while (length >= 2){
vector<double>::iterator it;
for (int j = 0; j < close.size(); j++){
sum = vector1[length + j - 1] + vector1[length + j - 2];
a = sum / length;
vector2.push_back(a);
vector<double>::iterator g;
for (g = vector2.begin(); g != vector2.end(); ++g){
cout << "Your SMA: " << *g;
}
}
}
}
You don't need 3 loops to calculate a moving average over an array of data, you only need 1. You iterate over the array and keep track of the sum of the last n items, and then just adjust it for each new value, adding one value and removing one each time.
For example suppose you have a data set:
4 8 1 6 9
and you want to calculate a moving average with a window size of 3, then you keep a running total like this:
iteration add subtract running-total output average
0 4 - 4 - (not enough values yet)
1 8 - 12 -
2 1 - 13 13 / 3
3 6 4 15 15 / 3
4 9 8 16 16 / 3
Notice that we add each time, we start subtracting at iteration 3 (for a window size of 3) and start outputting the average at iteration 2 (window size minus 1).
So the code will be something like this:
double runningTotal = 0.0;
int windowSize = 3;
for(int i = 0; i < length; i++)
{
runningTotal += array[i]; // add
if(i >= windowSize)
runningTotal -= array[i - windowSize]; // subtract
if(i >= (windowSize - 1)) // output moving average
cout << "Your SMA: " << runningTotal / (double)windowSize;
}
You can adapt this to use your vector data structure.
Within your outermost while loop you never change length so your function will run forever.
Then, notice that if length is two and closes.size() is four, length + j - 1 will be 5, so my psychic debugging skills tell me your vector1 is too short and you index off the end.
This question has been answered but I thought I'd post complete code for people in the future seeking information.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<double> vector1 { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
double length;
cout << "Enter number days for your Simple Moving Average:" << endl;
cin >> length;
double sum = 0;
int cnt = 0;
for (int i = 0; i < vector1.size(); i++) {
sum += vector1[i];
cnt++;
if (cnt >= length) {
cout << "Your SMA: " << (sum / (double) length) << endl;
sum -= vector1[cnt - length];
}
}
return 0;
}
This is slightly different than the answer. A 'cnt' variable in introduced to avoid an additional if statement.