Why doesn't my array store any input values? - c++

I want to input any number into array b[] by number of numCase times.
#include <iostream>
using namespace std;
//entry point
int main()
{
//Declarations
int b[20]; // array size 20 ( limit of inputs)
int c = 0;
int numCase;
int input;
cout << "ENTER NUMBER OF CASES (MAXIMUM NUMBER OF 20): \n";
cin >> numCase;
//checks that numCase is less than or equal to (20) and does not exceed
if (numCase < 21)
{
// gets input number based on the numCase
do
{
cout << "ENTER A NUMBER (MAXIMUM OF 5 DIGITS): \n";
cin >> input;
cout << "\n";
b[c] = input;
c++;
} while (c != numCase);
cout << b[c] ; // this is my problem it OUTPUTS RANDOM VALUE,
//but i can see on my watch list that b has the values of my input.
}
}

You're filling entries 0 toN of b, and then printing entry N+1, which you haven't filled in.

The variable c should be initialised back to zero.
} while (c != numCase);
c = 0;

cout << b[c] ; // in this statement c already reached to numCase where you have not assigned any value

I think this is what you might be looking for:
for (int i=0; i<numCase; i++)
{
if(b[i] >= x) //x is a variable that u can set as a limit. eg. 700
{
cout<<"\n"<<b[i];
}
}
Hope it helps

If you want to display all the numbers stored in array b[]
then you may write your code as
for(int i=0;i<=20;i++)
{ if(b[i]<101) //This will exclude all the values which are greater than 101
{cout<<"\n"<<b[i];}}

Related

Subtract each elements of an array consecutively

