How to use if with array elements in c++ - c++

I want to receive only positive numbers from the user which are less than or equal to 4
Here is my code:
#include <iostream>
using namespace std;
int main()
{
unsigned int n;
cin>>n;
unsigned int arr[n];
for (int i =0 ;i<n ; i++){
if (arr[i]<=4)
cin>>arr[i];
}
}
What am I doing wrong with my code? It receives numbers which are greater than 4 .

The behaviour of your code is undefined. You are reading elements of the array before writing to them.
And then you don't check the value inputted by the user.
Note also that variable length arrays are not standard C++ (unsigned int arr[n]; declares such an array). Use a std::vector instead?
Really the best way to sort out these problems is to use a good line-by-line debugger.

#include <iostream>
using namespace std;
int main() {
unsigned int input = 0u; // Holds user input
unsigned int nextPos = 0u; // Next free position in our array
unsigned int arraySize = 0u; // The size of the dynamic array
unsigned int* array = nullptr; // Pointer to our dynamic array
// Ask the user for the array size
cout << "Please Enter The Array Length" << endl;
cin >> arraySize;
// using array = int[arraySize] wouldn't work because the compiler won't know what value the number is at compile time.
// instead we use the 'new' keyword to allocate some memory while the program is running
// this is called dynamic allocation
array = new unsigned int[arraySize];
// The reason it's a while loop instead of a for loop is to only insert numbers into the array
// when the pass the rule if input <= 4u (the u part just means it's unsigned)
while(nextPos < arraySize) {
// Here we ask for an input and store it in the same named input variable
cout << "Please Enter A Valid Number" << endl;
cin >> input;
// Does the input pass the check?
if (input <= 4u) {
// If so store it in the current position in the array and increment
// the line below is the same as doing
// array[nextPos] = input;
// nextPos = nextPos + 1u;
array[nextPos++] = input;
} else {
// When the input doesn't meet the rule, complain about an invalid number
cout << input << " is an invalid number" << endl;
}
}
// A rule in C++ is that we need to manually release any memory we allocate using new
// it would be 'delete variable' for objects or 'delete[] variable' for arrays
delete[] array;
}

Related

Variable length array c++ & No operator >> error?

