Addition and subtraction of arrays - c++

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.

Related

Garbage values are being output in 2D Arrays [duplicate]

I got this output
Learning how to use arrays and I got an exercise to check if the array is in an ascending order, after the first run, this is what I got and I cant find the problem.
when I'm printing the array it shows in the last array some garbage.
#include <iostream>
using namespace std;
const int CAPACITY1 = 5;
int main()
{
int arr1[CAPACITY1];
bool a = false;
//init the first input
cout << "Enter 6 numbers: " << endl;
cin >> arr1[0];
int max = arr1[0];
int NoE = 1;
//init the loop to insert numbers
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
if (a == true)
cout << "The array is not in an ascending order" << endl;
else
cout << "The array is in an ascending order" << endl;
cout << NoE;
//end
cout << endl;
return 0;
}
Indexes in arrays in C++ are zero based. That means, that array with capacity of N, declared as T arr[N], have indexes starting at 0 and ending with N - 1.
For accessing such array using for loop, use this
for (int index = 0; index < N; ++index)
Your loop here operates from 1 to 5:
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
So you only enter five numbers and you never put anything in arr1[0] and you do put something in arr[5] which is invalid.
Aside from that, I suspect you may have missed the point of the exercise. If this is a homework assignment then I imagine they want you to iterate over an existing array and report if it is in ascending order.
Your for loop is wrong, and is going out of bounds.Note that arrays in C++ start at 0, not 1. The correct for loop is as follows:
for (int i = 0; i < CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
These 2 lines:
int CAPACITY1 = 5;
int arr1[CAPACITY1];
mean that the size of your array arr1 is 5, that is, it has 5 elements, from 0 to 4. Trying to access the element at position 5 is wrong.
That said, in your cout messages you talk about 6 numbers. If you want to store 6 elements, change the value of CAPACITY1 to 6, like:
const int CAPACITY1 = 6;
By your comments I think you are getting confused with the size of the array, possibly because you have heard something like "The index of the last element is always off by 1". Yes it is, but it doesn't mean that to store 6 elements you should use the number 5 when you define it! If you want 6 elements, the size must be 6, there is no trap here. The tricky part is that the index will start from 0, and therefore the last element is at position [size - 1], not at [size]. To clarify:
If you declare int arr1[5]; you will have 5 elements, with the index ranging from 0 to 4.
If you declare int arr1[6]; you will have 6 elements, with the index ranging from 0 to 5.
By the way, this shows why it would be a good idea to avoid hard-coded numbers (6, in this case) and always use variables. Try with
cout << "Enter " << CAPACITY1 << " numbers: " << endl;
This way, the size of the array and the messages will always match.
To summarize, if you want to work with 6 numbers, you need to use
const int CAPACITY1 = 6;
and, since you deal with the first element (at index 0) before the loop, the loop must start at 1 and run until the last element, which has index 5, so:
for (int i = 1; i < CAPACITY1; i++) {
On a side note, your logic to check whether the array is in ascending order is confusing. For you, a == true means it is not ascending. It works, but it is counter-intuitive. I would suggest to change it.

Counting occurences of same array value in C++

I recently have been building a program where:
A user is asked to enter a number that will represent the size of a character array.
Then they are asked whether they will want the program to fill the values automatically, or they could press M so they could enter the values manually. They may only enter a-zA-Z values, or they will see an error.
At the end of the program, I am required to count every duplicate value and display it, for example:
An array of 5 characters consists of A;A;A;F;G;
The output should be something like:
A - 3
F - 1
G - 1
I could do this easily, however, the teacher said I may not use an additional array, but I could make a good use of a few more variables and I also can't use a switch element. I'm totally lost and I can't find a solution. I've added the code down below. I have done everything, but the counting part.
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
void main() {
int n, i = 0;
char masiva_izvele, array[100], masiva_burts;
cout << "Enter array size: ";
cin >> n;
clrscr();
cout << "You chose an array of size " << n << endl;
cout << "\nPress M to enter array values manually\nPress A so the program could do it for you.\n\n";
cout << "Your choice (M/A): ";
cin >> masiva_izvele;
if (masiva_izvele == 'M' || masiva_izvele == 'm') {
clrscr();
for (i = 0; i < n; i++) {
do {
cout << "Enter " << i + 1 << " array element: ";
flushall();
cin >> masiva_burts;
cout << endl << int(masiva_burts);
if (isalpha(masiva_burts)) {
clrscr();
array[i] = masiva_burts;
}
else {
clrscr();
cout << "Unacceptable value, please enter a value from the alphabet!\n\n";
}
}
while (!isalpha(masiva_burts));
}
}
else if (masiva_izvele == 'A' || masiva_izvele == 'a') {
clrscr();
for (i = 0; i < n; i++) {
array[i] = rand() % 25 + 65;
}
}
clrscr();
cout << "Masivs ir izveidots! \nArray size is " << n <<
"\nArray consists of following elements:\n\n";
for (i = 0; i < n; i++) {
cout << array[i] << "\t";
}
cout << "\n\nPress any key to view the amount of every element in array.";
//The whole thing I miss goes here, teacher said I would need two for loops but I can't seem to find the solution.
getch();
}
I would be very thankful for a solution so I could move on and forgive my C++ amateur-ness as I've picked this language up just a few days ago.
Thanks.
EDIT: Edited title to suit the actual problem, as suggested in comments.
One possible way is to sort the array, and then iterate over it counting the current letter. When the letter changes (for example from 'A' to 'F' as in your example) print the letter and the count. Reset the counter and continue counting the next character.
The main loop should run foreach character in your string.
The secondary loop should run each time the main "passes by" to check if the current letter is in array. If it's there, then ++.
Add the array char chars[52] and count chars in this array. Then print out chars corresponding to the array, which count is more than 1.
std::unordered_map<char, int> chars;
...
char c = ...;
if ('A' <= c && c <= 'Z')
++chars[c];
else if ('a' <= c && c <= 'z')
++chars[c];
else
// unexpected char
...
for (const auto p : chars)
std::cout << p.first << ": " << p.second << " ";
Assuming upper and lower case letters are considered to be equal (otherwise, you need an array twice the size as the one proposed:
std::array<unsigned int, 26> counts; //!!!
// get number of characters to read
for(unsigned int i = 0; i < charactersToRead; ++i)
{
char c; // get a random value or read from console
// range check, calculate value in range [0; 25] from letter...
// now the trick: just do not store the value in an array,
// evaluate it d i r e c t l y instead:
++counts[c];
}
// no a d d i t i o n a l array so far...
char c = 'a';
for(auto n : counts)
{
if(n > 0) // this can happen now...
{
// output c and n appropriately!
}
++c; // only works on character sets without gaps in between [a; z]!
// special handling required if upper and lower case not considered equal!
}
Side note: (see CiaPan's comment to the question): If only true duplicates to be counted, must be if(n > 1) within last loop!

Vector: range error at memory

I have been programming a bit with C++ in CodeBloks before and since some time i started to program in MS Studio. At the moment im programming a little game from the book: Programming: Principles and Practice using C++. Exercise 12 of chapter 5.
I have been looking around on the internet to fix the range memory error which keeps occuring whatever I try (see printscreen link).
The description about the program is in the code itself.
I also did make the vectors a hard coded (if I say that right) size to make the program stop complaining about their memory range errors.
Note: Yes this is a school exercise/practice as well. But I rather ask what I did wrong then copy paste the code from the internet..
Please look over my code and see or I made some mistake with me vectors, cause that is where my errors are probably comming from.
Update: placed as answer in this topic.
Link to update
Error:
Unhandled exception at 0x7529CBC2 in Tweede project.exe: Microsoft C++ exception: Range_error at memory location 0x006FF510.
Program:
#include "std_lib_facilities.h"
int main(){
bool while_bit = false;
vector<int>bulls_cows(4);
vector<int>inputs_arr(4);
//Generate 4 random numbers.
for (int a = 0; a < 4; ++a){
bulls_cows[a] = a + 1;//randint(a) % 9 + 0; //random number between 0 and 9.
}
//bulls_cows[1] = randint(10);
cout << "For this game, called Bulls and Cows, you have to guess the four right numbers between 0 and 9.\n";
cout << "When one or more digets are right and in the right position the program will say the number of Bulls.\n";
cout << "When one or more digets are right but not in the right position the program will say the number of Cows.\n";
cout << "Please enter 4 number by filling in ONE positive diget and press enter. Do this four times and wait for the result.\n";
for (int z = 0; z < 4; ++z) {
cout << bulls_cows[z] << "\n";
}
while (while_bit == false) {
int input = 0; //Reset of input, cows and bulls every round.
int cows = 0;
int bulls = 0;
cin >> input;
//Test for legit input. If legit then it writes it to the array called "input_arr"
if (input < 0 || input > 9) {
cout << "Number must be between 0 and 9.\n";
}
else {
inputs_arr.push_back(input);
}
//Check or 4 numbers have been given.
if (sizeof(inputs_arr) < 4) {
//Check for equal numbers on same spot.
for (int b = 0; b < 4; ++b) {
if (inputs_arr[b] == bulls_cows[b]) {
bulls + 1;
}
}
//Check for a number in all spots.
for (int c = 0; c < 4; ++c) {
if (inputs_arr[c] == bulls_cows[0] || bulls_cows[1] || bulls_cows[2] || bulls_cows[3]) {
cows +1;
}
}
}
if (bulls < 4) {
cout << "You did not guess the right combination.\n";
cout << "Number of bulls: " << bulls << "\n";
cout << "Number of cows: " << cows << "\n";
inputs_arr[0, 0, 0, 0]; //Empty array.
}
if (bulls == 4) {
cout << "You guessed the right combination!\n";
while_bit = true;
}
}
keep_window_open(); //To keep terminal open since MS Studio doesn't itself.
return 0;
}
Using the sizeof operator with your inputs_array vector will give you the size in bytes of that object in memory. Perhaps you've used this with arrays before.
Instead, I think you want the number of items you've pushed into the vector. std::vector has a function called size which gives the number of items pushed to it.
In Visual Studio you should really, really set up the warning level to level 4. Then the compiler will tell you about several of the odd things you try to do.
For example:
warning C4552: '+': operator has no effect; expected operator with side-effect 1>
bulls + 1;
You compute a result, but never store it anywhere. Same thing for the cows.
error C4548: expression before comma has no effect; expected expression with side-effect
inputs_arr[0, 0, 0, 0]; //Empty array.
This is not the way to empty an array. To remove all elements, you do inputs_arr.clear();.
warning C4127: conditional expression is constant
if (sizeof(inputs_arr) < 4) {
Like we have already seen, sizeof is the size of the vector object (always the same), not the number of elements it holds.
Then there are some logic errors.
vector<int>inputs_arr(4);
This creates a vector originally holding 4 ints.
But later when you do
inputs_arr.push_back(input);
it adds more elements to the vector, so now it might hold up to 8 ints. You have to decide if you want to create it with the full size up front, or add elements as you go along. But not both.
Another problem is with the condition
if (inputs_arr[c] == bulls_cows[0] || bulls_cows[1] || bulls_cows[2] || bulls_cows[3]) {
Even though there are languages where you can write conditions similar to this, in C++ you cannot. To compare a variable x to several other values, you have to spell it out:
if (x == y || x == z || x == w)
Update: (wasn't sure or I had to add it to the question or as answer. If wrong, please let me know. Im new to Stack overflow ;) )
It seems some statement/loop brackets where not placed right. I edit that and a bit:
Sadly it seems that my intergers cows and bulls do not reset at line 61 and 62.. Anyone a idea what I might have done wrong there.
LOG:
cin did not not loop. Also edited else-statement 'inputs_arr.pushback(input)' and added all for-loops and statements below it. Fixed a part of the cin problem.
Replaced bulls, cows and input integers to top of program, and the reset at the end of the false/if-statement.
Put all loops and statements below the if-statement '(int b = 0; b < 4; ++b)' into it.
Edited the for-loop to >4 which couts "Size of array" to see what values it has. Gets deleted later on cause it is for test only.
#include "std_lib_facilities.h"
int main()
{
bool while_bit = false;
int input = 0;
int cows = 0;
int bulls = 0;
vector<int> bulls_cows(4); //size needed to prevent memory size error at line 11.
vector<int> inputs_arr;
//Generate 4 random numbers. Need to add seed later.
for (int a = 0; a < 4; ++a){
bulls_cows[a] = randint(a) % 9 + 0; //random number between 0 and 9.
}
cout << "For this game, called Bulls and Cows, you have to guess the four right numbers between 0 and 9.\n";
cout << "When one or more digets are right and in the right position the program will say the number of Bulls.\n";
cout << "When one or more digets are right but not in the right position the program will say the number of Cows.\n";
cout << "Please enter 4 numbers by filling in ONE positive diget and press enter. Do this four times and wait for the result.\n";
for (int z = 0; z < 4; ++z) { //Gives the generated numbers for testing.
cout << bulls_cows[z] << "\n";
}
while (while_bit == false) {
cin >> input;
//Test for legit input. If legit then it writes it to the array called "input_arr"
if (input < 0 || input > 9) {
cout << "Number must be between 0 and 9.\n";
}
else {
inputs_arr.push_back(input);
//Check or 4 numbers have been given.
if (inputs_arr.size() > 3) {
//Check for equal numbers on same spot.
for (int b = 0; b < 4; ++b) {
if (inputs_arr[b] == bulls_cows[b]) {
++bulls;
}
}
//Check for a number in all spots.
for (int c = 0; c < 4; ++c) {
if (inputs_arr[c] == bulls_cows[0] || inputs_arr[c] == bulls_cows[1] || inputs_arr[c] == bulls_cows[2] || inputs_arr[c] == bulls_cows[3]) {
++cows;
}
}
/*for (int x = 0; x < 4; ++x) { //Couts again the fresh entered numbers for a better overview.
cout << "Size of array: " << inputs_arr[x] << "\n";
}*/
if (bulls < 4) {
cout << "You did not guess the right combination.\n";
cout << "Number of bulls: " << bulls << "\n";
cout << "Number of cows: " << cows << "\n";
int cows = 0; //Reset of cows and bulls each round.
int bulls = 0;
inputs_arr.clear(); //Empty the array.
cout << "Please enter 4 numbers:\n";
}
if (bulls == 4) {
cout << "You guessed the right combination!\n";
while_bit = true;
}
}
}
}
keep_window_open(); //To keep terminal open since MS Studio doesn't itself.
return 0;
}

Why does the following code crash when I input a 12 digit number? [duplicate]

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/

Array last element automatically gets garbage

I got this output
Learning how to use arrays and I got an exercise to check if the array is in an ascending order, after the first run, this is what I got and I cant find the problem.
when I'm printing the array it shows in the last array some garbage.
#include <iostream>
using namespace std;
const int CAPACITY1 = 5;
int main()
{
int arr1[CAPACITY1];
bool a = false;
//init the first input
cout << "Enter 6 numbers: " << endl;
cin >> arr1[0];
int max = arr1[0];
int NoE = 1;
//init the loop to insert numbers
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
if (a == true)
cout << "The array is not in an ascending order" << endl;
else
cout << "The array is in an ascending order" << endl;
cout << NoE;
//end
cout << endl;
return 0;
}
Indexes in arrays in C++ are zero based. That means, that array with capacity of N, declared as T arr[N], have indexes starting at 0 and ending with N - 1.
For accessing such array using for loop, use this
for (int index = 0; index < N; ++index)
Your loop here operates from 1 to 5:
for (int i = 1; i <= CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
So you only enter five numbers and you never put anything in arr1[0] and you do put something in arr[5] which is invalid.
Aside from that, I suspect you may have missed the point of the exercise. If this is a homework assignment then I imagine they want you to iterate over an existing array and report if it is in ascending order.
Your for loop is wrong, and is going out of bounds.Note that arrays in C++ start at 0, not 1. The correct for loop is as follows:
for (int i = 0; i < CAPACITY1; i++) {
cout << "Enter 6 numbers: " << endl;
cin >> arr1[i];
NoE++;
//check if input is bigger than max
if (arr1[i] > max)
max = arr1[i];
else
a = true;
}
These 2 lines:
int CAPACITY1 = 5;
int arr1[CAPACITY1];
mean that the size of your array arr1 is 5, that is, it has 5 elements, from 0 to 4. Trying to access the element at position 5 is wrong.
That said, in your cout messages you talk about 6 numbers. If you want to store 6 elements, change the value of CAPACITY1 to 6, like:
const int CAPACITY1 = 6;
By your comments I think you are getting confused with the size of the array, possibly because you have heard something like "The index of the last element is always off by 1". Yes it is, but it doesn't mean that to store 6 elements you should use the number 5 when you define it! If you want 6 elements, the size must be 6, there is no trap here. The tricky part is that the index will start from 0, and therefore the last element is at position [size - 1], not at [size]. To clarify:
If you declare int arr1[5]; you will have 5 elements, with the index ranging from 0 to 4.
If you declare int arr1[6]; you will have 6 elements, with the index ranging from 0 to 5.
By the way, this shows why it would be a good idea to avoid hard-coded numbers (6, in this case) and always use variables. Try with
cout << "Enter " << CAPACITY1 << " numbers: " << endl;
This way, the size of the array and the messages will always match.
To summarize, if you want to work with 6 numbers, you need to use
const int CAPACITY1 = 6;
and, since you deal with the first element (at index 0) before the loop, the loop must start at 1 and run until the last element, which has index 5, so:
for (int i = 1; i < CAPACITY1; i++) {
On a side note, your logic to check whether the array is in ascending order is confusing. For you, a == true means it is not ascending. It works, but it is counter-intuitive. I would suggest to change it.