Finding the Largest and Smallest Integers In A Set- Basic [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm kind of on the right track, however my output is not quite right. The program asks for the number of integers you have and then it asks for those numbers. For an example is says please enter the number of integers, you can put 3. And then you enter 3 numbers. I can't use arrays because I am a beginner student and we have not learned those yet. Using count is the only way that allows me to input integers. What do I need to add to my program? Again I am a general computer science student so I can't use anything advanced. I used include iostream, namespace int main and all that you just cant see it
int data;
int num;
int count=0;
int max=0;
do
{
cout<<"Enter the number of intergers"<<endl;
cin>>num;
while (count<num)
{
cout<<"Please enter a number"<<endl;
cin>>data;
count++;
if (data<min)
{
min=data;
}
if (data>max)
{
max=data;
}
}
cout<<"Smallest integer:"<<min<<endl;
cout<<"Largest integer:"<<max<<endl;
cout<<"Would you like to continue?"<<endl;
cin>>ans;
} while ((ans=='y')||(ans=='Y'));
return 0;
}

Try out something like this:
int data;
int num;
int max=0, min = 1000000;
cout<<"Enter the number of intergers"<<endl;
cin>>num;
for (int count = 0; count < num; ++count)
{
cout<<"Please enter number #" << count <<endl;
cin>>data;
if (data<min)
{
min = data;
}
if (data>max)
{
max = data;
}
}
cout<<"The smallest number:"<<min<<endl;
cout<<"The largest number:"<<max<<endl;

You can use two temporal variables to store the smallest-so-far and biggest-so-far numbers. On each loop iteration, you check if need to update them.
I don't want to put any code... it is your assignment ;-)

The answer above is the way to do this correct but to be more explicit you may have to update the smallest or the biggest number. For example; give the computer 5 then 4.. Your program prints 4 as a biggest number. However if you update "max" by using any other temporary int, it will give the right number .

First of all, your condition is wrong, it should be while( count < num), since count starts at 0. Now, if you want the quick n' dirty way, simply initialize two variables, min and max to the minimum and maximum values an int can hold. Check the input via comparisons for each variable and update as needed.

Related

Printing a binary tree whose elements are stored in a array

I want to print a complete binary tree with n elements where 1<=n<=m & m is a natural number and these elements are stored in an array.
My approach :
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int a=0;a<n;a++)cin>>arr[a];
/*Printing the sorted tree*/
int l=1,cnt=1;
while(l<=n)
{
cnt++;
l=l+pow(2,cnt);
}
int val=0,cn=1,loli;
while(1)
{
for(int p=cnt;p>=1;p--) cout<<" ";
for(int ll=1,loli=1;ll<=pow(2,val);ll++){
if(cn==n)return 0;
if(loli!=2){
cout<<arr[cn++]<<" ";
loli++;
}
else{
cout<<arr[cn++];
loli=1;
}
}
val++;
cnt=cnt-2;
if(cnt==0)cnt=1;
cout<<endl;
}
return 0;
}
I found some related answers there . But the discussion is using link list may be (nodes) where I do not want to use nodes for taking elements of tree. I am taking them from an array.
It's difficult to follow your code because:
It's not clear how you're approaching this problem
You don't break into functions (which you should)
You use cryptic names for variables
You have a strange dependence on an entirely artificial parameter, m. Why do we care about m at all?
If you follow better practices solving this problem - starting with describing your algorithm clearly (to yourself if to no-one else) - you will probably get it right.

Displaying Hjighest and Lowest number in C++

I am trying it this way. seems to be more simplified. just trying to figure out now how to include the month names and to get the program to output the name of the rainiest month not the number the user inputs.
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int a[12];
int x;
for (x=0; x<12; x++)
{
cout << "Insert days of rainfall for month "<<x+1<<endl;
cin >>a[x];
}
int max;
int min;
max = a[0];
min = a[0];
int e=0;
while (e<12)
{
if (a[e]>max)
{
max = a[e];
}
else if (a[e]<min)
{
min = a[e];
}
e++;
cout<<"The rainiest month was " <<max<<endl;
cout<<"The least rainy month was " <<min<<endl;
getch ();
return 0;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Your average calculation is off a little, you have to take into consideration the order of operations when it comes to math. Multiplication and division are always done first, then addition and subtraction. What you end up with is that ONLY dec is divided by 12, and THEN you add all the other days to it. To fix this, you need to wrap the additions of all of the months in parentheses to force the addition to happen first, then do the divide after. In this case, you can just use your year variable since it is already all of the months added together and divide it by 12.
As far as your question goes, you want to show the highest and lowest values input, but I don't see any attempt to solve this in your code. I feel less inclined to just write the code for you so I will just give a brief explanation of what you need to do instead. Look at the value for each month, each time you look at the next month, you compare it with the current highest and current lowest values you remember. When the new month has a new higher, or new lower, value you replace the value you remember. Once you cycle through every month you will end up with your highest and lowest values.
The fastest and the most clean way is to use a container such as an std::vector. Then sort it using std::sort.
// Our container
std::vector<double> userInput;
// Populate the vector. Please don't cin into a double!
// Sort it.
std::sort (userInput.begin(), userInput.end());
// The highest value will be the last value in the vector
// whilst the lowest value will be the first one

Prime divisors of a number in C++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
This is my first question on Stackoverflow, so please excuse me if I'm doing something wrong. :) Can you help me with this code? Thank you! :)
#include <iostream>
using namespace std;
1)
int divisor(int a) // function that checks the divisors of a number *)
{
int i=1; // counter
while(i<=a) // while the counter is less than the number given
{
int i;
if(primes(i)) // here i get the error "primes was not declared in this scope
{
if(a%i==0) // if the remainder of the operation is 0, the number is a divisor
{
cout<<"The divisors of the number are: "<<i<<endl; // prints the divisors
++i; // counter is incremented
}
}
else // else it is not, and the counter i is incremented
{
++i;
}
}
}
2)
int primes(int number) // checks if a number is prime
{
int i;
for(i=2;i<number;i++) // for loop until the counter i is less than a number
{
if(number%i==0) // if the remainder of the operation is 0, the number is not prime
{
break;
}
else //else the number is prime
cout<<number;
break;
}
}
}
3)
int main()
{
int n,i;
cout<<"Give the number: ";
cin>>n;
for(i=2;i<n;i++)
{
divisor(n);
}
}
There are several issues:
1) You need to forward-declare primes() before divisors():
int primes(int number);
2) Your primes() function fails to return a value.
3) Not all code paths in divisor() increment i.
I am sure there are more problems, but this should get you started...
Assuming that the order you give above is the same order as you use in the file, the problem is that your divisor function comes first and makes use of the primes function which is declared later. The easiest (and I guess also most common) solution is to use "foward-delcaration". This means that at the top of your file you state:
int divisor(int);
int primes(int);
In addition you are forgetting to have primes() return a value. (As this question is tagged as
C++, you might even consider having it return a bool instead of an int).
Also in primes the else clause will now cause a break, but I don't think that's altogether wise. Numbers like 9 will end up in that clause when dividing by 2, but the fact that it is not divisible by 2, doesn't make it prime...
There are also other "smart tricks" when it comes to finding primes, but perhaps that is out of the scope of this question.