going through a c++ course and was asked to create a simple program to average values in a user array
i figured id go the extra mile and learn to mess with a few additional types.
I searched online for a fix for the non variable arrays in c, and i know this is where shit hits the fan
//manually allocate the space to the array
int** MyArray = new int* [Length_Of_Array]; // i changed it to float to suit my program
For my error's im getting
ERROR IMAGE
Is there a better alternative to this (sticking to arrays as opposed to vectors) ?
MY FULL CODE
#include <iostream>
using namespace std;
//function declare
float Avg(float Array, int Length);
//Variable declare
int Length_Of_Array;
int main()
{
//Declarations
float Result{};
//User defines size of the array
cout << "Please enter the length of your array (Min 5) ";
cin >> Length_Of_Array;
//User Enters x elements into array
cout << "Please enter" << Length_Of_Array << " Digits into the array " << endl;
//manually allocate the space to the array
float** MyArray = new float* [Length_Of_Array];
//Function use
Result = Avg(MyArray, Length_Of_Array);
//Result
cout << "THE AVERAGE OF YOUR ARRAY IS " << Result << endl;
}
float Avg(float** Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
Let's take a look at this function:
float Avg(float** Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
The type of Array is float** so the type of Array[i] is float *. But you can't read a float * from std::cin and you don't need a float** for a 1D-array. (** is usually used for matrices) Since you are required to use arrays, all you have to do is to change float** to float*.
So you get float Avg(float* Array, int length) and float* MyArray = new float[Length_Of_Array];
Some other hints:
Don't forget to update the forward declaration of Avg also ;)
Don't forget to free the allocated memory if you don't need it anymore with delete[] MyArray;
You should initialize a variable with an actual value like int sum = 0; insted of int sum{};. It makes your code better readble und understandable.
The function signature in function definition and declaration doesn't match.
float** Array means array of array or a pointer to array. Besides you have problem with memory leakage.
You can simply use vector instead:
float Avg(std::vector<float>& Array, int length) {
int sum{};
//Stores, enters and calculates user enters elements into array
for (int i = 0; i < length; i++) {
cin >> Array[i];
sum += Array[i];
}
return (sum /length);
}
and:
std::vector<float> MyArray(Length_Of_Array);

Problem with storing 10 integers into an array C++

Ok, I'm very confused as to why this happens. All I'm trying to do is put 10 integers from input into an array. Why is this happening.
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
If you could please tell me where I'm going wrong, that would be very much appreciated. Thank you!
From how your code is written, you're only adding the user's input to the [10] element of intArray[] within that for loop you created. Additionally, any information added to the array at intArray[10] or beyond is placed out of bounds.
The only way I can really demonstrate what I mean is...
for (int i = 0; i < 10; i++)
{
std::cout<<"Enter a number:";
std::cin >> intArray[i];
}
Another thing I noticed is you're creating another array with the same name in your printData method. You should instead pass the intArray you're filling up with information to this method and use it to display your information.
The problem lies in this block of code-
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[10];
}
As mentioned in other answers and comments you are storing all the values in the 10th memory slot of the array.
As per your comment
I forgot to mention, the output is just random integers and characters. EX: 00B3F724
00B3F724=> These are the memory address allocated to the array and which will hold the elements which will be inserted.
How array actually works-
float myArray[10];
The above snip creates 10 units of memory space. The units differ on the type which the array will hold. In this case it is holding float values, so each memory space will be of 4 bytes. All of these spaces have an address for lookup and other operations. All these spaces are expecting a float value to be inserted.
As you are using the loop you have to loop through the array(all the memory slots allocated to the array) and allocate a float element to each one of them and not only the last element(10th).
Effectively your for loop will become
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
Instead of intArray[10] insert values like this intArray[i]. As i will traverse through all the slots on every iteration of the loop insert a values to a slot.
Your code will look like
#include <iostream>
using namespace std;
int getData(float intArray[10]);
void printData(float intArray[10]);
int main() {
float myArray[10];
getData(myArray);
printData(myArray);
cin.get();
cin.ignore();
}
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cout << "Enter a number:";
std::cin >> intArray[i];
}
return 1;
}
void printData(float intArray[10]){
cout << intArray;
}
As you know if an array is declared as myArray[10], its index ranges from 0-9. Putting a value in myArray[10] will go out of bound and will produce garbage value.
In getData(float intArray[]) you are always overwriting the content of intArray[10] while it is out of bound so it is not being stored in an actual array. You should write your getData(float intArray[]) as following :
int getData(float intArray[]) {
for (int i = 0; i < 10; i++)
{
std::cin >> intArray[i];
}
return 1;
}
Also in printData(float intArray[10]) you are only printing the base address of the array (i.e the name of the array gives the address of the 0th index).So the correct code would be:
void printData(float intArray[])
{
for(int i=0;i<10;i++)
{
cout << intArray[i]<<" ";
}
}
Simply change,
std::cin >> intArray[10];
to,
std::cin >> intArray[i];
What you are doing wrong:
you are storing the value at the 10th position (actually it is 11th position) again and again and the value at 10th position replaces with the new value again and also the 10th position doesn't exist in the array because the index of the array starts from 0, so your array has the index values from 0 to 9.

How to pass arrays in the main func. w/ c++

