Wrong value output [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to make the program give me the lowest and the highest value in the array.
Here's my code :
int z=10;
int a[z]={1,2,3,4,5,6,7,8,9,10};
for (int x=1;x<=10;x++) {
cout << "How many pancakes were eaten by P"<<x<<endl;
cin >> a[x];}
int maxPancakes = a[0];
int glutton;
int minPancakes = a[0];
int mN;
for (int x = 0; x <= z; x++) {
if (a[x] >= maxPancakes) {
maxPancakes = a[x];
glutton = x;
}
else if (a[x] <= minPancakes) {
minPancakes = a[x];
mN = x;
}
}
The code for the highest value is working, but the code for the lowest value keeps on giving me wrong values (random big numbers)
i'd appreciate any help,thank you.

First of all use standard library. It will make your life easier and code safer (and most of the time also faster).
For the array since C++11 you can use std::array, if you are working with the older C++ standard you can use std::vector.
Please note that in your code you are creating array with 10 elements but in the second loop you are iterating 11 times. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and... 10.
The value of the a[10] is undefined, it can be anything (random value).
In the first for loop you are setting the values for a[1] (second element), a[2] (third element), ... , a[10] (eleventh element, bad!).
Fix this loops and check what will happen. You can also start "debugging" with something easier than gdb (which is awesome btw. and you should learn it). You can simply print the values (read about std::cout) in every iteration to see when exactly this "random big numbers" are found.
EDIT
for (int x = 0; x < 10; x++)
{
cout << "How many pancakes were eaten by P" << x << endl;
cin >> a[x];
}
int maxPancakes = a[0];
int glutton;
int minPancakes = a[0];
int mN;
for (int x = 0; x < z; x++)
{
if (a[x] > maxPancakes)
{
maxPancakes = a[x];
glutton = x;
}
else if (a[x] < minPancakes)
{
minPancakes = a[x];
mN = x;
}
}

Related

I am unable to assign difference of two elements of 2 dimensional array to element of other array in C++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Below is the code, which is breaking my head since two days.
#include <iostream>
using namespace std;
int main()
{
int N;
int A[1][N-1];
int B[1][N-1];
std::cout << "ENTER NO OF ROUND" << '\n';
std::cin >> N;
for (int j=0; j<N; j++)
{
int i =0;
std::cout << "enter the scores" << '\n';
std::cin >> A[i][j]>>A[i+1][j];
if (A[i][j] > A[i+1][j])
{
B[i][j] = A[i][j] - A[i+1][j];
B[i+1][j] = 1;
}
if (A[i][j] < A[i+1][j])
{
B[i][j] = A[i+1][j] - A[i][j];
B[i+1][j] = 2;
}
}
std::cout << A[0][0]<<A[1][0] << '\n';
return 0;
}
Here in line 18 line 19 and line23 line24i should get difference of two elements of array A[1][N-1] Which is then assigned to a element in array B[1][N-1],but am unable get the correct result ,rather am getting a random number.
help me getting through this
You use uninitialized data, so anything can happen.
You declare the N variable:
int N;
And then, in the very next line, without assigning any value, you use it to create two arrays using N as a size:
int A[1][N-1];
int B[1][N-1];
This already is a starting point for disaster. Moreover, declaring an array with size [N - 1] is not technically correct - N is a variable, so cannot be used to declare array in this manner. It's a compiler extension (are you using Visual Studio?). If value of N is known, declare it as:
static constexpr size_t N = value;
If it is read at runtime, create your arrays with new or, much better, use std::vector to make your code robust and less error-prone.
The second thing is, that A array is declared as int A[1][N-1];, but you do the following:
int i = 0;
....
if (A[i][j] > A[i+1][j])
Which results in reading A[1][j], which does not exist - in C++ we start indexing from 0! You also modify those non-existing elements:
std::cin >> A[i][j] >> A[i+1][j];
which most likely will result in writing to memory that belongs to B array.
Small notes:
using namespace std seems redundant, as you write std:: everywhere
what is the point of two-dimensional array [M][N] if M = 1?
Use std::vectors if you need arrays with size determined at run-time. The C Variable-length arrays you use are not supported in C++.
std::cout << "ENTER NO OF ROUND" << '\n';
int N = 0;
std::cin >> N;
std::vector<std::vector<int>> A(2, std::vector<int>(N));
std::vector<std::vector<int>> B(2, std::vector<int>(N));
And note that you need 2 x N array because you read both A[i][j] and A[i+1][j] and your for loop is from [0 to N-1] -- N times.

Program runs in compiler but returns runtime error in online judge [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to solve this problem on this online judge: https://a2oj.com/ladder?ID=3 (see problem below) using the following code. It runs successfully on the compiler but returns a runtime error on the online judge.
EDIT: Code after changing loop conditions
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct count {
int number;
int repetitions;
};
bool sortByNumber(const struct count &lhs, const struct count &rhs) {
return lhs.number < rhs.number;
}
int main() {
vector <int> input;
int n = 0;
do {
cin>>n;
input.push_back(n);
} while (n != 0);
struct count x[101] = {NULL};
for (int j = 0; j < input.size(); j++) {
int tracker = 0;
for (int z = 0; z < input.size(); z++) {
if (input[j] != x[z].number) {
tracker++;
}
}
if (tracker == input.size()) {
x[j].number = input[j];
}
}
sort(x, x+101, sortByNumber);
for (int y = 0; y < 101; y++) {
for (int w = 0; w < input.size(); w++) {
if (x[y].number == input[w]) {
x[y].repetitions++;
}
}
}
for (int v = 0; v < 101; v++) {
if (x[v].number != 0) {
cout << x[v].number << " " << x[v].repetitions << endl;
}
}
return 0;
}
I'm fairly new to programming so I apologize if the answer is obvious and I can't see it. I've researched causes of runtime errors and I can't see any memory leaks, logic errors, or divisions by zero. The only thing I can think of is that it's a segmentation fault caused by the many nested loops (this code uses a lot more memory and running time than the other programs I submitted to the online judge), but I can't think of another way to solve this problem. Any ideas, even just about where to look, would be very much appreciated.
EDIT: Problem
Problem Statement:
Amgad got a job as a Cashier in a big store, where he gets thousands of dollars everyday. As a cashier, he must count the amount of each dollar bill (banknote) he has at the end of each day.
Amgad wants you to help him by writing a computer program so Amgad can just enter the amount of each bill and you count each bill separately.
Input Format:
one or more positive numbers ending by zero each number is between 1 and 100 inclusive
Output Format:
print each number only once in one line followed by the number of repetitions
Sample Input:
100
20
5
2
10
20
5
5
20
100
10
2
2
10
5
0
Sample Output:
2 3
5 4
10 3
20 3
100 2
As #Component10 mentioned, your array is of a fixed size. Add an integer called count that increments every time a new number is popped out of the input. Change all the integer literal references to 8 to counter.
If input contains more than 101 elements, the conditions
if (tracker == 8) {
x[j].number = input[j];
}
and
if (input[j] != x[z].number) {
tracker++;
}
Are invoking undefined behavior for any j value above 100, due to out-of-bounds access of array x elements. Both z, and j are looped to input.size(), which can be higher than 101.
Undefined behavior can manifest itself in many ways. Runtime error is one of those possibilities.

C++ malloc(): memory corruption [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am currently going through a fibonacci practice problem on hackerrank and am having a malloc memory corruption error. This is the link to the problem I am doing:
https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-returns/
Input is 0-10, each number separated by a new line.
For each input, the value at that point in the sequence is printed. It works for small inputs, but after 6 it gets the malloc error. It doesn't seem that the size of the sequence is an issue either, just how many are done in succession.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> bigFib(1);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x;
while(cin >> x){
if(bigFib.size()-1 >= x){
cout << bigFib[x] << endl;
}
else{
vector<int> fib(x);
fib[0] = 0;
fib[1] = 1;
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
bigFib = fib;
cout << fib[x] << endl;
}
}
return 0;
}
I am pretty new to C++ and can't find the problem. Thanks for your time.
When you create std::vector of size N, you can access elements with index [0, N-1] - which is N elements. You create vector of size x and in your loop:
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
and in this statement
cout << fib[x] << endl;
you try to access element with index equal to x, which is UB. If you do need to access index x create vector with at least x+1 size
In vector<int> fib(x); you declare a vector<int> that has x elements. Those elements are fib[0] through to fib[x - 1]. However, in for(int j = 2; j <= x; j++){ fib[j] = ... you assign to an element out of bounds.
Imagine if x is 1, then you'd expect your fib vector to contain only one element: fib[0]... yet your loop is assigning to fib[1]. Problem? Yup.
I reckon for(int j = 2; j <= x; j++){ should probably be for(int j = 2; j < x; j++){...
... and cout << fib[x] << endl; should be cout << fib[x - 1] << endl;

why is bubble sort not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Given some numbers and the amount of numbers, I have to sort them in ascending order, then output how many passes and swaps were done. Why is it not working? Also, I wanted to use a vector for this problem; am i passing the vector into the function and calling it properly?
//bubble Sort
#include<iostream>
#include<vector>
using std::cin;
using std::cout;
bool isSorted(std::vector<int> & myData);
int main()
{
std::vector<int> myData;
int length = 0;
int pass = 0;
int swap = 0;
cin >> length;
int x = 0;
for(x; x < length; x++)
{
int input = 0;
cin >> input;
myData.push_back(input);
}
x = 1;
while(!isSorted(myData))
{
int trash = 0;
for(x; x < length; x++)
{
if(myData[x] < myData[x-1])
{
trash = myData[x];
myData[x] = myData[x-1];
myData[x-1] = trash;
swap++;
}
}
pass++;
}
cout << pass << " " << swap;
return 0;
}
bool isSorted(std::vector<int> & myData)
{
for(int i = 1; i < myData.size(); i++)
{
if(myData[i] < myData[i-1])
{
return false;
}
}
return true;
}
You do not reset x between iterations of bubble sort. What happens is that before the first iteration of your outer loop x is equal to one. You then run the inner while loop until x becomes length, and go to the next iteration of the outer loop. By the next iteration x is never reset, so it still equals to length, so nothing happens on the second iteration, the inner loop immediately breaks without doing any work. You go to the third iteration of the outer loop, and nothing happens again. In particular, your array never becomes sorted, so the outer while loop never breaks, and the program never finishes (and never prints anything).
To fix it, just move x = 1 inside the loop, like this:
...
while(!isSorted(myData))
{
x = 1;
int trash = 0;
...

Exponents in C++ by using loops [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need some help. I want to compute ax given real value a and positive value integer x.
My program:
#include <iostream>
using namespace std;
int main()
{
int a, x;
cout << "Input a: ";
cin >> a;
cout << "Input x: ";
cin >> x;
for (int i=0; i<=x; i++)
a= a*a;
cout << "The answer is: " << a;
}
Take a look at this loop:
for (int i=0; i<=x; i++)
a= a*a;
cout << "The answer is: " << a;
}
Every time you go through this loop, you multiply a by itself. Let's suppose the user enters number a0. Then:
After 0 iterations, a has value a0.
After 1 iteration, a has value a02
After 2 iterations, a has value a04
After 3 iterations, a has value a08
...
For example, if a = 2 and x = 4, the values will be 2, 4, 16, and 256, which are way bigger than you want them to be.
To fix this, try changing your loop so that you have a secondary variable, initially set to 1, that you keep multiplying by a. That way, you don't change what value you're multiplying by on each iteration.
Next, note that your loop is running too many times. Since you loop up to and including x, your loop runs x + 1 times, so if you want to compute ax you will get the wrong value. Try changing this to loop exactly x times.
Finally, your print statement runs on each iteration, so you'll see all the intermediary values. Change the code so that the print statement is outside the loop.
After doing all that, do look up the pow function. If this is for an assignment you might not be able to use this function, but it's the easiest way to solve this problem.
Hope this helps!
There are a couple of errors:
for (int i=0; i<=x; i++)
this will loop for x+1 times, not what you intended.
a= a*a;
every time you do this, a is the value that is already multiplied, so you need another variable to store the result.
int result = 1;
for (int i=0; i<x; i++)
result *= a;
}
cout << "The answer is: " << result;
One last note, to calculate a^x, int may be too small for many practical cases, consider a bigger type like long long.
int result = 1;
for (int i=1; i<=x; i++)
{
result= result*a;
}
cout << "The answer is: " << result;
}
Hope This will work for you
A more "fun" method would be to use a template:
template<unsigned int E>
unsigned int power(unsigned int i)
{
return i * power<E - 1>(i); // template "loop"
}
template<>
unsigned int power<0>(unsigned int i) // break the "loop"
{
return 1;
}
To get the result:
unsigned int result = power<5>(3);
I thought it obvious, but just for clarification: This method requires that you know the exponent at compile-time.
Since std::pow exists, it is a bit silly to use a loop, but it can be done:
unsigned int base = SOME_BASE;
unsigned int exponent = SOME_EXPONENT;
unsigned int result = 1;
for (int i = 0; i < exponent; result *= base, ++i);