Adding a struct int and a normal int. c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'd like to add an int from a struct with a regular int in c++. Is there an easy way to do it? Ive searched pretty much everywhere but theres nothing on adding either two struct ints while reading in data from a binary file or adding a regular int and a struct int together.
This is the simple version of what I currently have.
struct Add{
int k;
};
int total;
Add a;
//read in first set of number from binary file
total += a.k;
//add up to total, then read in second set of number from binary file.
The problem is, when I output total, it only gives me the last number I tried adding int k to it and not the total.
My actual code as requested.
struct TaskInit{
int weight;
};
TaskInit t;
int totalWeight;
for (int i = 1; i <= noOfRecords; ++i)
{
afile.seekg ((i - 1) * sizeof (TaskInit), ios::beg);
afile.read (reinterpret_cast <char *>(&t), sizeof (t));
totalWeight += t.weight;
}
cout << totalWeight;
struct Add{
int k;
};
int total = 0; // no indeterminate values. always init locals!
Add a;
// open your file here.
while (inFile >> a.k) {
//read in first set of number from binary file
//add up to total, then read in second set of number from binary file.
total += a.k;
}

arrays and index [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
How can I enter numbers into an array such that duplicate entries are ignored?
For example, if I put 6 and then 3 into the array, attempting to then insert 6 into the the array should cause 6 to be rejected (since it is already in the array).
#include <iostream>
using namespace std;
int main()
{
int x,y;
int number;
int arr[5];
for (x=0; x<5; )
{
cout<<"enter a number:"<<endl;
cin>>number;
bool replace = True;
for (y=0; y<x; y++)
{
if (number != arr[y])
{
cout << "try next time" << endl;
replace = False;
break;
}
}
if (replace)
{
arr[x] = number;
x++;
}
}
return 0;
}
std::set<int> would do what you want. This is not indexable, though.
You could use Boost.MultiIndex to give you random access and enforce uniqueness on the same underlying list of values.
btw - asking directly for code is not recommended practice.
you have too many x++'s and you don't preset arr (maybe more style than error)
how do you know it's not working?
(put some debug code inside of if (number == arr[y]) and if (replace)
What you really want is a set. Sets cannot contain duplicate elements.
Here is a reference to the set in C++.
Just use the set as a container for your numbers. When you try to add a duplicate, it will be automatically rejected.
You don't want an array but a datastructure called Hashtable for that;
Alternatively, you might want to look up a datastructure called associative array.
You shouldn't use arrays for this. You should use, for example, std::set. Or, if you need to have an array as your data structure, you could encapsulate the array (e.g. realized through std::vector) in a class and define specific functions to access the array elements. Additionally, you could hold a std::set to provide a fast check for existing elements.
Should be :
int arr[5] = {0,0,0,0,0};
Remove the x++ from the following line:
for (x=0;x<5;x++)
Then:
bool replace=true;
for (y=0;y<x;y++)
{
if (number == arr[y])
{
replace=false;
break;
}
}
if (replace)
{
arr[x]=number;
x++;
}
Finally, remove the :
else if(number == arr[x])
{
arr[x]=number;
cout << "try next time"<<endl;
}
You can insert :
cout << "try next time"<<endl;
before the
replace=false;
Take out the x++ in the for loop, That way you will only increment that count when you enter a new number.
Also, if you want to only run the loop five times, your outer for loop should be only to x<5.
All in all your outer loop should read:
for (x=0;x<5;)
Take a closer look at where you increment x.
It looks like you want to read in a sequence of numbers eliminating any duplicates.
It also appears that the maximum number of unique numbers is 5.
int n = 0; /* The number of unique numbers read in so far */
for {;;}
cout << "enter nmber" << endl;
cin >> number;
for (x=0; x < n; ++x) {
if (number == arr[x]) goto L1; /* I love messing with peoples head by using this goto */
}
arr[n] = number;
++n;
if (n == 5) break;
L1:
continue;
}