#include <iostream>
using namespace std;
const int MAX = 1000;
int ArrMix[MAX];
int *ptrArrPos[MAX];
int *ptrArrNeg[MAX];
int PosCounter = 0;
int NegCounter = 0;
int r;
void accept(int ArrMix[MAX])
{
cout<<"Enter the number of elements in your array: ";
cin>>r;
for (int i = 0; i < r; i++)
{
cout<<"Enter value:";
cin>>ArrMix[i];
}
}
void process(int &i)
{
if(ArrMix[i] >= 0)
{
ptrArrPos[PosCounter] = &ArrMix[i];
PosCounter++;
}
else
{
ptrArrNeg[NegCounter] = &ArrMix[i];
NegCounter++;
}
}
void display(int &i)
{
cout<<"Your passed array is: " << endl;
cout<<ArrMix[i] << endl;
cout <<"Total number of positive integers is: "<<PosCounter<<endl;
cout<<"Your positive array is: "<<endl;
for (int i = 0; i < PosCounter; i++)
{
cout << *ptrArrPos[i] << endl;
}
cout<<endl;
cout <<"Total number of Negative integers is: "<<NegCounter<<endl;
cout<<"Your negative array is: "<<endl;
for (int i = 0; i < NegCounter; i++)
{
cout << *ptrArrNeg[i] << endl;
}
}
int main ()
{
int *i;
int a = &i;
accept(&ArrMix[MAX]);
process(a);
display(a);
system("pause>0");
}
The code you see above is a program use to create a user-defined array list of numbers. It should accept numbers from the user, display the passed array, positive numbers array and its negative numbers array. it should evaluate items, meaning separating negatives #s from positive numbers then creating an array for each. next is to use a counter to identify how many positive #s and negative #s are in each array.
I am having problems in passing the array from one function to another using pointers and calling it in the main function. so please help me?
The expression &ArrMix[MAX] returns a pointer to the integer at index MAX in the array. This index is one beyond the array, meaning you pass a pointer to beyond the array to the function which will then happily write to that memory.
Passing an array is as simple as passing any other argument:
accept(ArrMix);
You also have a problem here:
int *i;
int a = &i;
You declare i to be a pointer to an int. Then you use &i which returns the address of the variable i, in other words a pointer to a pointer to an int, and try to assign this double-pointer to a normal int variable.
It seems to me that you might want to return the number of entries is in the array from the access function, and then loop over the entries the user entered in the array and call process for each value. And then in display instead of taking the ArrMix index it should take the size and loop over that to display the ArrMix array.

C++ Program Functions

I am having trouble with my functions. When I use a function to manipulate an array, and print it and move on to the next manipulation function, it uses the array that was previously manipulated instead of the original array. For example, when my function converts every negative number to a positive, I call the next function which zeros out all even numbers, and my array prints out all zeros, instead of using the array from the original.
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define NUMS_PER_LINE 10 // maximum numbers to be printed on each line.
int numbers[100]; // array to hold upto 100 integer numbers.
int numcnt; // actual count (<=100) of numbers in above array.
// reads file content into array
void read_array_from_file (const char filename[])
{
ifstream inpfile(filename);
if (!inpfile.is_open())
{
cout << "Can't open file : " << filename << endl;
exit(1);
}
numcnt=0; // Initialise count of read numbers
// Read numbers from the file into array.
inpfile >> numbers[numcnt];
while (!inpfile.eof()) // Read until EOF is reached.
{
numcnt++; // Got one more number from input file.
inpfile >> numbers[numcnt];
}
inpfile.close();
return;
}
// Print out all the values in the array
void print_array_content (int numsinaline)
{
int i;
for (i=0; i<numcnt+1; i++)
{
if ((i % numsinaline) == 0)
cout << endl;
cout << numbers[i] << " ";
}
cout << endl << endl;
return;
}
// calculate average
double calculate_average ()
{
int i;
float sum=0;
for (i=0; i<(numcnt-1); i++)
{
sum += numbers[i];
}
return (sum/(numcnt-1));
}
// Find numbers larger and smaller than the average.
void find_numbers_smaller_and_larger_than_average (int &larger, int &smaller, int average)
{
int i;
for (i=0; i<(numcnt-1); i++)
{
if (numbers[i] < average)
smaller++;
else if (numbers[i] > average)
larger++;
}
return;
}
// Convert negative numbers to positive in the array 'numbers'.
void convert_negative_to_positive ()
{
int i;
for (i=0; i<(numcnt-1); i++)
{
if (numbers[i] < 0)
numbers[i] *= -1;
}
return;
}
// Convert all even numbers into zero.
void zero ()
{
int i;
for (i=0; i<numcnt; i++)
{
if (numbers[i] > 0)
numbers[i] *= 0;
}
return;
}
First of all, you are using a global variable for your array, so you are never passing it to your function. When you change a global variable in the function, it changes the data in the array. You should be passing that data into the function and NOT using global variables.
Second, while(!inpFile.eof()) is bad! Don't do it.
For file streams:
std::vector<int> numbers;
std::ifstream fin("myfile");
std::copy(std::istream_iterator<int>(fin), std::istream_iterator(), std::back_inserter<vector<int> >(numbers));
Those 3 lines will read the entire file into the vector "numbers".
Third, when declaring your functions, pass the array:
void myFunction(const std::vector<int>& vec); // if you aren't going to change the vector
or
void myFunction(std::vector& vec); // if you are going to change it
and you would call it by simply:
myFunction(numbers);
" it uses the array that was previously manipulated instead of the original array."
Obviously because you have your array declared globally
int numbers[100];
Outside all functions.
When you perform one operation on this array, the element get modified and the new values will be used for next functions.
Instead of this, save of copy of your original array and then use this copy whenever you wish to work on original array
All your operations act on a single global variable, numbers. If you modify it in any of your functions its values will also change in every other occurrence.
Instead, provide a way to tell your functions which array you want to use, how many elements it contains and use several arrays. This also enables you to get rid of the global variable.
Example:
#include <iostream>
using namespace std;
typedef unsigned int array_size_t;
void print_array(int array[], array_size_t size){
for(array_size_t i = 0; i < size; ++i){
cout << array[i] << endl;
}
}
int main(){
int a1[] = {1,2,3,4};
int a2[] = {1,3,3,7,0,0,0,0};
print_array(a1,4);
print_array(a2,8);
}
Remark
If you're allowed use standard containers such as std::vector instead. The solution above is more C than C++-like.
You are using global variable. All your operation on numbers whatever index will change your certain position's value.
Another potential risk is if your input file contains more than 100 integers, you will do
inpfile >> numbers[100];
or some index number greater than 100.
which will cause a segmentation fault.
You should be very careful when using global variables
You are directly manipulating your array inside of your functions since it is defined globally, instead of passing in a copy as a parameter.
void modify(int[] array) {
//Modify copied array here
}
int main() {
int numbers[100];
int copyNumbers[100];
//Copy numbers
memcpy(copyNumbers, numbers, sizeof(numbers));
modify(copyNumbers);
//Use modified array
memcpy(copyNumbers, numbers, sizeof(numbers)); //Set back to original
modify(copyNumbers); //Modify copy again as original
}

