Logic flow for-loop - c++

So essentially the problem is that the findLowest function isn't doing what I had planned for it to do. I know it's a logic error but I can't seem to find out why the variables aren't updating. They always default to the values they are instantiated with.
#include <stdafx.h>
#include <string>
#include <iostream>
using namespace std;
//Function prototypes
void findLowest(int regAccidents[], int arraySize, string regNames[]);
int getNumAccidents(string);
const int NUM_REGIONS = 5;
int main(){
string regionNames[NUM_REGIONS] = { "North", "South", "East", "West", "Central" };
int regionAccidents[NUM_REGIONS];
for (int i = 0; i < NUM_REGIONS; i++){//Populates the accident array
regionAccidents[i] = getNumAccidents(regionNames[i]);
if (regionAccidents[i] < 0)//checks to see if there are any accidents counts lower than 0
regionAccidents[i] = 0;
}
findLowest(regionAccidents, NUM_REGIONS, regionNames);
}
int getNumAccidents(string region){//returns the accidents for a specific region to be assigned to the regionAccidents[] array in main()
int regionAccidents = 0;
cout << "How many accidents for " << region << "? ";
cin >> regionAccidents;
return regionAccidents;
}
void findLowest(int regAccidents[], int arraySize, string regNames[]){ //used to determine what the lowest number of accidents is
int lowest = regAccidents[0]; //once that is found, update the lowRegion string of the accident location
string lowRegion = regNames[0];
for (int i = 0; i < arraySize; i++){
if (regAccidents[i] < regAccidents[i++]){
lowest = regAccidents[i];
lowRegion = regNames[i];
}
}
cout << "The region with the lowest amount of accidents is: " << lowRegion << endl;
cout << "The lowest number of accidents is: " << lowest << endl;
}

if (regAccidents[i] < regAccidents[i++]) { ...
is dead wrong, you need to compare the current index to the lowest found so far:
if (regAccidents[i] < lowest) { ...
The expression regAccidents[i] < regAccidents[i++] will never be true because you're comparing the same items in the array. It will, however, increment i when you least expect it. Not that that actually matters here since it's a secondary problem totally hidden by your primary one :-)

Yes, you have logic errors in your code. The findLowest should look like the following:
int lowest = regAccidents[0];
string lowRegion = regNames[0];
for (int i = 1; i < arraySize; i++){
//^^you have initialized lowest as regAccidents[0], so search from 1
if (regAccidents[i] < lowest ){
//^^if current is smaller than lowest, update lowest and name
lowest = regAccidents[i];
lowRegion = regNames[i];
}
}

You did say anything about what your getting as an output now.
are you overrunning the array with this line's increment?
if (regAccidents[i] < regAccidents[i++])

Related

This program takes user input and is supposed to sort it using bubbleSort but its outputting letters and numbers and I'm not sure why

The output I'm getting when I run this code after inputting any set of integers, and ending the loop with the sentinel number 999, is always 0x7ffd85bc43b0 and I can't figure out why. I think I'm missing some important code somewhere, but I'm not sure where? This program is also eventually supposed to be able to find the mean and median of the inputted numbers as well.
// HouseholdSize.cpp - This program uses a bubble sort to arrange up to 300 household sizes in
// descending order and then prints the mean and median household size.
// Input: Interactive.
// Output: Mean and median household size.
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <any>
#include <stdio.h>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int householdSizes, int size) {
for(int i = 0; i<size; i++){
}
}
void bubbleSort(int householdSizes[], int size) {
for(int i = 0; i<size; i++) {
int swaps = 0; //flag to detect any swap is there or not
for(int j = 0; j<size-i-1; j++) {
if(householdSizes[j] > householdSizes[j+1]) { //when the current item is bigger than next
swapping(householdSizes[j], householdSizes[j+1]);
swaps = true; //set swap flag
}
}
if(swaps== false)
break; // No swap in this pass, so array is sorted
}
}
int main()
{
// Declare variables.
const int SIZE = 300; // Number of household sizes
int householdSizes[SIZE]; // Array used to store 300 household sizes
int x;
int limit = SIZE;
int householdSize = 0;
int pairsToCompare;
bool switchOccurred;
int temp;
double sum = 0;
double mean = 0;
double median = 0;
// Input household size
cout << "Enter household size or 999 to quit: ";
cin >> householdSize;
// This is the work done in the fillArray() function
x = 0;
while(x < limit && householdSize != 999)
{
// Place value in array.
householdSizes[x] = householdSize;
// Calculate total of household sizes
x++; // Get ready for next input item.
cout << "Enter household size or 999 to quit: ";
cin >> householdSize;
} // End of input loop.
// Find the mean
// This is the work done in the sortArray() function
int n = sizeof(householdSizes)/sizeof(householdSizes[0]);
bubbleSort(householdSizes, n);
cout <<householdSizes;
// This is the work done in the displayArray() function
// Print the mean
// Find the median
// Print the median
return 0;
} // End of main function
An array can't be printed directly using cout << householdSizes; Since an array is convertible to a pointer, that is what is done implicitly behind the scenes. Change cout << householdSizes; to:
for(int i = 0; i < x; ++i){
std::cout << householdSizes[i] << " ";
}
P.S. Also do as #0x5453 says. He is right.

