Array and function c++ - c++

I built a program that accepts two input from the user, using a array inside a loop, it is passed to a function inside a class which will display the two number.
The problem is when the user is inputting a number and it is 1. The program continuously asks the user to input a number, and when 2 is entered the program ask another number and end, but for example you entered 2 and 3. . . it will then output 2 and 4 (so 3 + 1 ) and always the last number is plus one. Here is the code:
main.cpp:
#include <iostream>
#include "newclass.h"
using namespace std;
int main()
{
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
newclass sum_object;
sum_object.loop_function(array_variable_main, 2);
return 0;
}
newclass.cpp:
#include "newclass.h"
#include <iostream>
using namespace std;
newclass::newclass()
{
}
void newclass::loop_function(int array_variable[], int arraysize)
{
cout << "The numbers that are stored in the array are: " << endl;
for(int counter = 1; counter <= arraysize; counter = counter+1)
{
cout << array_variable[counter] << endl;
}
}
newclass.h:
#ifndef NEWCLASS_H
#define NEWCLASS_H
class newclass
{
public:
newclass();
void loop_function(int array_variable[], int arraysize);
};
#endif // NEWCLASS_H

You have to remember that array indices go from zero to size-1. So for your array it's zero and one. Anything beyond that leads to undefined behavior. Undefined behavior can't easily be predicted, so the result of your program could be anything.

In C and C++ array index normally starts at 0 so this
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
will access outside the array
do instead
int array_variable_main[2];
for(int counter = 0; counter < 2; ++counter)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}

Related

counting the number of values in an array with autofilled elements from rand function in c++

I am currently working on a program that generates random numbers within a given range and that is saved into an array in which I can count the number of the value in the array that is desired. The program that I made works fine without altering compilation error, however, I always get a 0 for the result of the count function, no matter the existence of the element that I'm counting for. Is there a way to fix this problem?
This is the source code of random_function.cpp
#include <iostream>
#include "random_function.hpp"
using namespace std;
Rand::Rand()
{
}
void Rand::Random_function()
{
cout << "Enter amount of numbers to generate: ";
cin >> range;
if (range<=0)
{
cout <<"Error! Please enter the valid number and try again! "<<endl;
}
else {
cout << "Enter minimum boundary: ";
cin >> min;
cout << "Enter maximum boundary: ";
cin >> max;
cout << "\n";
if(max<=min || cin.fail())
{
cout << "\nError! Please enter the valid value and try again! " << endl;
}
else {
srand((unsigned)time(NULL));
for(int n=1 ; n <= range; n++)
{
cout << min + (rand() % static_cast<int>(max - min + 1)) <<endl;
}
}
cout <<"\n"<< "Total random numbers generated: " << range<< endl;
}
}
void Rand::Count_function()
{
extern int y;
int array[range];
int count=0;
int random= min+rand() % static_cast<int>(max - min + 1);
//for some reason this for loop is not working. But there isn't any compilation error.
for (int i=0; i<range; i++)
{
array[i] = random;
if(array[i]==y)
count++;
}
//This part works fine, its just that for loop above doesn't
cout <<"The number of '"<<y<<"'s in the given list is: "<< count <<endl;
}
This is a source code of the random function.hpp
#pragma once
using namespace std;
class Rand
{
public:
Rand();
int range,min,max;
void Random_function();
void Count_function();
};
This is main.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include "random_function.hpp"
using namespace std;
int y;
int main()
{
Rand call;
call.Random_function();
cout<<"Enter the value to count for: ";
cin>>y;
Rand call2;
call2.Count_function();
}

I got infinite loop while practicing array in C++ to find reversed number