I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5.
But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size.
Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on.
The problem is, how do I subtract them? I have two options:
The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on.
I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input.
Question: How do you solve this problem?
(This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?)
Thanks.
Let's see my code below of how I insert the user input into the array.
string input[100];
int arrayInput[100];
int x = 0;
for (int i = 0; i >= 0; i++) //which this will run until the user input 'count'
{
cout << "Number " << i+1 << ": ";
cin >> input[i];
arrayInput[i] = atoi(input[i].c_str());
...
//code to subtract them, and final answer will be in int x
...
if (input[i] == "count")
{
cout << "Result: " << x << endl;
}
}
You can/should use a dynamic sized container like std::vector as shown below:
#include <iostream>
#include <vector>
int main()
{
int n = 0;
//ask user how many input he/she wants to give
std::cout << "How many elements do you want to enter: ";
std::cin >> n;
std::vector<int> vec(n); //create a vector of size n
int resultOfSubtraction = 0;
//take input from user
for(int i = 0 ; i < n ; ++i)
{
std::cin >> vec.at(i);
if(i != 0)
{
resultOfSubtraction-= vec.at(i);
}
else
{
resultOfSubtraction = vec.at(i);
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}
Execute the program here.
If you want a string to end the loop then you can use:
#include <iostream>
#include <vector>
#include <sstream>
int main()
{
std::vector<int> vec;
int resultOfSubtraction = 0, i = 0;
std::string endLoopString = "count";
std::string inputString;
int number = 0;
//take input from user
while((std::getline(std::cin, inputString)) && (inputString!=endLoopString))
{
std::istringstream ss(inputString);
if(ss >> number)
{
vec.push_back(number);
if(i == 0)
{
resultOfSubtraction = number;
}
else
{
resultOfSubtraction-= number;
}
++i;
}
}
std::cout<<"result is: "<<resultOfSubtraction<<std::endl;
return 0;
}

Counting occurences of same array value in C++

I recently have been building a program where:
A user is asked to enter a number that will represent the size of a character array.
Then they are asked whether they will want the program to fill the values automatically, or they could press M so they could enter the values manually. They may only enter a-zA-Z values, or they will see an error.
At the end of the program, I am required to count every duplicate value and display it, for example:
An array of 5 characters consists of A;A;A;F;G;
The output should be something like:
A - 3
F - 1
G - 1
I could do this easily, however, the teacher said I may not use an additional array, but I could make a good use of a few more variables and I also can't use a switch element. I'm totally lost and I can't find a solution. I've added the code down below. I have done everything, but the counting part.
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
void main() {
int n, i = 0;
char masiva_izvele, array[100], masiva_burts;
cout << "Enter array size: ";
cin >> n;
clrscr();
cout << "You chose an array of size " << n << endl;
cout << "\nPress M to enter array values manually\nPress A so the program could do it for you.\n\n";
cout << "Your choice (M/A): ";
cin >> masiva_izvele;
if (masiva_izvele == 'M' || masiva_izvele == 'm') {
clrscr();
for (i = 0; i < n; i++) {
do {
cout << "Enter " << i + 1 << " array element: ";
flushall();
cin >> masiva_burts;
cout << endl << int(masiva_burts);
if (isalpha(masiva_burts)) {
clrscr();
array[i] = masiva_burts;
}
else {
clrscr();
cout << "Unacceptable value, please enter a value from the alphabet!\n\n";
}
}
while (!isalpha(masiva_burts));
}
}
else if (masiva_izvele == 'A' || masiva_izvele == 'a') {
clrscr();
for (i = 0; i < n; i++) {
array[i] = rand() % 25 + 65;
}
}
clrscr();
cout << "Masivs ir izveidots! \nArray size is " << n <<
"\nArray consists of following elements:\n\n";
for (i = 0; i < n; i++) {
cout << array[i] << "\t";
}
cout << "\n\nPress any key to view the amount of every element in array.";
//The whole thing I miss goes here, teacher said I would need two for loops but I can't seem to find the solution.
getch();
}
I would be very thankful for a solution so I could move on and forgive my C++ amateur-ness as I've picked this language up just a few days ago.
Thanks.
EDIT: Edited title to suit the actual problem, as suggested in comments.
One possible way is to sort the array, and then iterate over it counting the current letter. When the letter changes (for example from 'A' to 'F' as in your example) print the letter and the count. Reset the counter and continue counting the next character.
The main loop should run foreach character in your string.
The secondary loop should run each time the main "passes by" to check if the current letter is in array. If it's there, then ++.
Add the array char chars[52] and count chars in this array. Then print out chars corresponding to the array, which count is more than 1.
std::unordered_map<char, int> chars;
...
char c = ...;
if ('A' <= c && c <= 'Z')
++chars[c];
else if ('a' <= c && c <= 'z')
++chars[c];
else
// unexpected char
...
for (const auto p : chars)
std::cout << p.first << ": " << p.second << " ";
Assuming upper and lower case letters are considered to be equal (otherwise, you need an array twice the size as the one proposed:
std::array<unsigned int, 26> counts; //!!!
// get number of characters to read
for(unsigned int i = 0; i < charactersToRead; ++i)
{
char c; // get a random value or read from console
// range check, calculate value in range [0; 25] from letter...
// now the trick: just do not store the value in an array,
// evaluate it d i r e c t l y instead:
++counts[c];
}
// no a d d i t i o n a l array so far...
char c = 'a';
for(auto n : counts)
{
if(n > 0) // this can happen now...
{
// output c and n appropriately!
}
++c; // only works on character sets without gaps in between [a; z]!
// special handling required if upper and lower case not considered equal!
}
Side note: (see CiaPan's comment to the question): If only true duplicates to be counted, must be if(n > 1) within last loop!

Floats breaking my code

I've written a program that returns the median value of a user-defined array. While I've put a few checks in my code (array size can not be negative) I keep running into one issue I simply can not fix (for clarity sake, assume strings and alphabetical characters will not be used).
All of my input values are int however the user could just as easily enter in a float. When they do this (either for size of array or entering in the element) it breaks my code. I've tried multiple things to try and catch this, but it seems like the way my program is getting the value doesn't allow for the catch in time.
#include <iostream>
using namespace std;
void sort(int * a,int n)
{
for(int i=0;i<n;++i)
for(int j=i+1;j<n;++j)
{
if(a[i]>a[j])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}\
}
return;
}
int main()
{
int n;
int check;
int x;
cout<<"Enter length of array:";
cin>>n;
if (n < 0){
while (n < 0){
cout << "Please enter a length greater than 0" << endl;
cin >> n;
}
} else if (n % 1 != 0){
while (n % 1 != 0){
cout << "Whole numbers only! Try again" << endl;
cin >> n;
}
}
if (n == 0){
cout <<"You try to enter numbers, but there's no place to put them." << endl;
cout << ":(";
return 0;
}
int a[n];
cout<<"Enter values one by one:\n";
for(int i=0;i<n;++i){
cin >> x;
a[i] = int(x);
}
sort(a,n);
if (n % 2 == 1){
cout<<"Median is:"<<a[n/2]<<endl;
}
else{
float z = (float(a[n/2]) + float(a[(n/2)-1])) / 2;
cout << "Median is:" << z << endl;
}
return 0;
}
First thing I tried was catching the float like so
`if (n % 1 !=0){
while(n % 1 !=0){
cout << "Enter a whole number"
cin >> n
}
}`
This still broke my program. The odd thing was that I entered a float and then printed the value of n and it only showed the int value.
I tried using typeid.n() with #include <typeinfo>and comparing that to an int type to check it was the correct value, but that slipped through as well.
I tried doing an int cast, something like int(n) immediately after number was stored in n but before it went into a[n] and yet again, it still broke my code.
How can I check against float user-input and loop them until they give me an int?
You're reading into an int:
int x;
...
cin >> x;
So it will read what it can, then stop at e.g. a . and leave the rest on the stream (like if the user enters "123.4" you'll get 123 and then ".4" won't be consumed from the input stream).
Instead, you could read into a float:
float x;
...
cin >> x;
And do the appropriate math.
Alternatively you could read into a string and parse it into a float. That way you won't get stuck at letters and such either.
And the final option is to read into an int but handle any errors and skip the bad input, which is detailed at How to handle wrong data type input so I won't reproduce it here.
Which option you choose really just depends on what you want the behavior of your program to be and how strictly you want to validate input (e.g. round vs. fail if "2.5" is entered but an integer is expected, how do you want to handle "xyz" as input, etc.).

How to take numerous inputs without assigning variable to each of them in C++?

I'm beginning with C++. The question is: to write a program to input 20 natural numbers and output the total number of odd numbers inputted using while loop.
Although the logic behind this is quite simple, i.e. to check whether the number is divisible by 2 or not. If no, then it is an odd number.
But, what bothers me is, do I have to specifically assign 20 variables for the user to input 20 numbers?
So, instead of writing cin>>a>>b>>c>>d>>.. 20 variables, can something be done to reduce all this calling of 20 variables, and in cases like accepting 50 numbers?
Q. Count total no of odd integer.
A.
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int n,odd=0;
cout<<"Number of input's\n";
cin>>n;
while(n-->0)
{
int y;
cin>>y;
if(y &1)
{
odd+=1;
}
}
cout<<"Odd numbers are "<<odd;
return 0;
}
You can process the input number one by one.
int i = 0; // variable for loop control
int num_of_odds = 0; // variable for output
while (i < 20) {
int a;
cin >> a;
if (a % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
If you do really want to save all the input numbers, you can use an array.
int i = 0; // variable for loop control
int a[20]; // array to store all the numbers
int num_of_odds = 0; // variable for output
while (i < 20) {
cin >> a[i];
i++;
}
i = 0;
while (i < 20) {
if (a[i] % 2 == 1) num_of_odds++;
i++;
}
cout << "there are " << num_of_odds << " odd number(s)." << endl;
Actually, you can also combine the two while-loop just like the first example.
Take one input and then process it and then after take another intput and so on.
int n= 20; // number of input
int oddnum= 0; //number of odd number
int input;
for (int i = 0; i < n; i ++){
cin >> input;
if (input % 2 == 1) oddnum++;
}
cout << "Number of odd numbers :"<<oddnum << "\n";

Compare 3 arrays c++ [like graph]

can any one help me about this
#include <iostream>
#include <stdio.h>
using namespace std;
int main () {
int A[100] , B[100] , C[100];
int i=0 ,j=0, h=0;
int connctive=0 ;
cout << "THE PROGRAM TAKE 3 GRAGHS ONLY\n";
cout << "\n enter the Graph 1 \n";
cin >> A[i];
cout << "\n enter the Graph 2 \n";
cin >> B[j];
cout << "\n enter the Graph 3 \n";
cin >> C[h];
for(i=0;i<=100;i++ ){
for (j=0;j<=100;j++){
for(h=0;h<=100;h++){
if (A[i]==B[j]) {
connctive = connctive +1;}
if (A[i]==C[h]){
connctive = connctive +1;}
if (B[j]==C[h]){
connctive = connctive +1;
} else
{ if (A[i]!=B[j]!=C[h])
cout << "non of graphs is connective" <<endl;}}}
}
cout << connctive <<"connctive " <<endl;
return 0;
}
i'm working to solve this program i want to Compare 3 arrays and print out the Union numbers with name connective or not Can someone please explain to me why the output from the following code is saying that arrays are not connective all the time :( ?? even when i entered different numbers
As chris said, your loops
for(i=0;i<=100;i++ )
Should almost definitely be
for(i=0;i<100;i++ )
It may not completely solve your issue, but it's a start.
I will make no assumption about what problem your code is supposed to cope with. But there is at least three problems in your code.
First, you better check your array bounds because your have a buffer overflow which always leads to troubles. In C/C++, array are zero-indexed, therefore when you declare A[100] you have 100 elements ranging from A[0] to A[99]. Your three loops are wrongs, stop condition must be i<100 instead of i<=100.
Second, your last check is not what you think it is. You are not comparing three integers together. You are comparing a mix of integer and boolean promoted to integer, since the first == will return a boolean and it will be promoted to resolve the next ==. You must write (A[i]!=B[j])&&(B[j]!=C[h]) instead.
Third, you are not filling all vectors but only the first element of each. You must check the content of your data before you process it.
You are making some very basic mistakes like not even taking the iput correctly ,not checking runtime errors like the one by accessing an array element out of bounds.
I suggest that you should debug your code properly before you post here.
As far as the answer to your code is concerned, this is gonna be the algo..
*******************LOGIC*************************
First of all sort all the three arrays.
Secondly pick up the first element of any array (say C), and compare it the second one (say B) until you find a number in B which is greater than or equal to C[0].If they are equal start finding the number in A (if you find any such number it is connctive) else take the next element of C.
******************LOGIC ENDS*****************
******************CODE***************************
#include <iostream>
using namespace std;
void sort_array(int * X);
int main()
{
int A[5] , B[5] , C[5];
int i=0,j,h;
cout << "THE PROGRAM TAKES 3 GRAGHS ONLY\n";
cout << "\n enter the Graph 1 \n";
for (i=0 ; i<5 ; i++)
cin >> A[i];
cout << "\n enter the Graph 2 \n";
for (i=0 ; i<5 ; i++)
cin >> B[i];
cout << "\n enter the Graph 1 \n";
for (i=0 ; i<5 ; i++)
cin >> C[i];
sort_array(A);
sort_array(B);
sort_array(C);
i=0;
for (j=0;j<5;j++)
{
for(h=0;h<5;h++)
{
if (C[j]<=B[h])
{
break;
}
}
if (C[j]==B[h])
{
for(; i<5 ;i++)
{
if(A[i]>=C[j])
{
break;
}
}
if(A[i]==C[j])
{
cout<<"\n "<<A[i]<<" connective\n";
}
}
}
return 0;
}
void sort_array(int * X)
{
for( int i=0; i<4 ; i++)
{
for( int j=0; j<5-i ; j++)
{
if(X[i]>X[i+1])
{
swap(X[i],X[i+1]);
}
}
}
}
******************************CODE ENDS**************************************