The check with the module in the loop doesn`t work

There is a task. It is necessary in a one-dimensional array of N real numbers to calculate the number of the maximum modulo element among unpaired numbers.
I wrote the code, but it does not work. I can’t understand what’s wrong with him.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
setlocale(0, "");
const int KolEl = 5;
int mas[KolEl];
int max = abs(mas[0]);
int result;
for (int i = 0; i < KolEl; i++)
{
cout << " Введите елемент[" << i << "] = ";
cin >> mas[i];
if (mas[i] % 2 == 1) {
if (abs(mas[i]) > max) {
result = i;
cout << result << endl;
}
}
}
system("pause");
}
You initialize max as:
int mas[KolEl];
int max = abs(mas[0]);
However, the values in mas[] are garbage values (read: undefined behavior). So now the value in max is also UB.
You then go on to use that value to compare to the input you take:
if (abs(mas[i]) > max) {
So the result of that comparison is undefined.
You probably meant to declare max as something like:
int max = INT_MIN;
So that the first comparison will always be true (every int except INT_MIN will be greater than it).

Locating a Segmentation Fault

I have the fallowing code. I read the guide for what a segmentation fault is, but I'm not 100% sure where its actually happening within my code. It works until I start working with the dynamic array (histogram), more specifically at the //set all initial values to be zero. Within that mess after I'm not sure. Thanks!
The instructor asked to "Use a dynamic array to store the histogram.", Which I think is my issue here.
-Solved-
thanks for the help, the error was in how I initialized the array pointer
rather than
const int hSize = 10;
IntArrayPtr histogram;
histogram = new int[hSize];
I used
const int hSize = 10;
int hValues[hSize] = { 0 };
IntArrayPtr histogram;
histogram = hValues;
Which worked as the instructor wanted.
#include <iostream>
#include <vector>
using namespace std;
typedef int* IntArrayPtr;
int main() {
vector<int>grades;
int newGrade;
cout << "Input grades between 0 and 100. Input -1 to calculate histogram: " << endl;
cin >> newGrade;
grades.push_back(newGrade);
while (newGrade > 0) {
cin >> newGrade;
while (newGrade > 100) {
cout << "less than 100 plz: ";
cin >> newGrade;
}
grades.push_back(newGrade);
}
grades.pop_back();
int size = grades.size();
cout << "Calculating histogram with " << size << " grades." << endl;
//Create dynamic array for the histogram of 10 sections.
const int hSize = 10;
IntArrayPtr histogram;
histogram = new int[hSize];
}
//Make the historgram
int stackValue = 0;
for (int j = 0; j < hSize; j++) {
//Loop through the grade vector slots
for (int i = 0; i < size; i++) {
int testValue = grades[i];
//If the grade at the index is between the stack values of the histogram add one to the value of the slot
if (testValue > stackValue && testValue < stackValue + 10) {
histogram[j]++;
}
}
//After looping through the vector jump up to the next histogram slot and corresponding stack value.
stackValue += 10;
}
//Histogram output. Only output the stacks with values
for (int i = 0; i < 10; i++) {
if (histogram[i] != 0) {
cout << "Number of " << (i + 1) * 10 << "'s: " << histogram[i];
}
}
return 0;
}
Working Code:
#include <iostream>
#include <vector>
using namespace std;
typedef int* IntArrayPtr;
int main() {
vector<int>grades;
int newGrade;
cout << "Input grades between 0 and 100. Input -1 to calculate histogram: " << endl;
cin >> newGrade;
grades.push_back(newGrade);
while (newGrade > 0) {
cin >> newGrade;
while (newGrade > 100) {
cout << "less than 100 plz: ";
cin >> newGrade;
}
grades.push_back(newGrade);
}
grades.pop_back();
int size = grades.size();
cout << "Calculating histogram with " << size << " grades." << endl;
//Create dynamic array for the histogram of 10 sections.
const int hSize = 10;
int hValues[hSize] = { 0 };
IntArrayPtr histogram;
histogram = hValues;
//Make the historgram
int stackValue = 0;
for (int j = 0; j < hSize; j++) {
//Loop through the grade vector slots
for (int i = 0; i < size; i++) {
int testValue = grades[i];
//If the grade at the index is between the stack values of the histogram add one to the value of the slot
if (testValue > stackValue && testValue < stackValue + 10) {
histogram[j]++;
}
}
//After looping through the vector jump up to the next histogram slot and corresponding stack value.
stackValue += 10;
}
//Histogram output. Only output the stacks with values
for (int i = 0; i < 10; i++) {
if (histogram[i] != 0) {
cout << "Number of " << (i + 1) * 10 << "'s: " << histogram[i] << endl;
}
}
return 0;
}
histogram is a pointer, not an array.
While
int histogram[hSize] = {0};
would create a zero-initialised array, your
histogram = { 0 };
does not set any elements to zero (it couldn't, because histogram points to one int, not many).
The braces are ignored – a pretty confusing behaviour inherited from C – and it is equivalent to
histogram = 0;
that is,
histogram = nullptr;
You want
int* histogram = new int[hSize]();
The parentheses value-initialises the array, and in turn its elements.
Value-initialising integers sets them to zero.
(By the way: the habit of typedeffing away asterisks causes more problems than it solves. Don't do it.)
Seg faults are problems with accessing regions of memory you don't have access to, so you need to look at your use of pointers. It often means you have a pointer with a bad value that you just dereferenced.
In this case, the problem is this line:
histogram = { 0 };
This is not setting the histogram values to zero as you think: it's resetting the historgram pointer to zero. Then you later dereference that pointer causing your SegFault (note that this line doesn't even compile with clang, so your compiler isn't helping you any on this one).
Changing that line to:
memset(histogram, 0, hSize);
Will sort the problem in this case.
More generally, to diagnose a segfault there are two tricks I use regularly (though avoidance is better than cure):
Run the program under a debugger: the debugger will likely stop the program at the point of the fault and you can see exactly where it failed
Run the program under Valgrind or similar - that will also tell you where the error surfaced but in more complex failures can also tell you where it was caused (often not the same place).

C++ Variable not properly receiving new value from vector?

I'm trying to write a program that creates and fills a vector with int values, then searches through it and returns the minimum value, recursively. I have the code written out and building, but it returns a weirdly large value for minimum every time- I have a feeling it's not properly assigning the smallest value to int minimum, but I'm not sure. Any thoughts?
#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;
int vectorSize;
int minimum;
int result = -1;
int start;
int ending;
int answer;
int test;
int recursiveMinimum(vector<int>, int, int);
void main() {
cout << "How many values do you want your vector to be? ";
cin >> vectorSize;
cout << endl;
vector<int> searchVector(vectorSize);
start = 0;
ending = searchVector.size() - 1;
for (int i = 0; i < vectorSize; i++) {
cout << "Enter value for position " << i << " " << endl;
cin >> searchVector[i];
}
for (int x = 0; x < vectorSize; x++) {
cout << searchVector[x] << " ";
}
int answer = recursiveMinimum(searchVector, start, ending);
cout << "The smallest value in the vector is: " << answer;
_getch();
}
int recursiveMinimum(vector<int> searchVector, int start, int end) {
if (start < end) {
if (searchVector[start] < minimum) {
minimum = searchVector[start]; //this part seems to not work
}
start++;
recursiveMinimum(searchVector, start, end);
}
else {
return minimum;
}
}
`
Your minimum variable is not initialised, which leads to undefined behaviour. It should be set to the first value in the vector:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending);
Additionally, ending is off by one, which makes it pick 6 as the smallest value out of [6, 9, 8, 4].
So, ultimately, your code should look like this:
minimum = searchVector[0];
int answer = recursiveMinimum(searchVector, start, ending + 1); // note the + 1
While irrelevant to the question, I advise you to use a tail call in recursiveMinimum, as explained here:
start++;
return recursiveMinimum(searchVector, start, end);
The main issue is that you do not initialise minimum. Hence, comparison searchVector[start] < minimum might never become true, and minimum remains uninitialized.
As a quick fix, write int minimum = MAX_INT; instead of int minimum;. MAX_INT is the maximum positive integer value (defined in limits.h). So the values in your array will never be greater that this value, and your minimum search loop will work (unless there are other issues; but for that, please consult the debugger :-) )