Hye, Im a beginner trying to learn C++ language. This is my code that I tried to find reverse input numbers using array. Can help me point my mistakes since I always got infinite loop.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE=50;
int size[ARRAY_SIZE];
unsigned short int i;
cout << "You may enter up to 50 integers:\n";
cout << "\nHow many would you like to enter? ";
cin >> size[ARRAY_SIZE];
cout << "Enter your number: \n";
for (int i = 0; i < ARRAY_SIZE; i++)
{
cin >> size[i];
}
cout << "\nYour numbers reversed are:\n";
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Your infinite loop is because i is unsigned, so i >= 0 is always true.
Here's a C++-ified version:
#include <iostream>
#include <vector>
int main() {
std::cout << "You may enter up to 50 integers:\n";
std::cout << "\nHow many would you like to enter? ";
int count;
std::cin >> count;
// Use a std::vector which can be extended easily
std::vector<int> numbers;
for (int i = 0; i < count; ++i) {
std::cout << "Enter your number: \n";
int v;
std::cin >> v;
// Add this number to the list
numbers.push_back(v);
}
std::cout << "\nYour numbers reversed are:\n";
// Use a reverse iterator to iterate through the list backwards
for (auto i = numbers.rbegin(); i != numbers.rend(); ++i) {
// An iterator needs to be de-referenced with * to yield the value
std::cout << *i << " ";
}
std::cout << std::endl;
return 0;
}
There's many problems in your original code, but the clincher is this:
for (i = size[ARRAY_SIZE] - 1; i >= 0; i++)
cout << " size[i]" << " ";
}
Since you keep adding to i through each cycle you'll never go below zero, especially not for an unsigned short int. This should be:
for (int i = count - 1; i > 0; --i) {
std::cout << numbers[i];
}
Presuming you have a thing called numbers instead of the bizarrely named size and the array size is count, not i, as i is generally reserved for iterators and loop indexes.

How to echo input within a void function and do-while loop C++

I need some advice on how to echo the input from the user. A bit of background on the program that this is needed first. I created this program so that it asks the user how many values they would like to enter and then they enter the number in positive integers. Then the program computes to figure out if the numbers are even, odd, or zero and displays said information. I'm stuck on how I can create something that can output all of the enter values on the same line. For example, if the user chooses to enter in 4 values, being 1,2,3, and 4, with my current program it will read, Enter a number on one line and the next would be the number 1. Then it would ask to enter a number again and on another line the number 2. When I want it to read, The values you entered are 1,2,3,4. I'm confused as to how it works to display all the input on one line with a call by reference. Any advice or explanation would be greatly appreciated!
Code below
#include<iostream>
using namespace std;
void initialize(); //Function declarations
void get_number(int x);
void classify_number(int, int& zero_count, int& even_count, int& odd_count);
void print_results();
int N; //The number of values that the user wants to enter
//variables declared so that all functions can access it
int even_count;
int odd_count;
int zero_count;
int main()
{
cout << "Enter number of values to be read, then press return.\n"; //Prompting the user for how many values they will want to input
cin >> N;
get_number(N);
return 0;
}
void initialize() //This function is making sure that all the variables being used are initialized
{
even_count = 0;
odd_count = 0;
zero_count = 0;
}
void get_number(int N) //This function is getting the input from the user and then calling upon the previous function
{
int count = 0;
int x;
initialize(); //Calling upon the previous function to uses the variables
do {
cout << "Enter a positive whole number, then press return.\n";
cin >> x; //The number the user enters
//call the funtion and increment their count
classify_number(x, zero_count, even_count, odd_count); //Calling upon the function classify to update
count++;
} while (count < N);
//then print the count
print_results(); //Calling upon the print function
}
void classify_number(int x, int& zero_count, int& even_count, int& odd_count) //This function determines if it's an even,odd, or zero
{
if (x == 0)
zero_count++;
else if (x % 2 == 0)
even_count++;
else
odd_count++;
}
void print_results() //This is printing the results on the screen of the number of even, odds, and zeros.
{
cout << "There are " << even_count << " number of evens.\n";
cout << "There are " << zero_count << " number of zeros.\n";
cout << "There are " << odd_count << " number of odds.\n";
}
I believe that this much code will be sufficient :
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main() {
std::size_t n;
std::cout << "Enter number of elements : ";
std::cin >> n;
std::vector<int> v(n);
std::cout << "Enter the numbers now : ";
for (auto &i : v) std::cin >> i;
std::cout << "The values you entered are : [ ";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ","));
std::cout << "\b ]\n";
auto odd = std::count_if(v.begin(), v.end(), [](auto i) { return i % 2; });
auto zero = std::count(v.begin(), v.end(), 0);
auto even = v.size() - (odd + zero);
std::cout << "There are " << even << " even number(s).\n"
<< "There are " << zero << " zero(s).\n"
<< "There are " << odd << " odd number(s). \n";
}
Sample Run :
Enter number of elements : 6
Enter the numbers now : 0 1 2 3 4 6
The values you entered are : [ 0,1,2,3,4,6 ]
There are 3 even number(s).
There are 1 zero(s).
There are 2 odd number(s).
Ref. :
std::vector
Range-based for loop
How to print out the contents of a vector?
std::count, std::count_if
You could simply use an array of integers.
#include<iostream>
int main(int argc, char *argv[]){
/* Declare an array great enough to store all possible user values. */
/* Or use dynamic memory allocation when you are more experienced. */
int my_array[16];
int my_array_length = sizeof my_array / sizeof my_array[0];
/* As your code only uses positive integers, we use this information */
/* to our advantage and initialize our array with negative numbers. */
for(int i = 0; i < my_array_length; i++){
my_array[i] = -1;
}
/* Here is your own input program routine. I'll use some example values. */
for(int i = 0; i < my_array_length; i++){
if(i > 4){
break;
}
my_array[i] = i;
}
/* Here is your output program routine. */
for(int i = 0; i < my_array_length; i++){
if(my_array[i] == -1){
break;
}
std::cout << my_array[i] << std::endl;
}
return 0;
}
Or you could just count the amount of inputs in the first place.

