Compare 3 arrays c++ [like graph] - c++

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**************************************

Related

C++ code - Error message when floating point is entered [duplicate]

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.).

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.).

Creating number pattern (triangle numbers) in c++ with minimum loops

We were asked to make a triangular no. pattern in c++ with min. loops. The triangle pattern is as follows:
____1_____
___2__3____
__4__5__6__
7__8__9__10
My code:
#include <iostream>
using namespace std;
int main() {
int n=0, r=0, i=0;
cout << "No. of rows: ";
cin >> r;
for( n=1; n<=r; n++) {
for( i=1; i<=r-n; i++) {
cout << " ";
}
for( i=(n*(n-1)/2)+1; i<=(n*(n+1)/2); i++ ) {
if( i<10 )
cout << " " << i << " ";
else
cout << i << " ";
}
cout << "\n";
}
return 0;
}
OUTPUT
QUESTIONS
1) Is it wise to use pattern generating formulas? for eg, for putting value of i in last loop, i used the formula for the pattern 1,2,4,7 .. as (n*(n-1)/2)+1. Is it more efficient this way? what could be an iterative approach? and what could be a possible recursive one?
2) Is it possible to reduce no. of loops? is it better to reduce variables or reduce loops?
THANK YOU!
Its a simple incremental number pyramid that dose not require any special formula. Formula's increases the complexity of the program because more calculations are involved. Try to keep the code simple.
Simplest way to do this is :
int main() {
int num,i=1;
cout<<"Enter Number of Rows";
cin>>num;
for(int r=1; r<=num; r++)
{
for(int space=1; space<=num-r; space++){
cout<<" ";
}
for(int c=1; c<=r; c++,i++){
cout<<" "<<i;
}
cout<<"\n";
}
return 0;
}
This is a completely personal opinion, but I think that using formulae is really not going to affect the efficiency, since you are anyways printing the elements one at a time. So the total time is dependent on your length of input which is r(r+1)/2.
I wrote this and it seems to work good too, though the logic in this code is to just keep printing the elements in order and breaking the line when required. It uses only one inner loop to print the spaces at the beginning of each line. Here is the Ideone link.
int r;
cin>>r; //number of rows
int spaces = r-1, rowcount = 1;
int curcount = 0;
for(int i=1; i<=(r*(r+1))>>1;i++) {
if(curcount == 0) {
for(int j=0; j<spaces; j++)
cout<<" ";
spaces--;
}
cout<<(i<10?" ":"")<<i<<" ";
if(++curcount == rowcount) {
rowcount++;
curcount=0;
cout<<endl;
}
}

Why doesn't my array store any input values?

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];}}

I'm getting a weird error for a program that seems like it should "just work."

I present to you all a program I'm working on for my college programming course. I still have a little ways to go before it completely meets my assignment's requirements, but I've gotten a basic draft of the program error-free (supposedly) and it appears to run… but then it suddenly kicks me into Xcode's debugger and gives me:
Thread 1: EXC_BAD_ACCESS(code=2, address=0x7fff95c1e5f5)
Here's the command line output, up until it kicks me out:
-----------------------
Quarterly_sales_taxator
-----------------------
How many company divisions will we be dealing with? 2
Am I correct in assuming that there are 4 sales quarters? yes
Please enter the sales Company Division #1 brought in for Sales Quarter #1 20
(lldb)
Here's my code:
//
// quarterly_sales_taxator.cpp
// Ch. 7 program #7
//
// Created by John Doe on 11/27/12.
//
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <cctype>
using namespace std;
void read_company_divisions_and_sales_quarters(double **, int, int);
//void write_company_divisions_and_sales_quarters_to_array(double **, int, int); // This will be used later on to read data from a file.
void display_quarterly_sales_array(double **, int, int);
string temp; // A global temporary placeholder variable; I use this several times.
int main()
{
int COMPANY_DIVISIONS,
SALES_QUARTERS = 4;
double **quarterly_sales_form;
cout << "\n\n-----------------------\nQuarterly_sales_taxator\n-----------------------\n\n";
cout << "\nHow many company divisions will we be dealing with? ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
while (COMPANY_DIVISIONS < 1 || isdigit(COMPANY_DIVISIONS == false))
{
cout << "\n\n------"
<< "\nError:"
<< "\n------"
<< "\n\nYou have entered an invalid choice."
<< "\nPlease type a number greater than zero. ";
getline(cin, temp);
stringstream(temp)>>COMPANY_DIVISIONS;
}
cout << "\n\nAm I correct in assuming that there are 4 sales quarters? ";
getline(cin, temp);
// Convert to uppercase.
for (int count = 0; count < temp.length(); count ++)
{
temp[count] = toupper(temp[count]);
}
if (temp == "NO" || temp == "NOPE" || temp == "INCORRECT" || temp == "YOU ARE NOT" || temp == "YOU ARE INCORRECT" || temp == "NEGATIVE" || temp == "NEGATORY")
{
cout << "\nOk, then how many sales quarters are we dealing with? ";
getline(cin, temp);
stringstream(temp)>>SALES_QUARTERS;
}
cout << endl << endl;
// This sets up the 2d array.
quarterly_sales_form = new double *[COMPANY_DIVISIONS];
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
read_company_divisions_and_sales_quarters(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// write_company_divisions_and_sales_quarters_to_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS); // I'll add this feature later.
cout << "\n\nHere's what you entered:\n\n";
display_quarterly_sales_array(quarterly_sales_form, COMPANY_DIVISIONS, SALES_QUARTERS);
// Since we used a series of pointers, we need to free the allocated space back up.
for (int count = 0; count < COMPANY_DIVISIONS; count ++)
{ delete[] quarterly_sales_form[COMPANY_DIVISIONS]; }
delete[] quarterly_sales_form;
return 0;
}
/*############################################
# read_company_divisions_and_sales_quarters #
############################################*/
void read_company_divisions_and_sales_quarters(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < QUARTERS; count++)
{
for (int index = 0; index < DIVISIONS; index++)
{
cout << "\nPlease enter the sales Company Division #" << count+1 << " brought in for Sales Quarter #" << index+1 << " ";
getline(cin, temp);
stringstream(temp) >> array[count][index];
}
}
}
/*################################
# display_quarterly_sales_array #
#################################*/
void display_quarterly_sales_array(double **array, int DIVISIONS, int QUARTERS)
{
for (int count = 0; count < DIVISIONS; count++)
{
cout << "\nCompany division #" << count+1 << ":\n";
for (int index = 0; index < QUARTERS; index++)
{ cout << array[count][index] << ", "; }
}
}
Can some kind soul please tell me what I'm doing wrong?
{ quarterly_sales_form[COMPANY_DIVISIONS] = new double [SALES_QUARTERS]; }
In this line, COMPANY_DIVISIONS should be count.
In addition to what Dan Hulme said, it seems this line
stringstream(temp) >> array[count][index];
should really be
std::istringstream(temp) >> std::skipws >> array[index][count];
In addition to using std::istringstream rather than std::stringstream and making sure that an lvalue is at hand, which isn't strictly needed until the type read becomes more interesting, this also reverses the indices: index runs over COMPANY_DIVISIONS and count over SALES_QUARTERS.
The real question is, of course: Who hands out assignments like this? Pointer manipulations and allocations are best left to low-level library writers. This is C++ not C: we can and should use abstractions. Getting this code exception safe is a major challenge and there is no point in teaching people how to write broken (e.g. exception unsafe) code.