Heap Corruption Detected: after Normal block (#126)

I cannot for the life of me figure out why I am getting this Debug Error:
Heap Corruption Detected: after Normal block (#126) at
0x004cF6c0
CRT detected that the application wrote to memory after end of heap bugger.
I understand that you need to free memory whenever you use new operator,
which I did and I am still getting problems.
for some reason the program doesn't end correctly in the recursive function.
I debugged it and went through each line of code with breakpoints.
At the end of the if statement in countSum it somehow subtracts 1 from i
and then reenters the if block.....which it is not supposed to do.
Why is this occurring?
/*this program calculates the sum of all the numbers in the array*/
#include <iostream>
#include <time.h>
using namespace std;
/*prototype*/
void countSum(int, int, int, int*);
int main(){
bool flag;
int num;
int sum = 0, j=0;
int *array = new int;
do{
system("cls");
cout<<"Enter a number into an array: ";
cin>>array[j];
cout<<"add another?(y/n):";
char choice;
cin>>choice;
choice == 'y' ? flag = true : flag = false;
j++;
}while(flag);
int size = j;
countSum(sum, 0, size, array);
//free memory
delete array;
array = 0;
return 0;
}
void countSum(int sum, int i, int size, int *array){
if (i < size){
system("cls");
cout<<"The sum is :"<<endl;
sum += array[i];
cout<<"...."<<sum;
time_t start_time, stop_time;
time(&start_time);
do
{
time(&stop_time); //pause for 5 seconds
}
while((stop_time - start_time) < 5);
countSum(sum, (i+1) , size, array); //call recursive function
}
}
array holds enough space for a single int:
int *array = new int;
but there is potentially an attempt to insert more than one int which would result in writing to memory that is not available. Either use a std::vector<int> or it must be known beforehand the maximum number of ints that will be entered before array is allocated.
If this is a learning exercise and you do not want to use std::vector<int> you could prompt the user to enter the number of ints they wish to enter:
std::cout << "Enter number of integers to be entered: ";
int size = 0;
std::cin >> size;
if (size > 0)
{
array = new int[size];
}
Then accept size number of ints. Use delete[] when you use new[].
The solution was to set the size new int[size]....although I wish that you didn't have to set a size if it is dynamic.