So I am trying to get my even numbers to appear and tell me the result of the user input. Not sure why my function is an error in my main when I tried to just have it output in my even function won't print. Unsure why? also curious should I lock and make my array constant? It isn't changing but might feel like I have to make it constant and lock it in case if I have to change something to check for an even number. Plus I am a beginner and barely learning about arrays.
#include <iostream>
#include <string>
using namespace std;
// putting our voids first to declare be declare and run first
void fillUp(int num[], int size)
{
//user input
cout<<"Enter "<<size<<" and then press the ENTER/RETRUN: ";
for(int i = 0; i < size; i++)
{
cin>> num[i];
}
}
//obtaining user input and totaling them up
int total(int num[], int size)
{
int total = 0;
for(int i = 0; i < size;i++)
{
total += num[i];
}
return total;
}
int EvenElements(int num[], int size, int& evenCounter)
{
for(int i = 0; i<size;i++)
{
if(num[i] % 2 == 0)
{
evenCounter++;
}
}
return(evenCounter);
}
//display the array in a row
void display(int num[], int size)
{
for(int i = 0; i<size;i++)
{
cout<<num[i]<<" ";
}
}
//main function to display the results of the user input
int main()
{
int numOne[4], numTwo[5], numThree[6], evenCounter;
fillUp(numOne, 4);
fillUp(numTwo, 5);
fillUp(numThree, 6);
cout<<"The numbers in the array are: ";
display(numOne, 4);
cout<<" and the total of these numbers is "<<total(numOne, 4)
<<endl;
cout<<"The numbers in the array are: ";
display(numTwo, 5);
cout<<" and the total of these numbers is "<<total(numTwo, 5)
<<endl;
cout<<"The numbers in the array are: ";
display(numThree, 6);
cout<<" and the total of these numbers is "<<total(numThree, 6)
<<endl;
cout<<"This is how many evens were in the array: ";
EvenElements(evenCounter);
}
Your EvenElements() requires three arguments and you're passing only one and therefore, your code as it is will not compile. Try the following (read the comments for the last 3 lines):
#include <iostream>
#include <string>
using namespace std;
// putting our voids first to declare be declare and run first
void fillUp(int num[], int size)
{
//user input
cout<<"Enter "<<size<<" and then press the ENTER/RETRUN: ";
for(int i = 0; i < size; i++)
{
cin>> num[i];
}
}
//obtaining user input and totaling them up
int total(int num[], int size)
{
int total = 0;
for(int i = 0; i < size;i++)
{
total += num[i];
}
return total;
}
int EvenElements(int num[], int size, int& evenCounter)
{
for(int i = 0; i<size;i++)
{
if(num[i] % 2 == 0)
{
evenCounter++;
}
}
return(evenCounter);
}
//display the array in a row
void display(int num[], int size)
{
for(int i = 0; i<size;i++)
{
cout<<num[i]<<" ";
}
}
//main function to display the results of the user input
int main()
{
int numOne[4], numTwo[5], numThree[6], evenCounter;
fillUp(numOne, 4);
fillUp(numTwo, 5);
fillUp(numThree, 6);
cout<<"The numbers in the array are: ";
display(numOne, 4);
cout<<" and the total of these numbers is "<<total(numOne, 4)
<<endl;
cout<<"The numbers in the array are: ";
display(numTwo, 5);
cout<<" and the total of these numbers is "<<total(numTwo, 5)
<<endl;
cout<<"The numbers in the array are: ";
display(numThree, 6);
cout<<" and the total of these numbers is "<<total(numThree, 6)
<<endl;
cout<<"This is how many evens were in the array: ";
// Make sure you initialise evenCounter
evenCounter = 0;
// Call EventElement with the right parameters
EvenElements(numThree, 6, evenCounter);
// Display the result
cout<<evenCounter<<endl;
}
Note: Consider using macros for your sizes
#define SIZE_1 4
#define SIZE_2 5
#define SIZE_3 6
and then replace the hard-coded numbers with the appropriate sizes.
Related
I tried changing a lot of integers and stuff but it didn't work and it gives me a random number like 53289432 even tho lets say i put in 3:5,1,2 it should output 3 since 5-2 is 3.
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int x[n];
int mn;
int mx;
for(int i=1;i<n;i++)
{
cin>>x[i];
for(int j=1;j<n;j++)
{
if(x[i]>x[j]);
}
{
x[i]=mn;
}
}
for(int i=1;i<n;i++)
{
for(int j=1;j<n;j++)
{
if(x[i]<x[j]);
}
{
x[i]=mx;
}
}
cout<<mx-mn;
}
You don't need an array:
int smallest = 0;
int largest = 0;
std::cout << "Enter quantity: ";
int quantity;
std::cin >> quantity;
if (quantity < 1)
{
std::cerr << "Invalid quantity.\n";
return 1;
}
std::cout << "Enter number: ";
std::cin >> smallest;
largest = smallest;
for (int i = 1; i < quantity; ++i)
{
std::cout << "Enter number: ";
int number;
std::cin >> number;
if (number < smallest) smallest = number;
if (number > largest) largest = number;
}
std::cout << "maximum from minimum: " << (smallest - largest) << "\n";
std::cout << "minimum from maximum: " << (largest - smallest) << "\n";
The above code uses a running minimum/maximum, so no arrays are needed.
No need for variable length arrays or having to figure out the array capacity at compile time.
Your code carries several holes,
Firstly,
for(int i=1;i<n;i++)
{
cin>>x[i];
This won't take n integers, it will only take (n-1) integers as input. You need to initialise i=0, for n integers;
Secondly,
for(int i=1;i<n;i++)
{
cin>>x[i];
for(int j=1;j<n;j++)
{
if(x[i]>x[j]); //This will compare with garbage when i=1 and j>1
}
{
x[i]=mn;
}
}
Your comparison, will only be valid for first iteration of i=1 and j=1, after j>1, it will pick garbage value, since, you haven't taken any input yet.
It is suggested, to first take all the inputs, then do the comparison, or other operations.
Here is my solution
I think this is what you are trying to do!
#include <iostream>
#include <climits>
using namespace std;
int main()
{
int n;
cin>>n;
int x[n];
int mn;
int mx;
//First take the inputs in array x
for(int i=0;i<n;i++)
{
cin>>x[i];
}
//Find maximum and store it in mx
mx = INT_MIN; //This stores minimum in mx variable (climits)
for(int j=0;j<n;j++)
{
if(mx<x[j])
mx=x[j];
}
//Find minimum and store it in mn
mn = INT_MAX; //This stores maximum in mn variable (climits)
for(int j=0;j<n;j++)
{
if(mn>x[j])
mn=x[j];
}
int ans = mx - mn;
cout<<ans<<endl;
}
There is a better solution where you don't use extra space(array), and by using only 2 variables, you can find the difference. But I would recommend you to first understand this concept, and take a look, how array works, before moving towards any optimised solution.
I have written following code which allows user to input an array and give out maximum and minimum value in that array
when i input length of array value = 4 and elements of array as:- 32,152,38 it give output as
max = 1973314801 and min = 24(unexpected values)
for following code:-
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"input length of array = ";
cin>>n;
int array[n];
for(int i=0; i<n;i++)
{
int a;
cout<<"input element "<<i+1<<" = ";
cin>>a;
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
but when i define value of array in code it give expected output (min=3 and max=12)
code(code in which value of array is already defined):-
#include<iostream>
using namespace std;
int main()
{
int array[4]={3,6,9,12};
int max=array[0];
int min=array[0];
for(int i=0; i<4;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
what can be the problem here?
According to the C++ Standard the size of a C++ array must be compile time constant. So your first code example is not correct. That is you cannot take the size of the array from the user as input. You have to explicitly specify the size of the array as you did in your 2nd example.
You can use std::vector for this purpose instead.
You are storing input data in variable a instead of array array and you can't assign array size like that. You have to specify the size as constant before using it.
#include<iostream>
using namespace std;
int main()
{
const int n = 4;
/*cout<<"input length of array = ";
cin>>n;*/
int array[n];
for(int i=0; i<n;i++)
{
cout<<"input element "<<i+1<<" = ";
cin>>array[i];
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
}
But if you still want to take size as user input then you have to create that array in heap memory
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"input length of array = ";
cin>>n;
int* array = new int[n]; //array in heap
for(int i=0; i<n;i++)
{
cout<<"input element "<<i+1<<" = ";
cin>>array[i];
}
int max=array[0];
int min=array[0];
for(int i=0; i<n;i++)
{
if(array[i]>max)
{
max=array[i];
}
if(array[i]<min)
{
min=array[i];
}
}
cout<<"max = "<<max<<endl;
cout<<"min = "<<min;
delete [] array;
}
You don't need an array; use a running min and max calculation:
int minimum;
int maximum;
cin >> minimum;
maximum = minimum;
int number;
while (cin >> number)
{
if (number > maximum) maximum = number;
if (number < minimum) minimum = number;
}
cout << "Maximum: " << maximum
<< ", Minimum: " << minimum
<< "\n";
There is no need to store the numbers, only to compare the number to determine the maximum and minimum.
The requirements are still met, because the program is entering an array or bunch, of numbers.
One nice feature of the running min and max, is there is no limit to the quantity of numbers that can be input. The only limit is the range of values that an int can hold.
for example, I have to take input in the format:
2 // no of test cases
7 // n->size of an array
9 7 5 9 2 20 3 //n array elements
5 // second test case array size
4 5 8 96 6 // second test case array elements
I don't know what to write in the main function.
void sort(int arr[],int n)
{
for(int i=1;i<n;i++)
{
int current =arr[i];
int j;
for(j=i-1;j>=0;j--)
{
if(current<arr[j])
{
arr[j+1]=arr[j];
}
else
{
break;
}
}
arr[j+1]=current;
}
}
int main(){
// what should I write in the main func to test my problem for t no of times
// I have to take all inputs first then print the sorted arrays given by the user
// separated by space and new line for the next sorted array
}
I think this what you want.
const int N = 10;
int main(){
int t, n, arr[N];
cin >>t;
for(int T;T<t;++T){
cin >>n;
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Make sure to put the value if N is the maximum possible size of the array. Or you can declare the array as a dynamic array with the entered n (or use one of the STL like vector)
for example:
int main(){
int t, n;
cin >>t;
for(int T;T<t;++T){
cin >>n;
int * arr = new int [n];
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
Or by using Vector:
#include<vector>
using namespace std;
//your sort func here, but make sure to change it to have a vector instead of an array
int main(){
int t, n;
vector<int>arr;
cin >>t;
for(int T;T<t;++T){
arr.clear();
cin >>n;
arr.resize(n);
for(int i=0;i<n;++i){
cin>>arr[i];
}
sort(arr, n);
for(int i=0;i<n;++i){
cout <<arr[i]<<" ";
}
cout <<endl;
}
PS: I would recommend to see websites like codeforces, Hackerrank and others to practice on competitive programming question which contains a lot of question that will help (If you're interested)
int main()
{
int t; // number of test cases
std::cin >> t;
while (t--) // repeat t times
{
// what you had before
}
}
to test you can
define an input and a desired output, i.e an array "unsorted" and how it SHOULD look like after sorted
define a method that sorts input "a" and allows you to verify that by eather returning the sorted array or modifying the reference given as parameter.
defined a compare method that takes x1 and x2 as parameter and returns a bool indicating if the operation failed or no. x1 can be the desired sorted array and x2 the array returned from step1
loop in a for with DIFFERENT unsorted arrays and theis according sorted values...
int main()
{
int t;
cin >> t;
while (t--)
{
int size;
cin >> size;
int *arr = new int[size];
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
sort(arr, size);
for (int i = 0; i < size; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
cout << endl;
}
return 0;
}
I think this will work
this is a code example for what I mean
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int numOfTest = 0;
std::vector<int>vec;
std::cin>>numOfTest ;
for(int j=; j<=numOfTest; ++j) // loop for num of tests
{
int n=0;
for(int i=0; i<n; ++i) // loop for num of veriabels in one test
{
int var=0;
std::cin >> var;
vec.push_back(var);
}
// option one
int* arr = new int[n] ;
std::copy(vec.begin(),vec.end(),arr);
sort(arr, n);
//option two
sort(&vec[0], n);
//option three
sort(vec.data(), n);
for(int f=0; j<=n ++j)
{
std::cout << arr[f] << " "; // print the sorted array;
}
delete [] arr;
}
return 0;
}
if your choosing option two or three you can using range base loop instead of for loop:
it will look like this:
for(auto& e: vec)
{
std::cout << e << " ";
}
im trying to set up a lottery game that asks for input from the user 3 times and compares this to numbers drawn by the random array. if any of these user numbers match a number in the array, the program should print out the numbers that matched.
ive tried to use while loops in my main function to control the flow but im still having issues with compilation
#include<iostream>
#include <ctime>
#include "array.h"
using std::cout; using std::cin; using std::endl;
const int sizeofArray = 20;
void assign(int wins[], int sizeofArray);
void draw(int sizeofArray, int wins[]);
bool check(int num1, int wins[], int sizeofArray);
void entry(int& userNum);
void printOut(int wins[], int num);
int main() {
srand(time(nullptr));
int user[sizeofArray];
cout << "Good luck with this weeks lotto drawing!" << endl;
int wins[sizeofArray];
assign(wins, sizeofArray);
draw(sizeofArray, wins);
int userInput;
entry(userInput);
bool win = check(userInput, wins, sizeofArray);
if (win)
cout << "you have won!" << endl;
printOut(wins, sizeofArray);
}
void assign(int wins[], int sizeofArray) {
for (int i = 0; i < sizeofArray; ++i)
wins[i] = 0;
}
void draw(int sizeofArray, int wins[]) {
int number = 0;
while (number < sizeofArray) {
int number = rand() % 100 + 1;
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
number++;
}
}
}
bool check(int num1, int wins[], int sizeofArray) {
for (int j = 0; j < sizeofArray; j++) {
if (wins[j] == num1)
return true;
}
return false;
}
void entry(int& userNum) {
int j;
cout << "Enter your lottery number guess: ";
cin >> userNum;
cout << "Your number was " << userNum << endl;
}
void printOut(int wins[], int num) {
cout << "Winning numbers in lottery are" << endl;
for (int j = 0; j < num; ++j) {
cout << wins[j] << " ";
}
}
i
Your draw method is going to loop infinitely since you declared the condition variable twice which causes the ++ operator to be applied on the wrong variable
void draw(int sizeofArray, int wins[]) {
int number = 0; // <--- HERE
while (number < sizeofArray) {
int number = rand() % 100 + 1; // <--- AND HERE
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
number++; //This will increase the inner variable number not the outer one
}
}
}
to fix it just change the name of your variable
void draw(int sizeofArray, int wins[]) {
int counter = 0; <---
while (counter < sizeofArray) { <---
int number = rand() % 100 + 1;
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
counter++; <---
}
}
}
Let's take a look at draw():
void draw(int sizeofArray, int wins[]) {
int number = 0; //First variable of name number
while (number < sizeofArray) {
//new variable with name number is introduced, it shadows the first one
int number = rand() % 100 + 1; //<-----------------------+
if (!check(number, wins, sizeofArray)) { // |
wins[number] = number; // |
number++; //Here you actually increase this variable-+
}
}
}
So called shadowing occurs here and the outer int number is never modified inside the loop. Just rename one of them and you should be fine.
If you want to read more about this, take a look here.
[![enter image description here][1]][1]
This is what I have tried out but whenever I run the program it crashes and says error, although it compiles correctly. It asks me to enter department number but after that doesn't show me any output
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int STDTs = 25;
const int DEPTs = 7;
void initializeGPAs(double gpa[][DEPTs])
{
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
gpa[i][j]=(10+rand()%31)/10;
}
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
sum+=gpa[j][i];
deptAvg[i]=double(sum/STDTs);
}
}
int StdsOnProbationCount(double gpa[][DEPTs])
{
int ctr=0;
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
if(gpa[i][j]<2)
ctr++;
return ctr;
}
int StdsOnProbationCountinDeptX(double gpa[][DEPTs], int x)
{
int ctr=0;
for(int i=0;i<STDTs;i++)
if(gpa[i][x-1]<2)
ctr++;
return ctr;
}
void showReport(double gpa[][DEPTs],string dept_names[], double deptAvg[], int ctr1, int ctr2, int x)
{
cout<<endl;
for(int i=0;i<DEPTs;i++)
{
cout<<'\t'<<dept_names[i]<<" ";
}
cout<<endl;
for(int i=0;i<STDTs;i++)
{
cout<<"Student "<<i+1<<": ";
for(int j=0;j<DEPTs;j++)
cout<<gpa[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(int t=0;t<DEPTs;t++)
cout<<"Dept Avg.: "<<deptAvg[t]<<" ";
cout<<endl<<endl;
cout<<"Total number of students who are on probation is: "<<ctr1;
cout<<endl;
cout<<"Number of students who are on probation in "<<dept_names[x-1]<<" Dept. is "<<ctr2;
}
int main()
{
double gpa[STDTs][DEPTs];
int ctr1, ctr2, x;
double deptAvg[DEPTs];
string dept_names[DEPTs]={"MATH","STAT","COMP","PHYS","CHEM","BIOL","GEOL"};
initializeGPAs(gpa);
computeDeptAvg(gpa, deptAvg);
ctr1 = StdsOnProbationCount(gpa);
cout<<"Enter Department Number [1 to 7]: ";
cin >> x;
ctr2 = StdsOnProbationCountinDeptX(gpa, x);
showReport(gpa, dept_names, deptAvg, ctr1, ctr2, x);
return 0;
}
edit: I figured everything out but my problem seems to be in this function because it displays zeroes for all the department averages
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
{
sum+=gpa[j][i];
deptAvg[j]=double(sum/STDTs*1.0);
}
}
}
I'll consider only your computeDeptAvg function.
Your sum variable should be of type double, declaring it as an int makes all of your calculations (specifically the sum+=gpa[j][i] and sum/STDTs, which is an integer division) prone to truncating errors.
You nested the two loops in the wrong order: You should sum the scores of all the students in a particular department in order to calculate the average of that department. Besides, deptAvg[j] is overwritten every time the outer loop is executed.
You have declared gpa in main as a double gpa[STDTs][DEPTs];, but in your loops you are using gpa[j][i], where j is in the range [0, DEPTs) and i in [0, STDTs).
A modified version could be:
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int d = 0; d < DEPTs; d++)
{
double sum = 0.0;
for(int s = 0; s < STDTs; s++)
{
sum += gpa[s][d];
}
deptAvg[d] = sum / STDTs;
}
}