Storing individual numbers of an int in an array - c++

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).

Related

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.

write program to display odd and even numbers

im trying to write this code but i couldn't
the q is :
by using for loop, write a program to receive input for any 5 numbers and display the total of even an odd numbers. the output should be as shown below
---------------------------------
Enter any 5 numbers: 0 1 3 2 11
0 is not even number.
total exists even = 1
total exist odd = 3
--------------------------------
and this is what i did:
#include<iostream>
using namespace std;
int main()
{
int i,j=0,c=0;
for(i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>i;
}
if(i==0)
{
cout<< "0 is not even number"<<endl;
}
else if(i%2==0)
{j++;}
else if(i%2 !=0)
{c++;}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Going through your code step by step (notice the changed formatting!):
#include<iostream>
using namespace std; // usually considered bad practice
int main()
{
int i, j=0, c=0;
for(i = 0; i < 5; i++)
{
cout << "enter 5 numbers " << i;
cin >> i; // you are overwriting your loop variable!!!
// how do you think your program will go on if you enter
// e. g. 7 right in the first loop run?
// additionally, you did not check the stream state afterwards
// if user entered something invalid (e. g. S), cin sets the
// fail flag and stops further reading - attemps doing so yield
// 0 (since C++11) or don't modify the variable (before C++11)
}
// this section is outside the loop already!
// so you are only checking the number you read in your loop in the very last run
if(i == 0)
{
cout << "0 is not even number" << endl;
}
else if(i % 2 == 0)
{
j++;
}
// this check is redundant: it is the complement to your previous
// check, so if the first went wrong, the second cannot be false any more
// (compare: you did not check for i != 0 either before doing the modulo check)
else /* if(i % 2 != 0) */
{
c++;
}
cout << "total exists even: " << j << endl;
cout << "total exists odd: " << c << endl;
return 0;
}
Changed code:
#include<iostream>
int main()
{
// several serious coding guide lines mandate: only one variable per line:
unsigned int odd = 0;
unsigned int even = 0;
// I used unsigned int here, negative counts are just meaningless...
// I'm consequent in these matters, but range of (signed) int suffices anyway,
// so you can use either one...
// C++ is not C (prior to C99) - keep scope of variables as local as possible
// (loop counter declared within for header, local variable within body)
for(unsigned int i = 0; i < 5u; i++) // (unsigned? see above)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n; // separate variable!
if(!(std::cin >> n))
{
// some appropriate error handling!!! e. g.:
std::cout << "invalid value entered";
return -1;
}
// this now resides INSIDE the for loop
if(n == 0)
{
cout << "0 is not even number" << endl;
}
else
{
// this is an ALTERNATIVE calculation
n %= 2; // gets either 0 or 1...
odd += n;
even += 1 - n;
// (I personally prefer avoiding conditional branches but you *can*,
// of course, stay with the if/else you had before, too...
// - just don't check the complement as shown above)
}
}
cout << "total exists even: " << even << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
About the unsigned: Sometimes these are of advantage:
void f(int n) { /* need to check for both 0 <= n && n <= max! */ }
void f(unsigned int n) { /* n <= max suffices */ }
but sometimes one has to handle them with care:
for(unsigned int n = 7; n >= 0; --n) { /* ... */ } // endless loop!!!
for(unsigned int n = 7; n-- >= 0;) { /* ... */ } // correct variant
(the first one would have worked with signed int, but it is not the fault of the unsigned type, but the programmer's fault who did not chose the right type for what he or she intended...).
Just for completeness: Assuming we could drop the mathically incorrect statement that zero wasn't even, we could have it even much simpler:
unsigned int constexpr LoopRuns = 5u;
int main()
{
unsigned int odd = 0; // just one single variable...
for(unsigned int i = 0; i < LoopRuns; i++)
{
std::cout << "enter 5 numbers (" << i << "): ";
int n;
if(!(std::cin >> n))
{ /* ... */ }
odd += n %= 2;
}
// one single difference instead of five additions...
cout << "total exists even: " << LoopRuns - odd << endl;
cout << "total exists odd: " << odd << endl;
return 0;
}
This program will help you out.
#include <iostream>
int main () {
int num[5], even = 0, odd = 0;
bool hasZero = false;
std::cout << "Enter 5 numbers:"
for (int i = 0; i < 5; i++) {
std::cin >> num[i];
}
for (int i = 0; i < 5; i++) {
if (num[i] == 0) { // Checking if the current number is zero
hasZero = true;
} else if (num[i] % 2 == 0 ) { // Checking if the current number is even
++even;
} else { // If the number is not even, then it must be odd
++odd;
}
}
if (hasZero) { // If the input has zero then print following statement
std::cout << "0 is not an even number" << std::endl;
}
std::cout << "Total even count: " << even << std::endl;
std::cout << "Total odd count: " << odd << std::endl;
return 0;
}
If you are unable to understand any line, then you're most welcome in the comments section below ;)
The problem with your code:
In the for statement, you're using the same variable for both counter and input , i.e., i. This will allow neither for loop to execute properly nor the input to be captured properly.
You're overwriting the i variable everytime you take any input, then only the last input (out of 5 inputs) will be stored in memory.
You're just checking the last input, by using if statement, because the loop is already ended before.
If you want your code to run properly, then these modifications will make that work:
#include<iostream>
using namespace std;
int main()
{
int num,j=0,c=0; // Change the name to num here, because i will be used later as a counter variable.
for(int i=0;i<5;i++)
{
cout<<"enter 5 numbers "<<i ;
cin>>num;
// Don't end for loop here, this will not allow every input to be checked.
if(num==0)
{
cout<< "0 is not even number"<<endl;
}
else if(num%2==0)
{
j++;
}
else if(num%2 !=0) // Or just add a *else* here instead of *else if*, they will work exactly the same here.
{
c++;
}
} // End of for loop
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
Firstly, 0 is an even number, and your code needs to be properly indented, just so you can see that you are indeed reading the input into a single integer, which also controls the loop, and your if statement is outside the for loop (despite the misleading indentation. Here's a simple example implementation, but you can (and should) fix the bugs I pointed out in your own code:
#include <iostream>
int main() {
std::cout << "Enter 5 numbers\n";
int cnt(5);
int n, odd(0), even(0);
while(cnt-- && (std::cin >> n))
n % 2 ? ++odd : ++even;
std::cout << odd << " odd, "
<< even << " even numbers" << std::endl;
return 0;
}
Note the post decrement and the fact the && short-circuits.
This should be your code:
you take an array of integer where you store the input value. Head over to https://www.tutorialspoint.com/cprogramming/c_arrays.htm to learn more abour arrays..
#include<iostream>
using namespace std;
int main(){
int i,j=0,c=0;
int numbers[5];
for(i=0;i<5;i++){
cout<<"enter 5 numbers "<<i ;
cin>>numbers[i];
}
for(i=0;i<5;++i){
if(numbers[i]==0)
{
cout<< "0 is not even number"<<endl;
}
else if(numbers[i]%2==0)
{j++;}
else if(numbers[i]%2 !=0)
{c++;}
}
cout<<"total exists even : "<<j<<endl;
cout<<"total exists ODD : "<<c<<endl;
return 0;
}
using namespace std;
int main()
{
int * Array = new int[5];
int even(0), odd(0);
for(int i = 0; i < 5; i++)
{
cout<<"enter "<< i+1 << "-th number: " << flush;
cin>>Array[i];
if(!Array[i])
{
cout<< "0 is not even number... input again"<<endl;
i = i-1;
}
else
{
if(Array[i]&1) odd++;
else even++;
}
}
cout<<"total exists even : "<<even<<endl;
cout<<"total exists ODD : "<<odd<<endl;
cin.get(); cin.get();
delete[] Array;
return 0;
}

C++ Arrays, Array Conversion not working

I've been stuck on a problem for quite a while today, and despite my searching the internet, I'm not sure as to what I should do. This program (that I will post the source code to) is supposed to be based off of the Birthday Paradox, and help us to prove it correct.
The idea is that we have multiple arrays, one of which simulates the paradox by counting the times that there is NOT a matching birthday pair, another which takes that array and creates a ratio(array value/over total iterations) and another that creates a theoretical array ratio value.
Now, this is where I"m stuck. I can get the first two functions to work perfectly, birthdayFrequency and ratioArray, but the next one idealArray I cannot get to work properly. Both ratioArray and idealArray should be a double data type, and ratioArray stores it properly as a double.
However, idealArray does not. It stores the data in the array positions as integers. I want to know if there's something I missed, something that might have caused me to accidentally make the array an integer.
*I'm going to apologize, the code is really long. Also, I can't get it all to fit in a code window. I apologize.
using namespace std;
//Arraytype declarations
typedef int Birthday[365];
typedef bool Counter[365];
typedef double Ratio[365];
void ratioArray(int, Birthday, Ratio);
void idealArray(Ratio);
void outputTable();
int randomInt(int);
//Main function
int main()
{
Birthday array = {0};
Ratio vector = {0};
Ratio matrix = {0};
int seed;
int runs;
//Prompt the user for the number of times the simulation is to be run.
cout << "Hello and welcome to the Birthday Paradox Simulator. " << endl;
cout << "This program uses simulated runs to calculate and verify the paradox." << endl << endl;
cout << "Please enter the number of runs you want done. IMPORTANT, must be a positive integer." << endl;
cin >> runs;
while (runs <= 0)
{
cout << "That's an invalid value. Please enter a positive number." << endl;
cin >> runs;
}
//Prompt the user for a non-negative integer seed value
cout << "Please input a seed to be used for randomly generating numbers. It must be an integer, and non-negative." << endl;
cin >> seed;
while (seed < 0)
{
cout << "I'm sorry, that is an invalid value. Please enter a non-negative number)" << endl;
cin >> seed;
}
//Seed the srand function
srand(seed);
//Call birthdayFrequency function
birthdayFrequency(runs, array);
//Call ratioArray function
ratioArray(runs, array, vector);
//Call idealRatioArray function
idealArray(matrix);
//Testing values
cout << array[1] << endl;
cout << array[2] << endl;
cout << array[3] << endl;
cout << vector[1] << endl;
cout << vector[2] << endl;
cout << vector[3] << endl;
cout << matrix[1] << endl;
cout << matrix[2] << endl;
cout << matrix[3] << endl;
//Call outputTable function
outputTable();
return 0;
}
void birthdayFrequency(int n, Birthday number)
{
int iteration = 0;
int value;
int boundary = 364;
//For loop for n iterations
for ( int k =0 ; k < n ; k++)
{
Counter boolean = {0};
iteration = 0;
//Randomly mark birthdays until there's a duplicate using a for loop
for ( int i = 0; i < 366; i ++)
{
value = randomInt(boundary);
if (boolean[value] == 1)
break;
else
boolean[value] = 1;
number[iteration]++; //Increment the frequency array for every non-match
iteration++;
}
}
}
void ratioArray(int n, Birthday number, Ratio vectors)
{
double ratio;
//For loop for the number of runs, storing the value of ratios to the total number of runs.
for ( int i = 0 ; i < 364 ; i++)
{
ratio = (double)number[i] / n;
vectors[i] = ratio;
}
}
void idealArray(Ratio number)
{
number[0]= 1.0;
number[1] = 1.0;
//Create an ideal, theoretical probability array
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1- (n-1)/365));
}
}
void outputTable()
{
//Not completed yet.
}
int randomInt(int bound)
{
return static_cast<int>( rand() / (RAND_MAX + 1.0) * bound );
}
In this code:
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1- (n-1)/365));
}
n is an integer, therefore (1-(n-1)/365)) will evaluate to an integer value, since all values in the expression are integers. Also, an integer multiplied by an integer will produce an integer. Since you start off setting number[1] to 1.0, and each element is calculated by multiplying the previous element by an integer amount, all subsequent values will be integer amounts (although stored as doubles).
Change your code to use doubles for the calculation:
for ( int n = 2; n < 364; n++)
{
number[n] = (number[n - 1]*(1.0-((double)n-1.0)/365.0));
}

