I am trying to learn how to code array.. (i am still a beginner in programming just starting to learn last year) i don't know what's wrong in my code.. the problem is to take 5 integer inputs from user and store them in an array. Again ask user to give a number. Now, tell user whether that number is present in array or not. but my code doesn't recognize my else. Even if i put a number that isn't present in my array it still says "It is present".
int main(){
int num[4];
int i;
int comp;
cout<<"Please input 5 numbers: "<<endl;
for (i=0;i<=4;i++)
{
cin>>num[i];
}
cout<<"Now please input another number to compare: ";
cin>>comp;
if (num[i]=comp){
cout<<"The number you inputted is present in the array";
}
else {
cout<<"It is not present in the array";
}
}
the problem is to take 5 integer inputs from user and store them in an array.
Let's start declaring an array that can hold up to 5 integers.
int numbers[5] = {};
// ^^^ This should be the size of the array, not the maximum index
Since C++11, you can use a proper standard container
std::array<int, 5> numbers{};
Note that in both snippet I initialized those arrays.
Now, the loop that reads all the elements of the array can be written as
for (int i = 0; i < 5; ++i) {
// ^
}
Or use a ranged for
for (auto & number : numbers)
{ // ^^^^^^^^ Loops through the array using `number` as a reference to each element
std::cin >> number;
if (!std::cin) {
std::cerr << "An error occurred while reading.\n";
break;
}
}
The posted loop also goes from 0 to 4 (included), but the array declared in that snippet only has 4 elements, so that it is accessed out of bounds and the program has undefined behaviour.
Another problem, is that the program doesn't check
whether that number is present in array or not
It does only one "check", instead of a loop:
if ( num[i] = comp) {
num[i] = comp is an assignment, not a comparison (you should adequately rise your compiler warning level) and an assignment to an element outside the array (i has value 5, now). It's the result of this assignment, comp, that is used as a condition, which means that the branch is executed whenever comp is not 0.
Or, at least, this is the most likely outcome, given that that assignment is UB too and the compiler could genereate whatever code it decides or your program could seg-fault due to that access out of bounds.
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
int num[4];
int i;
int comp;
int coo;
int flg=0;
std::cout<<"Please input four numbers: "<<"\n";
for (i=0;i<=3;i++)
{
std::cin>>num[i];
}
std::cout<<"Now please input another number to compare: ";
std::cin>>comp;
for (i=0;i<=3;i++)
{
if (num[i]==comp){
flg = 1;
break;
}
}
if (flg) {
printf("The number you inputted is present in the array.\n","%s");
} else {
printf("It is not present in the array\n", "%s");
}
std::cin>>coo;
return 0;
}
Basically, you ommitted to loop through all the array members when comparing the array with the number to be compared and I just added the loop in so that it looped through all array members and compared it with the input number.
Related
im trying to let the user input a number for each person. the console then outputs the maximum value in the array. everything works fine but the max always outputs as -858993460. i tried multiple combinations but i cant seem to figure it out
im new to arrays so any help would be appreciated as well as an feedback on how to improve my code
#include <iostream>
int main()
{
int people[10];
int max = people[0];
std::cout << "please enter number of pancakes eaten by each person.\n";
//lets the user input values for each element
for (int i = 0; i < 10; ++i) {
std::cin >> people[i];
}
//outputs all the elements of the array
for (int i = 0; i < 10; ++i) {
std::cout << people[i] << " ";
}
//finds the largest element in the array
for (int i = 0; i > 10; ++i) {
if (people[i] > max) {
max = people[i];
}
}
std::cout << "\nmax: " << max;
return 0;
}
also i keep getting a warning saying: ill-defined for-loop. loop body not executed. i tried looking this warning up but the warning seems very broad and i couldnt find anything that helped
int people[10];
This declares an array of ten int values. None of the values are explicitly initialized. This is how plain values that get declared in automatic scope work in C++, they are not initialized to any values. It is the code's responsibility to initialize them.
int max = people[0];
This sets the value of max to the first value of the array. Which has not been initialized to any value. This is undefined behavior. From this point on the program's behavior is undefined.
Furthermore, even if peoples values were initialized this will still be broken. The intent of the program is clear: read values into the people array, and then find their maximum value.
However, at this point, nothing has been read from anywhere.
The attempted goal here is to set max, initially, to the first value in the array, the first read value.
But in order for this to make sense, max should be set after the values in the array get read from input, and not before. This should be done after all the values are read in, and not before.
in the line int max = people[0] you are dereferencing the first element of the array. But dereferencing to what? at that point in the program you have not initialised any of the 10 elements in the people array. So taking the value at people[0] at that point in the program and copying it into another int for later comparison is undefined behaviour. Best solution is to simply move int max = people[0] to after you take the user input, and for the comparison loop start with i = 1, because max is already equivalent to the first inputted value.
I like to fill this array to only up to a[4] and want to traverse only up to 4th position not the enire length.
int main()
{
int a[10],i,j=0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
}
while(a[j]!='\0')
{
cout<<a[j];
j++;
}
}
this code prints 11 numbers
If you can use a special value, such as zero, to indicate the items past the end, the way '\0' is used in C strings, you could use your approach after initializing a to all zeros:
int a[10] = {0};
...
while (a[j]) {
cout << a[j++];
}
The downside to this approach is that the end-marker becomes invalid in the input. In other words, if end-user enters a zero among the four inputs, printing will stop after printing fewer than four items.
That is why these two approaches are more common:
Use a dynamic container, such as std::vector<int> - this approach is valid only in C++
Store the number of items in a separate variable - if you must use a "raw" array, this approach is the most common.
The answer is: You can't. int arrays have nothing like a C style string termination.
An array has a fixed size and the array can't tell how many elements that you have written to. So if you want to use an array for this, you'll have to ad code to count how many elements that you have written, i.e. by using an extra variable for counting.
Like:
int a[10],i,j=0;
int valid_elements = 0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
++valid_elements;
}
for(i=0;i<valid_elements;i++)
{
cout<<a[i];
}
However, that is normally not a good approach.
A much better approach is a vector as the number of elements in a vector is dynamic. You can do something like:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> a;
int i, j;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>j;
a.push_back(j);
}
for (int x : a) // Range based for loop automatic iterates all elements in the vector
{
cout<<x;
}
return 0;
}
Well all I had to do was:
user has to enter 20 numbers.
and I should find from array numbers lower than the last number user entered ( 20 numbers )
Example :
User enters:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,4
Output should be:
1,2,3
according to me, my output is correct. But after 1,2,3 alot of 0 come in.
#include <iostream>
using namespace std;
int i,skaitlis,sk2,x;
int masivs[19];
int main() {
for ( i=0; i<=19; i++ )
{
cin >> masivs[i];
skaitlis = masivs[19];
}
for (i=0;i < sizeof masivs; i++){
if ( masivs[i]<skaitlis){
cout << masivs[i] <<endl;
}
}
}
The problem is here:
for (i=0;i < sizeof masivs; i++){
The sizeof operator returns the size of the array in bytes, not in number of elements. On normal modern systems the size of an int is four bytes, meaning sizeof masivs will give you 4*19.
That will lead the loop going massively out of bounds and give you undefined behavior.
Not to mention the other out of bounds you have in the previous loop.
Also, taking about the first loop, why have the assignment to skaitlis inside the loop? After you fix the out-of-bounds indexing, it will just assign zero (because masivs is a global variable and therefore initialized to all zeroes) except in the last iteration. You can move that assignment to be outside the loop.
My C++ program named "coinChange.cpp" reports the number of notes of different figures for changing a given integer amount. The code is
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
cout<<"please enter the amount: ";
int amount;
cin>>amount;
int totalNoOfCoins=0;
int coins[]= {100,50,20,10,5,1};
int noOfCoins[sizeof(coins)]= {0};
int counter=0;
while(amount>0)
{
if(amount>coins[counter])
{
noOfCoins[counter]=amount/coins[counter];
amount-=noOfCoins[counter]*coins[counter];
}
counter++;
}
string output="The amount can be changed by:\n";
for(int i=0;i<sizeof(coins);i++)
{
if(noOfCoins[i]>0)
{
ostringstream oss;
ostringstream oss1;
oss<<coins[i];
oss1<<noOfCoins[i];
if(noOfCoins[i]>1) output+="\t\t\t"+oss1.str()+" nos of "+oss.str()+" taka notes \n";
else output+="\t\t\t"+oss1.str()+" no of "+oss.str()+" taka note \n";
}
}
cout<<output<<endl;
return 0;
}
The result is okay for almost any integers like 34, 37829, ... etc, but the problem arises when the user inputs a number that ends in 6 like 6, x6, xx6, xxx6 etc.
There are 3 issues I see with your code.
First, the obvious one:
You are misusing sizeof:
int noOfCoins[sizeof(coins)]= {0};
This should be:
const int numCoins = sizeof(coins) / sizeof(coins[0]);
int noOfCoins[numCoins]= {0};
Then from there, you can use numCoins for the rest of the code:
for(int i=0;i < numCoins; i++)
The reason why sizeof(coins) did not work is that sizeof returns the size in bytes.
So if you have an array of 6 ints, the sizeof the array is sizeof(int) * 6, which is (assuming you are using 4 byte integers), 24. That goes way beyond the bounds of your array, thus you get undefined behavior.
Second issue: Faulty while() loop condition:
In the while loop condition, you're only testing for amount > 0. But what if amount is a large value? Your while loop will increment counter to beyond the bounds of your array, and you will be using counter as an index in your coins array, thus accessing beyond the bounds of the array.
The while loop should have this condition:
while (amount > 0 && counter < numCoins)
Third issue: Faulty test logic for the right coinage amount
You do this:
if (amount > coins[counter])
But this is wrong. What if the amount entered is simply 100? You miss the check for the 100 note using the above condition. This simply needs to be changed to this:
if (amount >= coins[counter])
Please i am stuck at this question for half an hour and can't find why the error comes?
Problem code : test
Life, Universe and Everything
#include<iostream>
using namespace std;
int main()
{
int a[20],i;
cin>>a[0];
for(i=1;a[i-1]!=42;i++)
{
cout<<a[i]<<"\n";
cin>>a[i];
}
return(0);
}
Your code tries to access non-existing array elements, which causes segfault. You should stop your loop before the array index gets larger than the length of the array minus 1:
int a[20];
for (i = 1; i < 20 && a[i - 1] != 42; i++)
{
// ...
}
Apart from limit problem, your printing elements without initializing them
//for i = 1, a[i] is uninitialized
cout<<a[i]<<"\n";
On accessing a local variable (like this), you're likely to get garbage value.
This might be better substitute for what you are trying to do:
int a[20],i;
for(i=0;i < 20;i++)
{
cin>>a[i];
if (a[i] == 42)
break;
cout<<a[i]<<"\n";
}
You are trying to print the uninitialized data...
#include<iostream>
using namespace std;
int main()
{
int a[20],i;
cin>>a[0]; // a[0] uninitialized
for(i=1;a[i-1]!=42;i++)
{
cout<<a[i]<<"\n";
cin>>a[i];
}
return(0);
}
In the for loop get the data first and then print it.Your array size is 20 but you are trying to write upto 42.
You use array values before initializing them. C++ doesn't initialize non-static arrays for you unless you tell it to, so $DEITY knows what's in there. And technically, whatever's in there could cause an exception...or any number of other things. (For ints, on an x86 machine, that's actually highly unlikely. But elsewhere, it's possible.)
The user can enter more than 20 numbers. That's really just a special case of the more general problem, though: You allow unknown number of entries, but aren't able to accept them all without crashing.
If you don't know beforehand how many objects there will be, use a vector.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<int> a;
int entry;
cin>>entry;
// Oh, yeah. This. You really, *really* want to check `cin`.
// Otherwise, if the user decided to type "i like cheese", you'd loop
// forever getting zeros while cin tried to parse a number.
// With the array, that'd typically cause a segfault near instantly.
// With a vector, it'll just eat up all your CPU and memory. :P
while (cin && entry != 42) {
a.push_back(entry);
cout << entry << "\n";
cin >> entry;
}
return 0;
}