sort and show the number of digits

I want to my program can sort the inputted integer and compute the number of any integer that inputted and I don't know where should write the cout of c
example
a[9]={2,3,2,6,6,3,5,2,2}
the number of 2 is 4
the number of 3 is 2
the number of 6 is 2
.
.
please fix this code
int main()
{
cout << "please enter the number of digites :" << endl;
int n;
cin>>n;
int a[n];
cout<<"enter numbers :"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
int c;
for(int m=0;m<n;m++)
{
if(a[m]==a[m+1])
c++;
else
c=0;
}
return 0;
}
Read through my solution, I've commented the parts I've changed. I tidied it up a little.
To answer your question: you should print the output (frequency of an integer in array) before you reset the count variable to 1. This will work because we have sorted the array, and will not have to look ahead for more occurrences of the current number.
[EDIT] I also added this above your code:
#include <iostream>
#include <vector>
using namspace std;
Full Solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Get input
int n;
cout << "Please enter the number of digits: ";
cin>>n;
vector<int> a;
cout << "Enter " << n << " numbers: " << endl;
for(int i=0;i<n;i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
// Sort input
int i,j;
for (i = 0; i < a.size(); i++) {
for(j = 0; j < a.size()-i-1; j++) {
if(a[j] > a[j+1]) {
int temp;
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
// If an element is in an array
// we can not have 0 occurrences
// of that element, hence count
// must start at 1
int count = 1;
// Int to count
int current = a[0];
// Ouput if we have reset the count,
// or if it is the last iteration
bool output;
// Loop through array
for (int i = 1; i < a.size(); i++) {
output = false; // Reset output if we have printed
if (a[i] == current) {
// If current int and the element next to it are the same,
// increase the count
count++;
} else {
// If current and next are different,
// we need to show the frequency,
// and then reset count to 1
cout << current << " occurs " << count << " times" << endl;
count = 1;
current = a[i];
}
}
// Output one last time, for last int in sorted set
cout << current << " occurs " << count << " times" << endl;
return 0;
}
If this doesn't help, go and read this page, it is a solution in C, but can be adapted to C++ easily. https://codeforwin.org/2015/07/c-program-to-find-frequency-of-each-element-in-array.html This will help you understand and write the task. They take you step-by-step through the algorithm.
This is a typical use-case for a std::map. A std::map<char,int> lets you easily count the frequency of charaters (its easier to treat the user input as characters instead of converting it to numbers).
This is basically all you need:
#include <iostream>
#include <iterator>
#include <map>
int main(){
std::istream_iterator<char> it( std::cin );
std::istream_iterator<char> end_of_input;
std::map<char,int> data;
while (it != end_of_input ) data[*(it++)]++;
for (const auto& e : data) std::cout << e.first << " " << e.second << "\n";
}
This is probably a lot at once, so lets go one by one.
std::istream_iterator<char> lets you extract characters from a stream as if you are iterating a container. So the while iteratates std::cin until it reaches the end of the input. Then *(it++) increments the iterator and returns the character extracted from the stream. data[x]++ accesses the value in the map for the key x and increments its value. If there is no value in the map yet for the key, it gets default initialized to 0.
For input: 11223 it prints
1 2
2 2
3 1
Your code has some issues, not sure if I can catch them all...
You are using VLA (variable lenght arrays) here: int a[n];. This is a compiler extension and not standard c++.
You access the array out of bounds. When i == 0 then j goes up to j<n-i-1 == n-1 and then you access a[j+1] == a[n], but the last valid index into the array is n-1. Same problem in the other loop (a[m+1]).
Assuming your sorting works, the last loop almost gives you the number of elements, but not quite, to fix it you can change it to...
int current = a[0];
int counter = 1;
for(int m=1;m<n;m++) {
if(a[m] == current) {
counter++;
} else {
std::cout << current << " appears " << counter << " times" << endl;
counter=1; // note: minimum freq is 1 not 0
current = a[m];
}
}

Storing individual numbers of an int in an array

I was trying to write a program in which I take an input number,
example 891 and input each of these number in an array for example
x[0] = 8, x[1] = 9 and x[2] = 1
I was trying to use recursion to implement my method:
void calc(int val, int k)
{
static int number = val;
if((val/10))
{
calc(val/10, k--);
}
int x = number - val*pow(10, k);
cout << x << ", k = " << k << " and number = " << number << endl;
}
int main()
{
//write a program that converts a number to string
int number;
cout << "Enter a number: ";
cin >> number;
number = 891;
int k = 0;
//while(number/10 != 0)
k = 2;
calc(number, k);
}
Basically I'm trying to use my recursive function to try to break the
number down in its finer parts, however I get an output of (in val):
91, 1, -8019. Is there a way I can improve on this, but maintaining
the structure?
Both putting your data into an array and solving this problem recursively requires a bit of pointer arithmetic.
You'll need to allocate your array ahead of time, which means you need to know the number of digits. You'll also need to pass around the pointer to the array so that recursive calls can assign to it.
Below is a shortish solution that fits both of these requirements.
#import <math.h>
#import <iostream>
using namespace std;
void calc(int num, int* digs) {
if (num > 0) {
calc(num/10, digs-1); //recursive call, doing head recursion
*digs = num %10; //assigning this digit
}
}
int main() {
//Get number from user
int inputNumber;
cout << "Input a number: ";
cin >> inputNumber;
int numDigits = log10(inputNumber) + 1;
int outputArray[numDigits];
//I give a pointer to the end of the array
//This is because we are receiving digits from the end
//So we traverse backwards from the end of the array
calc(inputNumber, outputArray+numDigits-1);
//Following is not logic, just printing
for (int i=0; i < numDigits; i++) {
cout << outputArray[i] << " ";
}
cout << endl;
}
void calc(int val)
{
cout << "digit:"<<val % 10<< " and number = " << val << endl;
if((val/10))
{
calc(val/10);
}
}
This will print out each digit (which looks like what you are trying to do in the function).