Using pointer arithmetic to add the contents of two arrays and save to an empty array

So I have written a function that should simply add the values of each element stored in two separate arrays, and save them to a third array.
I don't understand what the issue is, I am simply adding together the value of the int stored at the location referenced by each of my pointers, and saving it to my third, empty, array.
My code compiles just fine, but when I loop to print the contents of my third array (which should contain the sum of the two previous arrays elements at their respective indexes) it just prints a bunch of memory addresses. What gives?
EDIT: I fixed my while loop to perform the arithmetic, and everything is working well. My working code is below. Hope it helps someone else.
#include<iostream>
#include<stdlib.h>
using namespace std;
void arrayAdd(int firstArray[], int secondArray[], int targetArray[], int size){
int *firstPtr = firstArray;
int *secondPtr = secondArray;
int *tragetPtr = targetArray;
while (firstPtr <= &firstArray[size - 1] ){
//add the first two array elements
*tragetPtr = (*firstPtr + *secondPtr);
// point to the next location
*firstPtr++;
*secondPtr++;
*tragetPtr++;
}
}
int main() {
int totalElements;
const size_t ARRAY_SIZE = 50;
int firstIntegerArray[ARRAY_SIZE];
int secondIntegerArray[ARRAY_SIZE];
int thirdIntegerArray[ARRAY_SIZE];
cout << "Please enter the total number of elements for your array: ";
cin >> totalElements;
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the first array at index " << i << ": ";
cin >> firstIntegerArray[i];
}
for(int i = 0; i < totalElements; i++){
cout << "Please enter a value for the second array at index " << i << ": ";
cin >> secondIntegerArray[i];
}
//run our arrayAdd function
arrayAdd(firstIntegerArray, secondIntegerArray, thirdIntegerArray, totalElements);
cout << "The conents of your two arrays added together is; " << endl;
for(int i = 0; i < totalElements; i++){
cout << thirdIntegerArray[i] << ", ";
}
return 0;
}
A local array decays to a pointer when it is passed to a function, so you can't use sizeof on it anymore. Indeed this:
void arrayAdd(int firstArray[]) {
int *firstPtr = firstArray;
std::cout << "sizeof(firstArray) == " << sizeof(firstArray) << std::endl;
std::cout << "sizeof(firstPtr) == " << sizeof(firstPtr) << std::endl;
}
int main() {
int test[] = {1,2,3,4,5,6,7,8,9,0};
arrayAdd(test);
return 0;
}
Prints:
sizeof(firstArray) == 8
sizeof(firstPtr) == 8
on my 64 bit machine.
Casting int[] to int* doesn't change anything since it already became a pointer as an argument. You should pass the size of the array to the method or, since you are working with C++, use an std::array or std::vector which will just solve any problem.