Calculating a conditional probability that is similar to a binomial sum

I am considering a society where there are an arbitrary number of people. Each person has just two choices. Either he or she stays with her current choice or she switches. In the code that I want to write, the probability that the person switches is inputted by the user.
To make clear what I am trying to do, suppose that the user tells the computer that there are 3 people in the society where the probabilities that each person chooses to switch is given by (p1,p2,p3). Consider person 1. He has probability of p1 of switching. Using him as a base for our calculation, the probability given person 1 as a base, that exactly no one in the society chooses to switch is given by
P_{1}(0)=(1-p2)*(1-p3)
and the probability using person 1 as a base, that exactly one person in the society chooses to switch is given by
P_{1}(1)=p2*(1-p3)+(1-p2)*p3.
I can't figure out how to write this probability function in C++ without writing out every term in the sum. I considered using the binomial coefficient but I can't figure out a closed form expression for the sum since depending on user input, there are arbitrarily many probabilities that need to be considered.
I have attached what I have. The probability function is only a part of what I am trying to do but it is also the hardest part. I named the probability function probab and what I have in the for loop within the function is obviously wrong.
EDIT: Basically I want to calculate the probability of choosing a subset where each element in that subset has a different probability of being chosen.
I would appreciate any tips on how to go about this. Note that I am a beginner at C++ so any tips on improving my programming skills is also appreciated.
#include <iostream>
#include <vector>
using namespace std;
unsigned int factorial(unsigned int n);
unsigned int binomial(unsigned int bin, unsigned int cho);
double probab(int numOfPeople, vector<double> probs, int p, int num);
int main() {
char correctness;
int numOfPeople = 0;
cout << "Enter the # of people: ";
cin >> numOfPeople;
vector<double> probs(numOfPeople); // Create a vector of size numOfPeople;
for (int i = 1; i < numOfPeople+1; i++) {
cout << "Enter the probability of person "<< i << " will accept change: ";
cin >> probs[i-1];
}
cout << "You have entered the following probabilities of accepting change: (";
for (int i = 1; i < numOfPeople+1; i++) {
cout << probs[i-1];
if (i == numOfPeople) {
cout << ")";
}
else {
cout << ",";
}
}
cout << endl;
cout << "Is this correct? (Enter y for yes, n for no): ";
cin >> correctness;
if (correctness == 'n') {
return 0;
}
return 0;
}
unsigned int factorial(unsigned int n){ // Factorial function
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i) {
ret *= i;
}
return ret;
}
unsigned int binomial(unsigned int totl, unsigned int choose) { // Binomial function
unsigned int bin = 0;
bin = factorial(totl)/(factorial(choose)*factorial(totl-choose));
return bin;
}
double probab(int numOfPeople, vector<double> probs, int p, int num) { // Probability function
double prob = 0;
for (int i = 1; i < numOfPeople; i++) {
prob += binomial(numOfPeople, i-1)/probs[p]*probs[i-1];
}
return prob;
}
For future reference, for anybody attempting to do this, the probability function will look something like:
double probability (vector<double> &yesprobabilities, unsigned int numOfPeople, unsigned int yesNumber, unsigned int startIndex) {
double kprobability = 0;
// Not enough people!
if (numOfPeople-1 < yesNumber) {
kprobability = 0;
}
// n == k, the only way k people will say yes is if all the remaining people say yes.
else if (numOfPeople-1 == yesNumber) {
kprobability = 1;
for (int i = startIndex; i < numOfPeople-1; ++i) {
kprobability = kprobability * yesprobabilities[i];
}
}
else if (yesprobabilities[startIndex] == 1) {
kprobability += probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
}
else {
// The first person says yes, k - 1 of the other persons have to say yes.
kprobability += yesprobabilities[startIndex] * probability(yesprobabilities,numOfPeople-1,yesNumber-1,startIndex+1);
// The first person says no, k of the other persons have to say yes.
kprobability += (1 - yesprobabilities[startIndex]) * probability(yesprobabilities,numOfPeople-1,yesNumber,startIndex+1);
}
return probability;
}
Something called a recursive function is used here. This is completely new to me and very illuminating. I credit this to Calle from Math stack exchange. I modified his version slightly to take vectors instead of arrays with some help.