write a program that let's the user enter 10 numbers into an array. The program should then display the largest number as and the smallest number stored in the array.
I am very confused on this question that was on a previous exam and will be on the final. Any help would be appreciated! This is what I had on the test and got 3/15 points, and the code was almost completely wrong but I can post what I had if necessary, thanks! For creating the array, i can at least get that started, so like this?
#include <iostream>
using namespace std;
int main()
{
int array(10); // the array with 10 numbers, which the user will enter
cout << "Please enter 10 numbers which will be stored in this array" << endl;
cin >> array;
int smallest=0; //accounting for int data type and the actual smallest number
int largest=0; //accounting for int data type and the actual largest number
//-both of these starting at 0 to show accurate results-
And then on my test, i started using for loops and it got messy from there on out, so my big problem here i think is how to actually compare/find the smallest and largest numbers, in the best way possible. I'm also just in computer science 1 at university so we keep it pretty simple, or i like to. We also know binary search and one other search method, if either of those would be a good way to use here to write code for doing this. Thanks!
Start by declaring an array correctly. int array(10) initializes a single integer variable named array to have the value 10. (Same as saying int array = 10)
You declare an array of 10 integers as follows:
int array[10];
Anyway, two simple loops and you are done.
int array[10];
cout << "Enter 10 numbers" << endl;
for (int x = 0; x < 10; x++)
{
cin >> array[x];
}
int smallest=array[0];
int largest=array[0];
for (int x = 1; x < 10; x++)
{
if (array[x] < smallest)
{
smallest = array[x];
}
else if (array[x] > largest)
{
largest = array[x];
}
}
cout << "Largest: " << largest << endl;
cout << "Smallest: " << smallest << endl;
You can actually combine the two for loops above into a single loop. That's an exercise in an optimization that I'll leave up to you.
In this case, you don't actually have to do a binary search, or search the array. Since you will be receiving the input directly from the user, you can keep track of minimum and maximum as you encounter them, as show below. You know the first number you receive will be both the min and max. Then you compare the next number you get with those ones. If it's bigger or smaller, you store it as the max or min respectively. And then so on. I included code to store the number in an array, to check errors and to output the array back to the user, but that's probably not necessary on an exam due to the limited time. I included it as a little bit of extra info for you.
#include <cctype> // required for isdigit, error checking
#include <cstdlib> // required for atoi, convert text to an int
#include <iostream> // required for cout, cin, user input and output
#include <string> // required for string type, easier manipulation of text
int main()
{
// The number of numbers we need from the user.
int maxNumbers = 10;
// A variable to store the user's input before we can check for errors
std::string userInput;
// An array to store the user's input
int userNumbers[maxNumbers];
// store the largest and smallest number
int max, min;
// Counter variables, i is used for the two main loops in the program,
// while j is used in a loop for error checking
int i;
unsigned int j;
// Prompt the user for input.
std::cout << "Please enter " << maxNumbers << " numbers: " << std::endl;
// i is used to keep track of the number of valid numbers inputted
i = 0;
// Keep waiting for user input until the user enters the maxNumber valid
// numbers
while (i < maxNumbers)
{
// Get the user's next number, store it as string so we can check
// for errors
std::cout << "Number " << (i+1) << ": ";
std::cin >> userInput;
// This variable is used to keep track of whether or not there is
// an error in the user's input.
bool validInput = true;
// Loop through the entire inputted string and check they are all
// valid digits
for (j = 0; j < userInput.length(); j++)
{
// Check if the character at pos j in the input is a digit.
if (!isdigit(userInput.at(j)))
{
// This is not a digit, we found an error so we can stop looping
validInput = false;
break;
}
}
// If it is a valid number, store it in the array of
// numbers inputted by the user.
if (validInput)
{
// We store this number in the array, and increment the number
// of valid numbers we got.
userNumbers[i] = atoi(userInput.c_str());
// If this is the first valid input we got, then we have nothing
// to compare to yet, so store the input as the max and min
if (i == 0)
{
min = userNumbers[i];
max = userNumbers[i];
}
else {
// Is this the smallest int we have seen?
if (min < userNumbers[i])
{
min = userNumbers[i];
}
// Is this the largest int we have seen?
if (max < userNumbers[i])
{
max = userNumbers[i];
}
}
i++;
}
else
{
// This is not a valid number, inform the user of their error.
std::cout << "Invalid number, please enter a valid number." << std::endl;
}
}
// Output the user's numbers to them.
std::cout << "Your numbers are: " << userNumbers[0];
for (i = 1; i < maxNumbers; i++)
{
std::cout << "," << userNumbers[i];
}
std::cout << "." << std::endl;
// Output the min and max
std::cout << "Smallest int: " << min << std::endl;
std::cout << "Largest int: " << max << std::endl;
return 0;
}
Related
Newer to coding and im stuck, Need to make a array thats stores 5 numbers (1-9), then i need to check that array for duplicates if there is duplicates i need to replace that number either with a whole new random line no duplicates (seems like the easier option) or just replace that one number,
after that wants me to get users 5 numbers guess store that in a array, display that array at the bottom along with these under each of the numbers
// The * = means the number is in the exact location
// The - = means the array does not contain that number
// The + = means the array contains the number but its not in the right location
All the arrays want the digits to be entered one at a time
repeat steps till user gets all the numbers to * then end game with completion msg.
My true problem lies with step 4 and step 7;
Below is the code ive been working on today but any help would be truly appreciated
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE]; //this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
srand(time(0));
for(int i=0;i<SIZE;i++)
randcode[i]= (rand() % 10); //Computers random 5 numbers generated
cout<<"\nRandom C-numbers::"<<endl;
for(int i=0;i<SIZE;i++)
cout<<randcode[i] << " ";
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
for (int i=0; i<SIZE; i++) {
cout<<"\nEnter Digit "<< i+1 << ": ";
cin >> guess[i];}
cout << endl;
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int n=0; n < SIZE; ++n) {
cout << guess[n] << " ";
}
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << endl << endl;
cout << "Good job! You guessed the code!";
return 0;
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i+1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
I got most the side code done but im just stumped on how to get this array to match any help would be nice
Here is how I would implement the program to generate the number without duplicate:
Step3 would look like this:
int tempNumber;
int i = 0;
while (i < SIZE) {
tempNumber = (rand() % 10);
if (contains_duplicates(randcode, tempNumber, i) == false) {
// every time there is no duplicate we push and add i by 1;
randcode[i] = tempNumber; // Computers random 5 numbers generated
i++;
}
}
contains_duplicates function would look like this:
bool contains_duplicates(int arr[], int tempNum, int currentArrSize)
// This function searches the array a (of size n) and returns true if the
//array
// contains duplicates; otherwise, it returns false.
{
for (int j = 0; j <= currentArrSize; j++) {
// if the array[index] not equal generated number the loop will
//iterate again without going to the line below
if (arr[j] != tempNum) {
continue;
}
// if the array[index] equal the function will return true and end
//the function
// uncomment this to check how many time it duplicate (not
//necessary tho)
//cout << "if return true, this will appear"<< endl;
return true;
}
// if the loop is done and no duplicate, function will return false
return false;
}
With this method it is not necessary to do step 4 because we already prevent duplicate array!
Here is the last problem from your question which is step 7:
cout << endl;
for (int i = 0; i < SIZE; i++) {
if (guess[i] == randcode[i]) {
cout << "* ";
} else if (search_array(randcode, SIZE, guess[i])) {
cout << "+ ";
} else {
cout << "- ";
}
}
Seems like the problem has been solved, now try to implement step 8 by yourself, good luck :)
This is my code in C++. When I am taking input {11 10 5 6 7} in the array, Every time it's giving output smallest as 0. But giving correct output to the other inputs.
#include<bits/stdc++.h>
using namespace std;
int main() {
int a[100000];
int large, small;
int n;
cin >> n;
for (int j = 0; j < n; j++) {
cin >> a[j];
}
for (int j = 0; j < n; j++) {
cout << a[j] << " ";
}
large = small = a[0];
for (int i = 1; i <= n; i++) {
if (a[i] < small) {
small = a[i];
}
if (a[i] > large) {
large = a[i];
}
}
cout << "Smallest is " << small << endl;
cout << "Largest is " << large << endl;
}
You have three loops, two of them run while i<n and the third one while i<=n. And then it uses a[n] item. How do you think what the value of a[n] is?
You were asking:
What is wrong in my code
Let me first answer this question and then we will refactor and optimize it.
So, let's list up the findings
#include<bits/stdc++.h> is non-compliant C++ code. It should never be used. It will run only on selected compilers
using namespace std; should not be used. Always use fully qualified names
C-Style arrays, like a[100000] should not be used in C++. Always use dedicated C++ containers like std::array or std::vector or others. In your case, the size of the array is determined at runtime. So, std::vector must be used
the “100000” is a magic number. Why 100000? Why not 500?. And what happens if the user enters 200000 as array size. Then the program will most likely crash
Use always meaningful variable names. Something like “n” will not be understood. The variable “arraySize” would be understood.
Variables shall always be initialized. And only defined, where they are used and not in the beginning of the program
Input should be verified (cin >> n). What will happen, if the user enters ‘x’ and not ‘5’. Remember, you do not initialize variable n.
large and small must be initialized with the smallest / largest value that the relevant data type can hold. Otherwise the result will always be wrong
array indices start with 0 and not with 1. So, your for loop will fail. The result will be wrong. And you used <=n. So, you will access an out of bounds value.
No need to use endl with cout. ‘\n’ will be sufficient
Then, from the design point of view. You do not need an array at all. You can make all checks immediately, directly after reading the next value.
Anyway, let us make the first step of refactoring. And ths adopted to your programming style. We will
still use C-Style arrays and dynamically allocate the memory
even use raw pointers for owned memory and new. Please note. This should not be done!
correct the bugs
use INT_MIN and INT_MAX
use meaningful variable names and comments
Please see the first refactoring step:
#include <iostream>
#include <climits>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
int* const array = new int[arraySize]();
// Read all values from user into the just allocated array
for (unsigned int index = 0; index < arraySize; ++index) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> array[index])) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = INT_MIN;
int minValueInArray = INT_MAX;
// Iterate over all values and check for min and maximum
for (unsigned int index = 0; index < arraySize; ++index) {
// Compare and assign potential new values
if (array[index] < minValueInArray) minValueInArray = array[index];
if (array[index] > maxValueInArray) maxValueInArray = array[index];
}
// Free the allocated memory. We do not need it any longer
delete [] array;
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
So, next, let’s go a little bit more into the direction C++.
We will get rid of raw pointers, new and will use the correct limit values.
#include <iostream>
#include <limits>
#include <memory>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
std::unique_ptr<int[]> array = std::make_unique<int[]>(arraySize);
// Read all values from user into the just allocated array
for (unsigned int index = 0; index < arraySize; ++index) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> array[index])) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Iterate over all values and check for min and maximum
for (unsigned int index = 0; index < arraySize; ++index) {
// Compare and assign potential new values
if (array[index] < minValueInArray) minValueInArray = array[index];
if (array[index] > maxValueInArray) maxValueInArray = array[index];
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
A little bit better. Now we get rid of the whole manual memory allocation and use a std::vector, which is by far better. And we will use range based for loops, which will make our life simpler:
#include <iostream>
#include <limits>
#include <vector>
int main() {
// Get the array size from the user and validate the input
unsigned int arraySize{};
if ((std::cin >> arraySize) and (arraySize > 0u)) {
// Now, allocate the memory for the array
std::vector<int> data(arraySize, 0);
// Read all values from user into the just allocated array
for (int& value : data) {
// Read value and check, if OK. If not, value will be 0
if (not (std::cin >> value)) std::cerr << "\nError: Wrong value\n";
}
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Iterate over all values and check for min and maximum
for (const int& value : data) {
// Compare and assign potential new values
if (value < minValueInArray) minValueInArray = value;
if (value > maxValueInArray) maxValueInArray = value;
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading array size\n\n";
}
And last but not least, we will get of the whole array/vector stuff. It is not needed.
#include <iostream>
#include <limits>
int main() {
// Get the number of values to check from the user and validate the input
unsigned int numberOfValues{};
if ((std::cin >> numberOfValues) and (numberOfValues > 0u)) {
// Now we set up the result values, always with the opposite maximum/minimum
int maxValueInArray = std::numeric_limits<int>::min();
int minValueInArray = std::numeric_limits<int>::max();
// Read all values from user and check them immediately
for (unsigned int i{}; i<numberOfValues; ++i) {
// Read value and check, if OK. If not, value will be 0
int value{};
if (not (std::cin >> value)) std::cerr << "\nError: Wrong value\n";
// Compare and assign potential new values
if (value < minValueInArray) minValueInArray = value;
if (value > maxValueInArray) maxValueInArray = value;
}
// Show result to user
std::cout << "Smallest is " << minValueInArray << '\n';
std::cout << "Largest is " << maxValueInArray << '\n';
}
else std::cerr << "\nError while reading number of values\n\n";
}
On the third loop it will be
for(int i=0;i<n;i++)
This question already has answers here:
cin >> fails with bigger numbers but works with smaller ones?
(4 answers)
Closed 5 years ago.
I have been following a course about algorithms on Coursera and I tried to put what I learned into code. This is supposed to be a "divide & conquer" algorithm and I hope that part is alright. I have a problem I encountered just messing around with it: everything works fine until I input a 12 digit number into the program. When I do that, it just ends the cin and outputs all the previous numbers sorted (blank space if no numbers are before). If you could, please tell me what's wrong if you spot the mistake. This is my code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
// setup global variable for the number of inversions needed
int inversions = 0;
// function to merge 2 sublists into 1 sorted list
vector<int> Merge_and_Count(vector<int>& split_lo, vector<int>& split_hi) {
// setup output variable -> merged, sorted list of the 2 input sublists
vector<int> out;
int l = 0;
int m = 0;
// loop through all the elements of the 2 sublists
for (size_t k = 0; k < split_lo.size() + split_hi.size(); k++) {
// check if we reached the end of the first sublist
if (l < split_lo.size()) {
// check if we reached the end of the second sublist
if (m < split_hi.size()) {
// check which element is smaller and sort accordingly
if (split_lo[l] < split_hi[m]) {
out.push_back(split_lo[l]);
l++;
}
else if (split_hi[m] < split_lo[l]) {
out.push_back(split_hi[m]);
m++;
inversions++;
}
}
else {
out.push_back(split_lo[l]);
l++;
inversions++;
}
}
else {
out.push_back(split_hi[m]);
m++;
}
}
return out;
}
// function that loops itself to split input into halves until it reaches the base case (1 element array)
vector<int> MergeSort_and_CountInversions(vector<int>& V) {
// if we reached the base case, terminate the loop and feed the output to the previous loop to be processed
if (V.size() == 1) return V;
// if we didn't reach the base case
else {
// continue halving the sublists
size_t const half_size = V.size() / 2;
vector<int> split_lo(V.begin(), V.begin() + half_size);
vector<int> split_hi(V.begin() + half_size, V.end());
// feed them back into the loop
return Merge_and_Count(MergeSort_and_CountInversions(split_lo), MergeSort_and_CountInversions(split_hi));
}
}
// main function of the app, runs everything
int main()
{
// setup main variables
int input;
vector<int> V;
// get input
cout << "Enter your numbers to be sorted (enter Y when you wish to proceed to the sorting)." << endl;
cout << "Note: do NOT use duplicates (for example, do not input 1 and 1 again)!" << endl;
while (cin >> input)
V.push_back(input);
cout << "\nThe numbers you chose were: " << endl;
for (size_t i = 0; i < V.size(); i++)
cout << V[i] << " ";
// get sorted output
vector<int> sorted = MergeSort_and_CountInversions(V);
cout << "\n\nHere are your numbers sorted: " << endl;
for (size_t j = 0; j < sorted.size(); j++)
cout << sorted[j] << " ";
// show number of inversions that were needed
cout << "\n\nThe number of inversions needed were: " << inversions << endl;
return 0;
}
12 decimal digits is too long to fit into a 32-bit number, which is how int is usually represented. Reading that number using >> therefore fails and cin >> input converts to a false value, which terminates the loop.
See operator >> documentation for details of handling failure modes.
You can get the maximum number of base-10 digits that can be represented by the type using the std::numeric_limits::digits10 constant:
std::cout << std::numeric_limits<int>::digits10 << '\n';
Chances are the maximum number of significant digits for type int is 9, and you try to supply 12 via standard input. The program doesn't crash, the condition of (cin >> input) simply evaluates to false.
12 digits is too much for 32-bit integer, try to use as unsigned long long int, check these limits:
http://www.cplusplus.com/reference/climits/
The assignment requires three functions. The user enters digits 0-9 until they enter a 10, which stops input, and counts each number, then outputs how many of each number has been counted. It should only output if the user entered a number for it.
My only problem is that for every element in the array that the user doesn't use, Xcode counts it as a 0, so the final output has an abnormally large amount of zeros. Everything else works fine.
here is my code
#include <iostream>
using namespace std;
// counter function prototype
void count(int[], int, int []);
// print function prototype
void print(int []);
int main()
{
// define variables and initialize arrays
const int SIZE=100;
int numbers[SIZE], counter[10], input;
// for loop to set all counter elements to 0
for (int assign = 0; assign < 10; assign++)
{
counter[assign]=0;
}
// for loop to collect data
for (int index=0 ; input != 10 ; index++)
{
cout << "Enter a number 0-9, or 10 to terminate: ";
cin >> input;
// while loop to ensure input is 0-10
while (input < 0 || input > 10)
{
cout << "Invalid, please enter 0-9 or 10 to terminate: ";
cin >> input;
}
// if statements to sort input
if (input >= 0 && input <=9)
{
numbers[index] = input;
}
}
// call count function
count(numbers, SIZE, counter);
// call print function
print(counter);
return 0;
}
// counter function
void count(int numbers[], int SIZE, int counter[])
{
// for loop of counter
for (int index = 0 ; index < 10 ; index++)
{
// for loop of numbers
for (int tracker=0 ; tracker < SIZE ; tracker++)
{
// if statement to count each number
if (index == numbers[tracker])
{
counter[index]++;
}
}
}
return;
}
// print function
void print(int counter[])
{
// for loop to print each element
for (int index=0 ; index < 10 ; index++)
{
// if statement to only print numbers that were entered
if (counter[index] > 0)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
}
return;
}
What you're referring to as "XCode count[ing] as a 0" is actually just the uninitialized value. Given that you've decided to restrict the user's input to 0-9, an easy way of solving this dilemma would be, immediately after you size the array, to iterate through the array and set each value to -1.
Thereafter, when the user finishes their input, instead of just couting every single value, only print it with a conditional like the following:
if (counter[index] != -1)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
Note that this is the kind of use case that's much better suited to something like a linked list or a vector. As it stands, you're not doing anything to resize the array, or guard against overflow, so if the user attempts to enter more than 100 numbers, you'll run into serious problems.
First off, this isn't an answer to your exact question, but rather a suggestion on how to write your code in a much simpler form.
I'm not going to write this for you, as it's an assignment, and a rather simple one. Looks like you have a good handle on things as far as coding goes.
Consider this:
You need to allow the user to enter 0-10, and count all 0-9's. An array has indices, and a integer of array 10, would hold those 10 numbers you're counting by the indices. Now you just have some empty ints sitting around, so why not use them to count?
A code hint:
++numbers[input];
Second hint: Don't forget to initialize everything to zero.
I have been working on this all day but just cant get the output right.
What I want to do is input two numbers, which would be pushed into two arrays so we can subtract or add them and display the result. Seems simple, but there are few catches
Input must be pushed into the array, from the user, one by one.
In case I don't enter a value, code should assume it to be '0' or 'null'. '0' if its in the beginning and 'null' if its in the end. for example if 1st number is 234 and second number is 23 then code should make it into '023' and if I enter first number as 2, 2nd number as 3 but don't enter anything in the end then code should assume it to be null.
Problems
I cant take 'carry' to the next set, in case the sum is greater than 10. Which means the value I m getting is just addition of two numbers doesn't matter if its greater than 10 or not. for example addition of 234 and 890 is giving me [10, 12, 4]
Here is the code.....
#include<iostream>
using namespace std;
main() {
int first[10], second[10], result[10], c, n;
cout << "Enter the number of elements in the array ";
cin >> n;
if (n > 10 || n < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
cout << "Enter elements of first array " << endl;
for (c = 0; c < n; c++) {
cin >> first[c];
if (first[c] > 9 || first[c] < 0) {
std::cout << "invalid number, you are a bad reader" << endl;
system("PAUSE");
return 0;
}
}
cout << "Enter elements of second array " << endl;
for (c = 0; c < n; c++)
cin >> second[c];
cout << "Sum of elements of two arrays " << endl;
for (c = 0; c < n; c++)
cout << first[c] + second[c] << endl;
if ((first[c] + second[c]) > 9) {
cout << "overflow" << endl;
}
//result[c] = first[c] + second [c];
//cout << result[c] <<endl;
system("PAUSE");
return 0;
}
I would really appreciate some suggestions.
In case your intention is to have the result of e.g.
234 + 890 = 1124
then your summation loop should be in reverse order.
(Since you are reading number of elements of the array from the prompt, you may use this information to input first/second numbers into each array in the order preferred for the following summation loop.)
For the carry problem, you need to setup a variable and use it in the loop like this, for example.
int sum[10] = {0};
int c;
int carry = 0;
for (c = 0; c < n; c++)
{
sum[c] = first[c] + second[c] + carry;
carry = sum[c] / 10;
}
if (c < n)
sum[c] = carry;
else
cout << "overflow";
Use std::vector and learn how to use reverse iterators. So if someone enters 234 you push_back(2), push_back(3), push_back(4) and have [0]=2,[1]=3,[2]=4. Then if the next number is 23 you have [0]=2,[1]=3. Now walk both vector with reverse iterators so the first call to rbegin() will give a pointer to [2]=4 and the other vector will give [1]=3. Now add and carry using push_back into a third vector to store the result. Output the result using reverse iterators to print the result.
This looks like homework, so no sample code.