Working on an exercise that wants to print out the index position of the number in the array once the user inputs what value he chooses.
Here's the code so far but don't know how to organize it to print of the index position of the number they put in from the list of the array
#include <iostream>
using namespace std;
int main()
{
int numbers [11] = {5, 2, 11, 6, 33, 756, 32, 0, 1, 31, -1,};
int num = 0;
int x = 0;
cout << "List:" ;
for (int i = 0; i <= 11; i++)
{
cout << numbers [i] << ", ";
}
cout << endl;
cout << "Enter a number from the list to find its position: ";
cin >> num;
numbers [x] = {num};
cout << numbers [x];
}
basically all its doing now is printing out the number you put in instead of the location it is in the array....
also how do you input values into an array from the user input
First, this is Undefined behavior,
for (int i = 0; i <= 11; i++) // will iterate from 0 to 11
Arrays range starts from 0, so if you want to loop through it or need to go to last element, you should access Array[MaxNum-1].
So you should be using,
for (int i = 0; i < 11; i++) // will iterate from 0 to (11-1)
Now coming to your doubt::
You should iterate through entire array, find your number and then print the index as following::
int nIndex = -1 ;
for (int i = 0; i < 11; i++ )
{
if ( numbers[i] == num )
{
nIndex = i ;
break ;
// Or to end the loop, you can set i = SomeValueToBreakTheCondition
// ex., i = 11
}
}
if( nIndex == -1 )
{
std::cout << Element Not Found ;
}
else
{
std::cout << "Element Found Out Index::" << nIndex ;
}
When you write int numbers[11], that is an array of 11 elements whose indices are 0 through 10.
So when you have i <= 11 in your loop; the last loop iteration reads beyond the end of the array, causing undefined behaviour. Change this to i < 11, or even better i < sizeof numbers / sizeof numbers[0], which you can wrap in a macro if you think it looks nice.
numbers [x] = {num}; would be better written as numbers[x] = num;. Anyway, you then go: cout << numbers[x] which does exactly what you say: it puts out the number at the location indexed by x, which you just stored num in.
If you want to putout the location then do cout << x;.
how do you input values into an array from the user input
You're already doing that , cin >> num; numbers[x] = num; does that. You could go cin >> numbers[x]; directly. If you run a loop then you can input several numbers in a row, for example:
for( x = 0; x < 11; ++x )
cin >> numbers[x];
1- this program does not find the index!! for finding the index you should do a loop on your array and compare the array[i] and the x
for(int i = 0 ; i < 10 ; i++)
{
if(number[i] == x)
{
// do what you want with index i
}
}
2- for inputting an array, you can do something like this
for(int i = 0 ; i < 10 ; i++) { cin >> numbers[i]; }
You are not checking in which index the given number is. The statement:
numbers [x] = {num};
simply assigns num to the x-th item of the array. In your case, x has been initialized to zero. So, the first item of the array gets set to num and
cout << numbers [x];
always prints the first item of the array.
You can fix this by replacing the lies
numbers [x] = {num};
cout << numbers [x];
by
for (int i = 0; i < 11; ++i )
{
if ( numbers[i] == num )
{
cout << i << endl;
break;
}
}
if ( i == 11 )
{
cout << "Number not found" << endl;
}
You can make a loop to find the index by yourself, also you can use std::find:
int* pos = find(&numbers[0], &numbers[11], num);
if (pos == &numbers[11]) {
cout << "not found\n";
} else {
cout << (pos - &numbers[0]) << endl;
}
In addition, you should change
for (int i = 0; i <= 11; i++)
to
for (int i = 0; i < 11; i++)
to avoid array index goes out of range.
Related
How do I edit the given program to get all possible combinations of array values which will provide the given data using addition operator?
The following code works fine only if there is only one combination. For example, in the array = {1,2,3,4,5}, the given value = 6; the only possibility is the sum of 2 and 4. Thus the output desired is array [1] & array[3]. Attached coding works fine for this. But for array ={1, 3, 3, 4, 2}, there is two possibilities but the code returns nothing...
#include<iostream>
using namespace std;
int main() {
int n = 5; int m = 0;
int givendata;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cin >> givendata;
if (m < n) {
for (int i = 0; i < n; i++) {
int sum = a[n - i] + a[m];
if (sum == givendata) {
cout << m << " " << n - i;
}
}
}
m = m + 1;
return 0;
}
You need to use a double loop to compare all the values:
// start at 0, the first position of the array. Loop until the 2nd to last element
for (int i=0; i<n-1;i++)
{
// start this index at one higher than i. Since a+b == b+a, there's no need to
// add the later values in the array with the previous ones, we've already
// done that
for (int j=i+1; j<n; j++)
{
int sum = a[i]+a[j];
if (sum == givendata)
{
std::cout << a[i] << " + " << a[j] << " = " << givendata << std::endl;
}
}
}
Demonstration
Also see Why is "using namespace std;" considered bad practice?
Would like to seek a bit of help from StackOverflow. I am trying to print out the sequence of Fibonacci number and also the number of time the iterative function is called which is supposed to be 5 if the input is 5.
However, I am only getting 4199371 as a count which is a huge number and I am trying to solve the problem since four hours. Hope anyone who could spot some mistake could give a hint.
#include <iostream>
using namespace std;
int fibIterative(int);
int main()
{
int num, c1;
cout << "Please enter the number of term of fibonacci number to be displayed: ";
cin >> num;
for (int x = 0; x <= num; x++)
{
cout << fibIterative(x);
if (fibIterative(x) != 0) {
c1++;
}
}
cout << endl << "Number of time the iterative function is called: " << c1 << endl;
}
int fibIterative(int n)
{
int i = 1;
int j = 0;
for(int k = 1; k <= n; k++) {
j = i + j;
i = j - i;
}
return j;
}
First, initialize the variable
c1 = 0;
so that you will not get any garbage value get printed.
Secondly this:
if (fibIterative(x) != 0)
{
c1++;
}
will make 2*count - 1 your count. You don't need that.
Edit: I have noticed that you have removed extra c1++; from your first revision. Hence, the above problem is not more valid. However, you are calling the function fibIterative() again to have a check, which is not a good idea. You could have simply print c1-1 at the end, to show the count.
Thirdly,
for (int x = 0; x <= num; x++)
you are starting from 0 till equal to x that means 0,1,2,3,4,5 total of 6 iterations; not 5.
If you meant to start from x = 1, you need this:
for (int x = 1; x <= num; x++)
{ ^
cout << fibIterative(x) << " ";
c1++;
}
I wrote code that prints classLength length combinations out of length elements. It works fine but I don't understand why.
My Questions:
When the
while(index[0] != length - classLength)
loop finishes the program doesn't print the last combination so I have to print it after the while loop. Why is that?
I tried changing the condition in the above mentioned while loop.
Instead length-classLength I wrote lenght-classLength+1
When running the program this resulted in an infinite loop. Why did this happen?
Note the commented part of the
while(index[position] == maxIndex /*&& position >= 0*/)
while loop condition and commented if statement
/*if(position>=0)*/ index[position]++;
Program will run fine when those parts of code are uncommented and when they are commented. I originally wrote the code with those conditions so the program doesn't access an array with an improper index. But this works just fine without those security checks. Why are indices always in range and errors don't occur?
C++ code
#include <iostream>
#include <fstream>
using namespace std;
/**Print all combinations of k-th class of n elements**/
int main() {
const int maxN = 100;
int length = 0, classLength = 0;
cout << "Input number of elements and class number: " << endl;
cin >> length >> classLength;
int array[maxN];
cout << "Input elements: " << endl;
for(int i = 0; i < length; i++)
cin >> array[i];
//first combination has indices 0, 1, ... , k-1
int index[maxN];
for(int i = 0; i < classLength; i++)
index[i] = i;
int ordNum = 1;
ofstream out("output.txt");
//length of class is classLength, last combination's last element's index is n-1
//last combination's last element's index is n-1-k
while(index[0] != length - classLength) {
//print current combination
out << ordNum++ << ")\t";
for(int i = 0; i < classLength; i++)
out << array[index[i]] << " ";
out << endl;
int position = classLength-1, maxIndex = length-1;
//if index at current position is its max
// value then we have to carry digit
while(index[position] == maxIndex /*&& position >= 0*/) {
index[position] = -1;
position--, maxIndex--;
}
//when loop stops position is at index that
//should be added the carried 1
/*if(position>=0)*/
index[position]++;
//if a carry accured indices must be arranged so that
//array index[] is non-decreasing
for(int i = 1; i < classLength; i++)
if(index[i] <= index[i-1])
index[i] = index[i-1]+1;
}
out << ordNum++ << ")\t";
for(int i = 0; i < classLength; i++)
out << array[index[i]] << " ";
out << endl;
out.close();
return 0;
}
I'm trying to write the code for a C++ program which will get some numbers (integers) and will put them into a 100 sized array, and will begin searching for possibly given negative ones (Negative of given positive numbers) after the user had inputted the sentinel number (101). For example; when we give the integers 1, 45, 12, -32, 103, 2015 and 32 to the program, it should give us the the integer 32 (because the negative form of it is existing) and if there were no numbers with this statement, then it will prints nothing. I wrote something like below; but I don't know how to do the rest... Any help or suggestions are appreciated.
I forgot to say that I use CodeBlocks 13.12 .
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[0]= number;
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){
if (myArray[i] > 0) // I'm stuck at here!
}
return 0;
}
Thanks and please apologize for possible English mistakes.
Here are some mistakes in the code :
First, you are assigning all the input elements to the 0th indexed element of the array.
The user can very well give 200 elements without typing 101, in that case you will overrun your array size.
A simple algorithm should be like this:
Pick the ith positive element and search through out the array for its negative.
Repeat 1 for every possible positive element in the array.
Here is a working example.
The input should be like this :
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
And the checking condition:
for ( i = 0; i < nCounter; i++ ){
if (myArray[i] > 0) {
for( j = 0; j < nCounter; j++) {
if(myArray[i] + myArray[j] == 0) // positive and negative add up to 0
std::cout << myArray[i] << std::endl ;
}
}
}
Here's a slight modification of your code that will get you what you need
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i, negMatch;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
cout << "Enter the number to negative match";
cin >> negMatch;
for ( i = 0; i < nCounter; i++ ){
if ( (myArray[i] + negMatch) == 0) {
cout << myArray[i];
return 0;
}
}
return 0;
}
Please note the following changes:
You were inserting all the elements into the first slot, I changed it so that you enter them in the correct spot
Getting the number to be matched as input (negMatch is "32" in your question)
Modified the loop to check the numbers
However, this program is not ideal. Ideally, you would use something like Vectors, which can dynamically grow. Also, it might be better to have the user input the count of numbers, instead of using a sentinel number that he might want to give as input.
If I understand this correctly you want to print the negative ones but with positive sign. With this simple code you can do it!
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
for (int i = 0; i < nCounter; i++ ){
if (myArray[i] < 0) {
std::cout << (myArray[i] * -1) << std::endl ;
}
}
return 0;
}
A simple change that reduce the computational cost is the following: you can try to get information from the number given when you read it
#include <iostream>
#include <vector>
using namespace std;
int number = 0, sentinel = 101;
int main (){
cout << "Please enter your numbers: " << endl;
vector<int> array;
while (number != sentinel) {
std::cin >> number;
if(number < 0)
array.push_back(number);
}
for (int i = 0; i < array.size(); i++ )
std::cout << (array[i] * -1) << std::endl ;
return 0;
}
I suggest to write positive numbers in the beginning of the array and negative numbers in the end of the array.
Here is a demonstrative program
#include <iostream>
int main()
{
const size_t N = 100;
const int SENTINEL = 101;
int a[N];
int number;
size_t positive_end = 0;
size_t negative_begin = N;
for ( size_t i = 0; i < N && std::cin >> number && number != SENTINEL; i++ )
{
if ( number < 0 )
{
a[--negative_begin] = number;
}
else
{
a[positive_end++] = number;
}
}
if ( positive_end != 0 && negative_begin != N )
{
for ( size_t i = 0; i < positive_end; i++ )
{
size_t j = negative_begin;
while ( j != N && a[i] + a[j] != 0 ) ++j;
if ( j != N ) std::cout << a[i] << '\t' << a[j] << std::endl;
}
}
return 0;
}
If for example to enter the following sequence of numbers
1 2 -3 4 -5 6 7 3 -9 9 101
then the output will be
3 -3
9 -9
Also you could sort each part of the array (the part of positive numbers and the part of negative numbers) and apply standard algorithm std::set_intersection. In this case you could exclude situations when one negative number corresponds to several positive numbers.:)
You did not pay enough attention to the logic of your code. I'll assume you are very new at this, but no person will want to enter 100 inputs before they see what your program does.
Here is what's wrong with your code:
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i; // OK
int myArray[100]; // OK, an array with 100 elements
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){ //this is where you got it wrong
// this should have been nCounter instead of number
// If you are looking at 100 elements then the condition
// should be "nCounter != 100"
cin >> number;
myArray[0]= number; // this should have been "myArray [nCounter]=number;"
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){ // defining i from outer scope is unnecessary
// since it is only used in the for loop
if (myArray[i] > 0) // I'm stuck at here! // Put a semicolon here
// the remainder of the code probably here
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//initialize size and empty array
int size = 10, x;
int myArray[10] = {};
//enter integers into array
for (int i = 0; i < size; i++)
{
cin >> myArray[i];
}
//search array for negative numbers
for (int i = 0; i < size; i++)
{
if (myArray[i] < 0)
{
x = (myArray[i] * (-1)); //multiply by -1 to get (+)
cout << x << ' ';
}
}
return 0;
}
The problem is that, I have an array of 10 integers, having some duplicates. The task is to copy this array to another array of same size, but without duplicate values. That is, read one element from array1, compare it with all the elements in array2, if it's already in array2, just skip it or print that it's already in array2, go to second element of array1, and repeat the process.
Now, I've tried this but don't know where's the problem:
#include <iostream>
using namespace std;
int main()
{
int temp;
int array1[] = {10,2,5,4,10,5,6,9,8,10};
int array2[11] = {0};
for(int i = 1; i <= 10; i++)
{
temp = array1[i-1];
for(int j = 1; j <= 10; j++)
{
if(temp == array2[j])
{
cout << "Duplicate " << temp << endl;
i++;
break;
}
}
array2[i] = array1[i-1];
}
for(int k = 1; k <= 10; k++)
cout << array2[k] << " " << endl;
system("pause");
}
array1 has 10 elements and array2 has 11, so right away the requirements haven't been met. Presumably, having 11 elements was a workaround for using incorrect index values in the for loops; the index should run from 0 to 9, not from 1 to 10.
When you add an element to the second array, you should only check it value against the elements that have already been added, not against the values in the entire array.
Finally, there's an underspecification. Once you've eliminated duplicates, you have fewer than 10 elements; array2 has 10 elements; what values should the extra elements have?
std::unique_copy is your friend:
http://en.cppreference.com/w/cpp/algorithm/unique_copy
remember to sort the source array first
In C++, break immediately ends one loop structure, and starts execution immediately after it. Thus, the line array2[i] = array1[i-1]; executes redardless of whether the inner for loop finds a duplicate. One solution is to set a variable indicating that the value is a duplicate:
int main() {
int temp;
bool isDuplicate; //added this line
int array1[] = {10,2,5,4,10,5,6,9,8,10};
int array2[11] = {0};
for(int i = 1; i <= 10; i++)
{
temp = array1[i-1];
isDuplicate=false;//added this line
for(int j = 1; j <= 10; j++)
{
if(temp == array2[j])
{
cout << "Duplicate " << temp << endl;
i++;
isDuplicate=true; //added this line
break;
}
}
if(!isDuplicate) //added this line
array2[i] = array1[i-1];
}
for(int k = 1; k <= 10; k++)
cout << array2[k] << " " << endl; system("pause"); }
Alternatively (though many programmers would disagree with this practice) you could use a goto statement instead of a break statement:
int main()
{
int temp;
int array1[] = {10,2,5,4,10,5,6,9,8,10};
int array2[11] = {0};
for(int i = 1; i <= 10; i++)
{
temp = array1[i-1];
for(int j = 1; j <= 10; j++)
{
if(temp == array2[j])
{
cout << "Duplicate " << temp << endl;
i++;
goto duplicate; //added this line
}
}
array2[i] = array1[i-1];
//added next line
duplicate:
}
for(int k = 1; k <= 10; k++)
cout << array2[k] << " " << endl;
system("pause");
}
You could use a std::set to ensure uniqueness for you.
http://en.cppreference.com/w/cpp/container/set
You have three approaches:
compare each element one by one (O(N^2) performance)
sort your reference array and use a binary search to determine if the element exists (O(N*lnN) performance)
create a lookup hash (O(1) performance)
I can see two main sources of problems in your code: 1) the break statement, as it is, does not solve the problem of differentiating between the case when duplicate is found, and when the element in array1 should be added to array2. 2) There is no counter which would store the number of elements inserted so far into array2, this way they could not be copied to array2 next to each other. The code which fixes both is:
#include <iostream>
using namespace std;
int main()
{
int array1[] = {10,2,5,4,10,5,6,9,8,10};
int array2[10];
int array2_elements_inserted = 0;
for(int i = 0; i < 10; i++)
{
int temp = array1[i];
bool isDuplicate = false;
for(int j = 0; j < array2_elements_inserted; j++)
{
if(temp == array2[j])
{
cout << "Duplicate " << temp << endl;
isDuplicate = true;
break;
}
}
if (!isDuplicate)
{
array2[array2_elements_inserted] = temp;
++array2_elements_inserted;
}
}
for(int k = 0; k < array2_elements_inserted; k++)
cout << array2[k] << " " << endl;
// system("pause");
}
Output:
10
2
5
4
6
9
8
First of all, use dynamic containers. Especially have a look at those provide by
the standard library, e.g. std::vector. Second, you should use a set data structure
to keep track of the elements you have seen before, e.g., std::set.
Then it's just an iteration on the input array and appending new elements to the
output array.
Here's an example:
#include <vector>
#include <set>
#include <iostream>
int main() {
// define and print input data
std::vector<int> v1 = {10,2,5,4,10,5,6,9,8,10};
for (int i : v1)
std::cout << i << " ";
std::cout << "\n";
// this will soon contain the output data
std::vector<int> v2;
// a set to keep track of the already seen elements
std::set<int> set;
// iterate the input array using range-based for loop
for (int i : v1) {
// check for duplicates
if (set.find(i) == set.end()) {
// first occurrence, insert to set, append to output data
set.insert(i);
v2.push_back(i);
}
else {
// seen before, do nothing
}
}
// print output data
for (int i : v2)
std::cout << i << " ";
std::cout << "\n";
}
The output:
$ g++ test.cc -std=c++11 && ./a.out
10 2 5 4 10 5 6 9 8 10
10 2 5 4 6 9 8
For reference:
http://en.cppreference.com/w/cpp/container/vector
http://en.cppreference.com/w/cpp/language/range-for
http://en.cppreference.com/w/cpp/container/set
http://en.cppreference.com/w/cpp/container/set/find