Adding a series of input number in c++

Hi can anyone help me in creating a code for the sum of input number in C++.
e.g.
Input: 535
Output: 13
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
int i = 0,sum = 0;
int numarray[50];
void calc(int c,string num) {
do {
numarray[i] = num.at(i);
/*sum = sum + numarray[i];*/
sum = sum + num.at(i);
cout << numarray[i] << endl;
i++;
} while(i != c);
cout << sum << endl;
}
int main() {
string num;
int i,charlen;
int numar[50];
int sum=0;
cout << "Input numbers: ";
cin >> num;
charlen = num.length();
calc(charlen,num);
}
While characters are numbers, their values are often not the same as the character they represent. The most common encoding scheme is ASCII encoding.
As you can see in the linked table, the digits don't have the value 1 or 2 etc. Instead they have values like 49 and 50 etc. The characters '5' and '3' have the ASCII values 53 and 51 respectively, adding e.g. "535" will give you the result 157.
But as you can see in the ASCII table, all numbers are consecutive, that means we can use a very simple trick to get the digits value from its ASCII value, simply subtract the ASCII value of '0'. For example '5' - '0' will give you the value 5.
Without testing:
#include <iostream>
int main()
{
unsigned long long x;
std::cout << "Enter a non-negative number: ";
std::cin >> x;
unsigned long long sum = 0;
do { sum += x % 10; } while ( x /= 10 );
std::cout << "\nThe sum of digits of the number is " << sum << std::endl;
}
For the sake of readability, it might help to not pass in the charlength into the function, and just do that inside the method. Besides that, a for loop seems like a better option in this case as well.
void calc(string num) {
int sum = 0, int i = 0;
//for loop run from num.length - 1 to 0 {
/*numarray[i] = stoi(num.at(i));*/
/*sum = sum + numarray[i];*/
sum = sum + stoi(num.at(i));
cout << numarray[i] << endl;
i++;
}
cout << sum << endl;
}