Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to get the greatest value from the array and its index number also by using a function maxin but my logic somehow isn't working?
#include <iostream>
#include <conio.h>
#include <proceass.h>
void maxin(double[], int);
void main()
{
const int k = 10;
int l = 0;
double num[k];
for (int j = 0; j < k; j++)
{
cout << "Enter the number " << j + 1 << " = ";
cin >> num[j];
if (cin.fail())
{
cout << "Wrong data entered " << "\nTry again";
getch();
exit(0);
}
}
maxin(num, l);
cout << "The Greatest number is = " << num;
cout << "\nIt is " << l << "th number";
getch();
}
void maxin(double k[], int p)
{
int l, s;
l = 10;
s = 0;
double m;
for (int n = 0; n < l; n++)
{
if (k[s] > k[n++])
{
m = k[n];
}
else
{
m = k[n++];
s = ++;
}
}
p = s;
k[s] = m;
}
Your maxin function is invoking Undefined Behavior on your program for causing access to areas beyond the bounds of the array k. This happens because not only is n incremented in the for loop statement, but again in the if statement which is evaluated on each iteration as well. This also happens in the else statement, which is another case of the problem.
When n is 1 less than l, n++ will be >= l, and subsequently dereferencing that address, k[n++], will cause Undefined Behavior. After that, anything can happen to your program, including valid or invalid side effects.
When finding the maximum/minimum value in an array, a variable is usually set to an arbitrary value in the array (typically the first index), and then iteration is performed to check if any other value in the array is smaller/larger than that variable. When that condition passes, the variable is set to the new value in the array.
Furthermore, since you said you needed to set the variable to the index at which the largest value was found, it is necessary that you pass p by reference.
The STL approach:
vector< double > v = {1,2,3,4,5};
auto maxElemIter = std::max_element(begin(v), end(v));
cout << "Max is: " << *maxElemIter;
cout << ", at index: " << distance(begin(v), maxElemIter) << endl;
(I know, this is a cruel suggestion, given code as stated in question above...)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed last year.
Improve this question
Im trying to create a a code that count numbers divisible by 9 by putting numbers into an array and count the numbers in it but it only prints 1 instead of the number of numbers divisible by 9 please help me i want to use array to count those numbers
#include <iostream>
using namespace std;
int main(){
int a,b,i;
int numbers[]={i};
cin >>a>>b;
for (i=a; i<=b; i++)
if (i%9==0){
cout << sizeof(numbers)/sizeof(numbers[0]);
}
}
Nowhere in your code are you adding numbers to the array. Anyhow, it is not possible to add elements to arrays, because they are of fixed size. Your array has a single element.
Moreover, int numbers[]={i}; is undefined, because i has not been initialized.
Further, it is not clear what is the purpose of sizeof(numbers)/sizeof(numbers[0]) in your code. sizeof(numbers) is the size of a single int because the array has a single element. sizeof(numbers[0]) is the size of a single int as well. Hence the result is 1 always. (Its a compile time constant btw.)
If you want to count how many numbers fullfil some condition you best use a counter and print its value after the loop:
#include <iostream>
int main(){
int a,b;
cin >> a >> b;
unsigned counter = 0;
for (int i=a; i<=b; i++) {
if (i%9==0){
++counter;
}
}
std::cout << counter;
}
i want to use array for my learning porpuses please help me
You chose the wrong example to train working with arrays, because as already mentioned, arrays have fixed size. It is an opportunity to learn about std::vector. You can add elements to a std::vector at runtime and query its size:
#include <iostream>
#include <vector>
int main(){
int a,b;
std::vector<int> by9divisables;
std::cin >> a >> b;
for (int i=a; i<=b; i++) {
if (i%9==0) {
by9divisables.push_back(i);
}
}
std::cout << by9divisables.size();
}
However, other than to see how std::vector is working, the vector has no place in this code. As you can see above, the result can be obtained without it.
This declaration
int numbers[]={i};
declares an array with only one element and initializes it with an indeterminate value stored in the variable i because the variable i was not initialized.
The body of this if statement
if (i%9==0){
cout << sizeof(numbers)/sizeof(numbers[0]);
}
does not make a sense because it always outputs the number of elements in the array numbers that has only one element. But according to the description of the assignment you have to place numbers divisible by 9 into the array.
As the user can enter arbitrary values for the variables a and b then it means that you need a variable length array. However variable length arrays is not a standard C++ feature. Instead you should use the standard container std::vector.
The program can look the following way
#include <iostream>
#include <vector>
#include <utility>
int main()
{
int a = 0, b = 0;
std::vector<int> numbers;
const int divisor = 9;
std::cout << "Enter two integer numbers: ";
std::cin >> a >> b;
if ( b < a ) std::swap( a, b );
for ( int i = a; not ( b < i ); ++i )
{
if ( i % divisor == 0 ) numbers.push_back( i );
}
std::cout << "There are " << numbers.size()
<< " numbers divisible by " << divisor
<< " in the range [" << a << ", " << b << "]\n";
if ( numbers.size() != 0 )
{
std::cout << "They are ";
for ( const auto &n : numbers )
{
std::cout << n << ' ';
}
std::cout << '\n';
}
}
Your code is printing one's for each element found because your array only has one element in it!
Print i instead like so:
#include <iostream>
using namespace std;
int main(){
int a,b,i;
//int numbers[]={i};
cin >>a>>b;
for (i=a; i<=b; i++)
{
if (i%9==0)
{
cout << "i: " << i << endl;
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Tried several times yet still didnt manage to find my mistake: here is my program. i need to find the odd numbers from 1 and integer x and find the sum of them cubed.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int x;
int i = 1;
int result;
cout <<" Enter the value for n" << endl;
cin >> x;
while (i >x)
if (i%2 == 0) {}
else {
result += pow(i,3);
i++;
}
cout << "The sum of odd integers cubes from " << i << " to " << x << "= " << result << endl;
return 0;
}
Minimally, you should change the compare in while
from
while (i > n)
to
while (i <= n)
There a many numbers where i will be greater than the number entered, n.
You didn't add in your curly brackets for the while loop.
while (i > x)
if (i%2 == 0) {}
needs to be:
while (i > x){
if (i % 2 == 0) {}
}
Plus what are you doing inside of that if statement? You should decrement x, to find if each number is odd.
Plus, your program ends early because i is 1 and if the user enters a number above 1, your while loop won't even run. You're telling the while loop to run ONLY when i is larger than x. Try changing it to less than:
from:
while (i > x){
to:
while (i < x){
Plus you're not doing anything with x. You want to decrement x, not add i. Although, I would recommend using a do-while loop. ( a dowhile loop does one iteration first before incrementation)
do{
if (x % 2 == 0) { // if the remainder of x/2 is 0, do this
x--;
cout << "Equal: " << x << endl;
}
if(x % 2 != 0) { //if the remainder of x/2 is not 0, do this.
temp = pow(x,3);
//you don't want to take the power of the added sum,
//you were taking the power 3 of x which was being added to.
//you want to add the sums of each power. So here we have temp, a
//temporary variable to store your addends.
result = result + temp;
cout << "Not equal, temp:" << temp <<endl;
cout << "Result: "<< result << endl;
x--; //you didn't have a decrement, you need to bring x eventually down to i if you want the loop to end, or even look through all of the numbers
}
}
while (i < x);
//You have to have this semi colon here for the compiler to know its a do-while.
cout << "The sum of odd integers cubes from " << i << " to " << userVar
<< " = " << result << endl;
return 0;
}
note: if-else statements are for flow control, its like true and false, one or the other, so that your data will flow somewhere. I used two if statements because I want to have complete control over the flow.
note2: It's ok to use:
using namespace std;
at first, but eventually you want to start learning what library each command is using. When you get into more complex programming, you start using commands from different libraries than the standard one.
So I've been working on problem 15 from the Project Euler's website , and my solution was working great up until I decided to remove the cout statements I was using for debugging while writing the code. My solution works by generating Pascal's Triangle in a 1D array and finding the element that corresponds to the number of paths in the NxN lattice specified by the user. Here is my program:
#include <iostream>
using namespace std;
//Returns sum of first n natural numbers
int sumOfNaturals(const int n)
{
int sum = 0;
for (int i = 0; i <= n; i++)
{
sum += i;
}
return sum;
}
void latticePascal(const int x, const int y, int &size)
{
int numRows = 0;
int sum = sumOfNaturals(x + y + 1);
numRows = x + y + 1;
//Create array of size (sum of first x + y + 1 natural numbers) to hold all elements in P's T
unsigned long long *pascalsTriangle = new unsigned long long[sum];
size = sum;
//Initialize all elements to 0
for (int i = 0; i < sum; i++)
{
pascalsTriangle[i] = 0;
}
//Initialize top of P's T to 1
pascalsTriangle[0] = 1;
cout << "row 1:\n" << "pascalsTriangle[0] = " << 1 << "\n\n"; // <--------------------------------------------------------------------------------
//Iterate once for each row of P's T that is going to be generated
for (int i = 1; i <= numRows; i++)
{
int counter = 0;
//Initialize end of current row of P's T to 1
pascalsTriangle[sumOfNaturals(i + 1) - 1] = 1;
cout << "row " << i + 1 << endl; // <--------------------------------------------------------------------------------------------------------
//Iterate once for each element of current row of P's T
for (int j = sumOfNaturals(i); j < sumOfNaturals(i + 1); j++)
{
//Current element of P's T is not one of the row's ending 1s
if (j != sumOfNaturals(i) && j != (sumOfNaturals(i + 1)) - 1)
{
pascalsTriangle[j] = pascalsTriangle[sumOfNaturals(i - 1) + counter] + pascalsTriangle[sumOfNaturals(i - 1) + counter + 1];
cout << "pascalsTriangle[" << j << "] = " << pascalsTriangle[j] << '\n'; // <--------------------------------------------------------
counter++;
}
//Current element of P's T is one of the row's ending 1s
else
{
pascalsTriangle[j] = 1;
cout << "pascalsTriangle[" << j << "] = " << pascalsTriangle[j] << '\n'; // <---------------------------------------------------------
}
}
cout << endl;
}
cout << "Number of SE paths in a " << x << "x" << y << " lattice: " << pascalsTriangle[sumOfNaturals(x + y) + (((sumOfNaturals(x + y + 1) - 1) - sumOfNaturals(x + y)) / 2)] << endl;
delete[] pascalsTriangle;
return;
}
int main()
{
int size = 0, dim1 = 0, dim2 = 0;
cout << "Enter dimension 1 for lattice grid: ";
cin >> dim1;
cout << "Enter dimension 2 for lattice grid: ";
cin >> dim2;
latticePascal(dim1, dim2, size);
return 0;
}
The cout statements that seem to be saving my program are marked with commented arrows. It seems to work as long as any of these lines are included. If all of these statements are removed, then the program will print: "Number of SE paths in a " and then hang for a couple of seconds before terminating without printing the answer. I want this program to be as clean as possible and to simply output the answer without having to print the entire contents of the triangle, so it is not working as intended in its current state.
There's a good chance that either the expression to calculate the array index or the one to calculate the array size for allocation causes undefined behaviour, for example, a stack overflow.
Because the visibility of this undefined behaviour to you is not defined the program can work as you intended or it can do something else - which could explain why it works with one compiler but not another.
You could use a vector with vector::resize() and vector::at() instead of an array with new and [] to get some improved information in the case that the program aborts before writing or flushing all of its output due to an invalid memory access.
If the problem is due to an invalid index being used then vector::at() will raise an exception which you won't catch and many debuggers will stop when they find this pair of factors together and they'll help you to inspect the point in the program where the problem occurred and key facts like which index you were trying to access and the contents of the variables.
They'll typically show you more "stack frames" than you expect but some are internal details of how the system manages uncaught exceptions and you should expect that the debugger helps you to find the stack frame relevant to your problem evolving so you can inspect the context of that one.
Your program works well with g++ on Linux:
$ g++ -o main pascal.cpp
$ ./main
Enter dimension 1 for lattice grid: 3
Enter dimension 2 for lattice grid: 4
Number of SE paths in a 3x4 lattice: 35
There's got to be something else since your cout statements have no side effects.
Here's an idea on how to debug this: open 2 visual studio instances, one will have the version without the cout statements, and the other one will have the version with them. Simply do a step by step debug to find the first difference between them. My guess is that you will realize that the cout statements have nothing to do with the error.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
char arr[10]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
gets(arr);
for (int i=0;i<1;i++)
{
for (int j=0;j<10;j++)
{
if(j<=4)
{
arr1[0][j]=arr[j] ;
}
else if (j>4)
{
arr1[1][j-5]=arr[j] ;
}
}
}
for(int j=0;j<5;j++)
{
cout<<arr1[0][j]<<" ";
}
cout<<endl;
for(int j=0;j<5;j++)
{
cout<<arr1[1][j]<<" ";
}
Here what i am trying to do is converting a 1d array in to 2d array.
my main purpose is to store 1d array on a 2d and when the first row is completed it should shift the string to next row it is doing all the as i have declared the arr[10] and inputting 10 charcter string through get(arr) it is storing the array as i want but at the end displays an error window i dont know why the program is running perfect as well as giving this error window
my input : hanzlaamja (10charcters)
my output:
h a n z l
a a m j a
according to my wish but the main problem is the error window.
note : there is nothing in error box or warning box.
My program is working perfectly, but i am getting an error of array corruption.
Can anybody help me out? I would be very thankful
please see this error message
full picture
The problem is that you read in 10 characters (e.g. "hanzlaamja") and the string termination character '\0', which is automatically added by gets. Thereby you exceed array bounds, as this would require space for 11 characters. So it would already work if you wrote char arr[11];. But as mentioned in the comments, do not use gets; it is unsafe and it does not prevent you from exceeding array bounds. The following snippet shows how to do this part better:
...
char arr[11]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
// gets(arr);
if (!fgets(arr,11,stdin)) {
cout << "no value read." << endl;
return 1;
}
...
A lot of your loops could be written shorter / better readable. But that's not the actual topic.
Adding to the great point pointed out by #Stephan Lechner, I have composed a solution "as close as possible" to your original.
Compiled under visual studio 2017.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "main - start" << endl;
const size_t numOfRows = 2;
const size_t numOfCol = 5;
const size_t numCharsInSingleDimArray = 10;
char arr[numCharsInSingleDimArray] = { '\0' }, arr1[numOfRows][numOfCol] = { '\0' };
cout << "enter the full line : ";
gets_s(arr); // Note:If the buffer (arr) is too small to contain the input line and null terminator, these functions invoke an invalid parameter handle.
cout << "main - entered:" << arr << endl;
char* twoDimArrStartLoc = &(arr1[0][0]); // as user4581301 pointed out, it is also possible to "approach" it by treating the two dimensional array as a contiguous bytes in memory
for (size_t i = 0, j = 0; i< numCharsInSingleDimArray; ++i, ++j)
{
twoDimArrStartLoc[j] = arr[i];
}
cout << "main - after converting the 1d array into 2d array, arr1 is:" << endl;
for (size_t i = 0; i < numOfRows; ++i)
{
for (size_t j = 0; j < numOfCol; ++j)
{
cout << "arr1[" << i << "]" << "[" << j << "]:" << arr1[i][j] << " ";
}
cout << endl;
}
// for debug - you can remove this if not needed...
cout << "main - end, enter any key and press enter to terminate..." << endl;
char tmp;
cin >> tmp;
return 0;
}
Hope it helps.
Cheers,
Guy.
thank you everyone for your support the MAIN mistake i was doing is the use of gets(arr) and doing arr[10] as if you are using function gets(arr) you have to give one extra index which is used by this function gets(arr) i.e. arr[11]
solved :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find greatest number entered, and then display it to the user.
So once the user enters several numbers, program calls function that will find it and then return it. Unfortunately every time I run it, the number resets to zero even after the function has worked successfully. What do I do wrong?
Visual Studio mentions this: Run-Time Check Failure #3 - The variable 'gromax' is being used without being initialized.
int largestGroup(int groupsize[], int theValue)
{
int gromax=groupsize[0];
for (int i=1;i<9;i++){
if(groupsize[i] > gromax){
gromax=groupsize[i];
}
}
return gromax;
}
int main()
{
int groupsize[10]={0,0,0,0,0,0,0,0,0,0};
int gromax = groupsize[0];
char newentry='n';
do{
cin >> groupsize[i];
cout << string(60, '\n');
cout << "Would you like to enter another questionare? Enter either 'y' or 'n': " << endl;
cin >> newentry;
cin.ignore();
}while((newentry =='y') || (newentry=='Y'));
largestGroup(groupsize, i);
cout << "Number of customers in largest group today was " << gromax << endl;
Insert in the very beginning of main
int i = 0;
and inside the loop increase it as for example
cin >> groupsize[i++];
Change this
largestGroup(groupsize, i);
statement to
int gromax = largestGroup(groupsize, i);
And remove statement
int gromax = groupsize[0];
Also you shall check in the loop that you are not trying to acces a memory beyond the array.
And function largestGroup is wrong.
int largestGroup(int groupsize[], int theValue)
{
int gromax=groupsize[0];
This declares a function that - despite appearances - actually takes an array and an integer (inherited from C, arrays can decay to pointers as necessary, and it's deemed necessary when someone tries to pass them to functions).
Then, it declares a private local variable, gromax. This value, think of it as largestGroup::gromax, exists only for the life time of each individual call to the function. The last line of the function is then paramount.
return gromax;
}
This pushes the "gromax" into whatever CPU register/location return values are stored. It will live there until something else uses the value.
The language does not automatically transfer the value anywhere, even if your calling function has a variable of the same name.
So, the bug in your code is this:
largestGroup(groupsize, i);
You call the function, and you never capture the return value.
gromax = largestGroup(groupsize, i);
would capture the value.
Be aware that arrays are passed by address/pointer (live demo: http://ideone.com/DTkbFn)
#include <iostream>
void f(int groups[5], int x)
{
x = 3;
groups[x] = 999;
}
int main()
{
int groups[5] = { 0, 1, 2, 3, 4 };
int x = 10;
std::cout << "before: x = " << x << ", groups[3] = " << groups[x] << '\n';
f(groups, x);
std::cout << "after: x = " << x << ", groups[3] = " << groups[x] << '\n';
return 0;
}
When you pass an array, you are actually passing by pointer, so normal "pass by value" behavior does not apply.
int largestGroup(int groupsize[], int thevalue)
is actually equivalent to
int largestGroup(int* groupsize, int theValue)
It is advisable to use the second syntax to avoid falling into the trap of thinking you can modify groupsize with no impact on the caller.
You didn't use the return value. Try:
gromax = largestGroup(groupsize, 1);