Unable to get desired output for the problem - c++

I am trying to solve a problem here. I have two arrays which needs to be added and produce a desired output. {'A','A','A','B','A','X','M'} and {'A', 'B', 'A', 'A', 'B', 'A', 'B', 'B'}. Value of A is 10 and B is 20.
If A or B are repeated consecutively then the bonus numbers are added which is 10. I need to get an output of total score of 90 for first and 140 for second. How Can I write the perfect code.
My Code here is as below: The output should be 90 for the first array and 140 for a second. X and M have 0 value. SO don't mind them.
Here First character in array is A so score is 10
Second is also A so now 10 for A and as the previous was A so 10+10 = 20
Now as third one is also A add another 10 to previous score as 10 + 20(as last two were two as well ) ie. 30
Now fourth element in array is B so its not A and Streak is Broken so add Score For B which is set as 20
For Fifth Element we have A but as previous was Blue so no streak bonus and score of A was reset so add 10 now
Add 0 for X and M element
hence total score is 10+20+30+20+10 = 90
#include <iostream>
int main()
{
int currentEScore = 0;
int TotalScore = 0;
char Box[] = { 'A', 'A', 'A', 'B', 'A', 'X', 'M' };
// A B A R A R A A
for (int i = 0; i < Box[i]; i++) {
if (Box[i] == 'A') {
currentEScore = 10;
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
TotalScore = TotalScore + currentEScore;
}
else {
TotalScore = TotalScore + currentEScore;
}
}
else if (Box[i] == 'B') {
currentEScore = 20;
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
TotalScore = TotalScore + currentEScore;
}
else {
TotalScore = TotalScore + currentEScore;
}
}
else {
currentEScore = 0;
}
}
std::cout << TotalScore;
}

First things first: You are accessing the array out-of-bounds in the first iteration (if (Box[i - 1] == Box[i])). That is undefined behavior and strictly speaking all your code is meaningless, because a compiler is not mandated to do anything meaningful with invalid code. It just happens that this does not affect the outcome of your code. This is the worst incarnation of undefined behavior: It appears to work. You need to fix that.
Next, your loop reads for (int i = 0; i < Box[i]; i++) { and the condition cannot be correct. Again this makes your loop access the array out-of-bounds. I am a bit puzzled how this worked (I didnt realize it myself first). This also has to be fixed! I suggest to use a std::string for character arrays. It is much less error prone and it has a size() method to get its size.
The above issues didn't affect the output (nevertheless they have to be fixed!), so now lets look at the logic of your code. But first a disclaimer: Really the best advice I can give you is to not continue reading this answer. The problem you are facing is a good opportunity to learn how to use a debugger. That is a skill you will need always. If you still decide to read the following, then at least you should try to forget everything this answers says and go trough the same process on your own, by either using a debugger or a piece of paper and a pen.
Lets go step by step in your first example { 'A', 'A', 'A', 'B', 'A', 'X', 'M' }
first character is A
if (Box[i] == 'A') -> condition is true
currentEScore = 10; -> currentEScoe == 10
(we ignore the out-of-bounds for a moment)
TotalScore = TotalScore + currentEScore; -> TotalScore == 10
next character is A
if (Box[i] == 'A') -> condition is true
currentEScore = 10; -> currentEScore == 10
if (Box[i - 1] == Box[i]) -> yes
currentEScore += 10; -> currentEScore == 20
TotalScore = TotalScore + currentEScore; -> TotalScore == 10+20 == 30
next character is A
if (Box[i] == 'A') -> condition is true
currentEScore = 10; -> currentEScore == 10 -> stop... this is wrong !
You are resetting the bonus score on each character and then only check for the previous one. The effect is that you never give bonus more than 20.
Solution: Fix the out-of-bounds access and only reset the bonus when the character is different from the last. Also the code can be simplified a bit, by realizing that the bonus is indepenent from whether the character is A or B. You only have to check if it is the same as the last, hence calculating the bonus and adding points for A and B can be done seperately:
#include <iostream>
#include <string>
int main()
{
int bonus_increment = 10;
int bonus = 0;
int score_A = 10;
int score_B = 20;
int TotalScore = 0;
std::string Box{"AAABAXM"};
for (size_t i = 0; i < Box.size(); i++) {
// determine bonus
if ( i > 0 && Box[i] == Box[i-1] ) {
bonus += bonus_increment;
} else {
bonus = 0;
}
// accumulate score
if (Box[i] == 'A') {
TotalScore += score_A + bonus;
} else if (Box[i] == 'B') {
TotalScore += score_B + bonus;
}
}
std::cout << TotalScore;
}
Don't forget what I said above. You waste this exercise if you simply copy this code and assume that you completed the exercise by doing so.

Here's I have made some changes with your code with minimal optimization.
It'll work for you. Please check it and let me know it's working or not.
#include <iostream>
int main()
{
int currentEScore = 0;
int TotalScore = 0;
char Box[] = {'A','A','A','B','A','X','M'};
// A B A R A R A A
for (int i = 0; i < Box[i]; i++) {
if (Box[i] == 'A') {
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
}
else {
currentEScore = 10;
}
}
else if (Box[i] == 'B') {
if (Box[i - 1] == Box[i]) {
currentEScore += 10;
}
else {
currentEScore = 20;
}
}
else {
currentEScore = 0;
}
TotalScore = TotalScore + currentEScore;
}
std::cout << TotalScore;
}

Related

Roman Numerals to Arabic (vinculum) - reading characters in a string

I am currently working on a project that converts Roman Numerals to Arabic Numbers and vice versa.
I am also responsible to implement concepts like vinculum, where if you put a bar on top of a Roman numeral, the numbers below will be multiplied by 1,000.
The problem I am having is I can get only one side working, meaning:
I can either just convert from Roman Numeral to Arabic without Vinculum:
ex. I = 1, II = 2
However, when this works my vinculum code does not work.
Here is a snippet of my code:
int romanToDecimal(char input[], size_t end) {
int roman = 0;
int vroman = 0;
for (int i = 0; i < strlen(input); ++i)
{
int s1 = value(input[i]);
int s2 = value(input[i]);
if (input[i] == '-')
{
for (int j = i - 1; j >= 0; --j)
{
roman = (roman + value(input[j]));
}
roman *= 1000;
for (int k = i + 1; k <= strlen(input); k++)
roman += value(input[k]);
}
else
roman += s1;
}
return roman;
}
We use '-' instead of the bar on top of the characters, because we cannot do that in computer easily. So IV-, would be 4000 and XI- would be 11,000 etc...
I understand that the way I am doing the loop is causing some numbers that were converted to add twice, because if(input[i] == '-') cycles through each character in the string one at a time.
OK, so my question is basically what is the logic to get it to work? So if the string contains '-' it will multiply the number by 1000, if the string does not contain '-' at ALL, then it will just convert as normal. Right now I believe what is happening is that when "if (input[i] == '-')" is false, that part of the code still runs, how do I not get it to run at all when the string contains '-'??
The posted code seems incomplete or at least has some unused (like end, which if it represents the length of string could be used in place of the following repeated strlen(input)) or meaningless (like s2) variables.
I can't understand the logic behind your "Vinculum" implementation, but the simple
roman += s1; // Where s1 = value(input[i]);
It's clearly not enough to parse a roman number, where the relative position of each symbol is important. Consider e.g. "IV", which is 4 (= 5 - 1), vs. "VI", which is 6 (= 5 + 1).
To parse the "subtractive" notation, you could store a partial result and compare the current digit to the previous one. Something like the following:
#include <stdio.h>
#include <string.h>
int value_of(char ch);
long decimal_from_roman(char const *str, size_t length)
{
long number = 0, partial = 0;
int value = 0, last_value = 0;
for (size_t i = 0; i < length; ++i)
{
if (str[i] == '-')
{
number += partial;
number *= 1000;
partial = 0;
continue;
}
last_value = value;
value = value_of(str[i]);
if (value == 0)
{
fprintf(stderr, "Wrong format.\n");
return 0;
}
if (value > last_value)
{
partial = value - partial;
}
else if (value < last_value)
{
number += partial;
partial = value;
}
else
{
partial += value;
}
}
return number + partial;
}
int main(void)
{
char const *tests[] = {
"I", "L", "XXX", "VI", "IV", "XIV", "XXIII-",
"MCM", "MCMXII", "CCXLVI", "DCCLXXXIX", "MMCDXXI", // 1900, 1912, 246, 789, 2421
"CLX", "CCVII", "MIX", "MLXVI" // 160, 207, 1009, 1066
};
int n_samples = sizeof(tests) / sizeof(*tests);
for (int i = 0; i < n_samples; ++i)
{
long number = decimal_from_roman(tests[i], strlen(tests[i]));
printf("%12ld %s\n", number, tests[i]);
}
return 0;
}
int value_of(char ch)
{
switch (ch)
{
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
Note that the previous code only checks for wrong characters, but doesn't discard strings like "MMMMMMMMMMIIIIIIIIIIIIIV". Consider it just a starting point and feel free to improve it.

What's wrong with my dynamic programming algorithm with memoization?

*Sorry about my poor English. If there is anything that you don't understand, please tell me so that I can give you more information that 'make sence'.
**This is first time asking question in Stackoverflow. I've searched some rules for asking questions correctly here, but there should be something I missed. I welcome all feedback.
I'm currently solving algorithm problems to improve my skill, and I'm struggling with one question for three days. This question is from https://algospot.com/judge/problem/read/RESTORE , but since this page is in KOREAN, I tried to translate it in English.
Question
If there are 'k' pieces of partial strings given, calculate shortest string that includes all partial strings.
All strings consist only lowercase alphabets.
If there are more than 1 result strings that satisfy all conditions with same length, choose any string.
Input
In the first line of input, number of test case 'C'(C<=50) is given.
For each test case, number of partial string 'k'(1<=k<=15) is given in the first line, and in next k lines partial strings are given.
Length of partial string is between 1 to 40.
Output
For each testcase, print shortest string that includes all partial strings.
Sample Input
3
3
geo
oji
jing
2
world
hello
3
abrac
cadabra
dabr
Sample Output
geojing
helloworld
cadabrac
And here is my code. My code seems to work perfect with Sample Inputs, and when I made test inputs for my own and tested, everything worked fine. But when I submit this code, they say my code is 'wrong'.
Please tell me what is wrong with my code. You don't need to tell me whole fixed code, I just need sample inputs that causes error with my code. Added code description to make my code easier to understand.
Code Description
Saved all input partial strings in vector 'stringParts'.
Saved current shortest string result in global variable 'answer'.
Used 'cache' array for memoization - to skip repeated function call.
Algorithm I designed to solve this problem is divided into two function -
restore() & eraseOverlapped().
restore() function calculates shortest string that includes all partial strings in 'stringParts'.
Result of resotre() is saved in 'answer'.
For restore(), there are three parameters - 'curString', 'selected' and 'last'.
'curString' stands for currently selected and overlapped string result.
'selected' stands for currently selected elements of 'stringParts'. Used bitmask to make my algorithm concise.
'last' stands for last selected element of 'stringParts' for making 'curString'.
eraseOverlapped() function does preprocessing - it deletes elements of 'stringParts' that can be completly included to other elements before executing restore().
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#define MAX 15
using namespace std;
int k;
string answer; // save shortest result string
vector<string> stringParts;
bool cache[MAX + 1][(1 << MAX) + 1]; //[last selected string][set of selected strings in Bitmask]
void restore(string curString, int selected=0, int last=0) {
//base case 1
if (selected == (1 << k) - 1) {
if (answer.empty() || curString.length() < answer.length())
answer = curString;
return;
}
//base case 2 - memoization
bool& ret = cache[last][selected];
if (ret != false) return;
for (int next = 0; next < k; next++) {
string checkStr = stringParts[next];
if (selected & (1 << next)) continue;
if (curString.empty())
restore(checkStr, selected + (1 << next), next + 1);
else {
int check = false;
//count max overlapping area of two strings and overlap two strings.
for (int i = (checkStr.length() > curString.length() ? curString.length() : checkStr.length())
; i > 0; i--) {
if (curString.substr(curString.size()-i, i) == checkStr.substr(0, i)) {
restore(curString + checkStr.substr(i, checkStr.length()-i), selected + (1 << next), next + 1);
check = true;
break;
}
}
if (!check) { // if there aren't any overlapping area
restore(curString + checkStr, selected + (1 << next), next + 1);
}
}
}
ret = true;
}
//check if there are strings that can be completely included by other strings, and delete that string.
void eraseOverlapped() {
//arranging string vector in ascending order of string length
int vectorLen = stringParts.size();
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].length() < stringParts[j].length()) {
string temp = stringParts[i];
stringParts[i] = stringParts[j];
stringParts[j] = temp;
}
}
}
//deleting included strings
vector<string>::iterator iter;
for (int i = 0; i < vectorLen-1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].find(stringParts[j]) != string::npos) {
iter = stringParts.begin() + j;
stringParts.erase(iter);
j--;
vectorLen--;
}
}
}
}
int main(void) {
int C;
cin >> C; // testcase
for (int testCase = 0; testCase < C; testCase++) {
cin >> k; // number of partial strings
memset(cache, false, sizeof(cache)); // initializing cache to false
string inputStr;
for (int i = 0; i < k; i++) {
cin >> inputStr;
stringParts.push_back(inputStr);
}
eraseOverlapped();
k = stringParts.size();
restore("");
cout << answer << endl;
answer.clear();
stringParts.clear();
}
}
After determining which string-parts can be removed from the list since they are contained in other string-parts, one way to model this problem might be as the "taxicab ripoff problem" problem (or Max TSP), where each potential length reduction by overlap is given a positive weight. Considering that the input size in the question is very small, it seems likely that they expect a near brute-force solution, with possibly some heuristic and backtracking or other form of memoization.
Thanks Everyone who tried to help me solve this problem. I actually solved this problem with few changes on my previous algorithm. These are main changes.
In my previous algorithm I saved result of restore() in global variable 'answer' since restore() didn't return anything, but in new algorithm since restore() returns mid-process answer string I no longer need to use 'answer'.
Used string type cache instead of bool type cache. I found out using bool cache for memoization in this algorithm was useless.
Deleted 'curString' parameter from restore(). Since what we only need during recursive call is one previously selected partial string, 'last' can replace role of 'curString'.
CODE
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#define MAX 15
using namespace std;
int k;
vector<string> stringParts;
string cache[MAX + 1][(1 << MAX) + 1];
string restore(int selected = 0, int last = -1) {
if (selected == (1 << k) - 1) {
return stringParts[last];
}
if (last == -1) {
string ret = "";
for (int next = 0; next < k; next++) {
string resultStr = restore(selected + (1 << next), next);
if (ret.empty() || ret.length() > resultStr.length())
ret = resultStr;
}
return ret;
}
string& ret = cache[last][selected];
if (!ret.empty()) {
cout << "cache used in [" << last << "][" << selected << "]" << endl;
return ret;
}
string curString = stringParts[last];
for (int next = 0; next < k; next++) {
if (selected & (1 << next)) continue;
string checkStr = restore(selected + (1 << next), next);
int check = false;
string resultStr;
for (int i = (checkStr.length() > curString.length() ? curString.length() : checkStr.length())
; i > 0; i--) {
if (curString.substr(curString.size() - i, i) == checkStr.substr(0, i)) {
resultStr = curString + checkStr.substr(i, checkStr.length() - i);
check = true;
break;
}
}
if (!check)
resultStr = curString + checkStr;
if (ret.empty() || ret.length() > resultStr.length())
ret = resultStr;
}
return ret;
}
void EraseOverlapped() {
int vectorLen = stringParts.size();
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].length() < stringParts[j].length()) {
string temp = stringParts[i];
stringParts[i] = stringParts[j];
stringParts[j] = temp;
}
}
}
vector<string>::iterator iter;
for (int i = 0; i < vectorLen - 1; i++) {
for (int j = i + 1; j < vectorLen; j++) {
if (stringParts[i].find(stringParts[j]) != string::npos) {
iter = stringParts.begin() + j;
stringParts.erase(iter);
j--;
vectorLen--;
}
}
}
}
int main(void) {
int C;
cin >> C;
for (int testCase = 0; testCase < C; testCase++) {
cin >> k;
for (int i = 0; i < MAX + 1; i++) {
for (int j = 0; j < (1 << MAX) + 1; j++)
cache[i][j] = "";
}
string inputStr;
for (int i = 0; i < k; i++) {
cin >> inputStr;
stringParts.push_back(inputStr);
}
EraseOverlapped();
k = stringParts.size();
string resultStr = restore();
cout << resultStr << endl;
stringParts.clear();
}
}
This algorithm is much slower than the 'ideal' algorithm that the book I'm studying suggests, but it was fast enough to pass this question's time limit.

my code doesn't run some thing wrong about strings, c++

I was training on solving algorithms, I wrote a code but it won't compile
in (if) I can not check s[i]=='S' .
I'm trying to if s[i] is S character or not but I don't know where my problem is.
If I can't use this syntax, what could be a solution?
#include<iostream>
#include<string>
using namespace std;
int main()
{
double v_w=25,v_s=25,d_w=25,d_s=25;
int n;
cin>>n;
string s[]={"WSSS"};
int i ;
for (i=0; i<n; i++)
{
if( s[i] == "W" )
{
v_s += 50;
d_w = d_w + (v_w/2);
d_s = d_s + (v_s/2);
cout<<"1 \n";
}
if(s[i]=='W')
{
v_w +=50;
d_w = d_w + (v_w/2);
d_s = d_s + (v_s/2);
cout<<"2 \n";
}
return 0;
}
cout<< d_w<<endl<<d_s;
}
string s[]={"WSSS"}; means an array of strings which the first one is "WSSS".
What you need is:
std::string s="WSSS";
string s[] = {"Hello"} is an array of strings (well, of one string).
If you iterate over it, or index into it s[0] is "Hello".
Whereas
string s{"Hello"} is one string, which is made up of characters.
If you iterate over it, or index into it s[0], you will get 'H'.
To pre-empt all the other things that are going to go wrong when the string versus character problem is sorted, lets move the return 0; from the middle of the for loop.
Then let's think about what happens if the number n entered is larger than the length of the string:
int n;
cin>>n; //<- no reason to assume this will be s.length (0 or less) or even positive
string s{"WSSS"}; //one string is probably enough
int i ;
for(i=0;i<n;i++)
{
if( s[i] == 'W' ) //ARGGGGGGG may have gone beyond the end of s
{
In fact, let's just drop that for now and come back to it later. And let's use a range based for loop...
#include<iostream>
#include<string>
using namespace std;
int main()
{
double v_w = 25, v_s = 25, d_w = 25, d_s = 25;
string s{ "WSSS" };
for (auto && c : s)
{
if (c == 'W')
{
v_w += 50;
d_w = d_w + (v_w / 2);
d_s = d_s + (v_s / 2);
cout << "2 \n";
}
}
cout << d_w << '\n' << d_s << '\n'; //<- removed endl just because...
return 0;
}
s is an array of strings in this case it has only element:
string s[] = {"WSSS"};
so writing s[2]; // is Undefined behavior
your code will produce a UB if the user enters n greater than the number of elements in s:
n = 4;
for(i = 0; i < n; i++) // s[3] will be used which causes UB
{
if( s[i] == 'W' ) // s[i] is a string not just a single char
{
}
}
also as long as s is an array of strings then to check its elements check them as strings not just single chars:
if( s[i] == "W" ) // not if( s[i] == 'W' )
I think you wanted a single string:
string s = {"WSSS"};
because maybe you are accustomed to add the subscript operator to character strings:
char s[] = {"WSSS"};
if so then the condition above is correct:
if( s[i] == 'W' )

c++ string (int) + string (int) [duplicate]

This question already has answers here:
How to implement big int in C++
(14 answers)
Closed 9 years ago.
I have 2 strings, both contain only numbers. Those numbers are bigger than max of uint64_t.
How can I still add these 2 numbers and then convert the result to string?
Well, you can either use a bigger datatype (for example a library that deals with large integers), or you can quickly knock up your own.
I would suggest that if this is a one off, you do long addition exactly like you would have learned to do in your first few years of school. You can operate directly on the two strings, add the columns, do the 'carry', and build another string containing the result. You can do all this without any conversion to or from binary.
Here. Just for fun, I knocked up a solution for you:
string Add( const string& a, const string& b )
{
// Reserve storage for the result.
string result;
result.reserve( 1 + std::max(a.size(), b.size()) );
// Column positions and carry flag.
int apos = a.size();
int bpos = b.size();
int carry = 0;
// Add columns
while( carry > 0 || apos > 0 || bpos > 0 )
{
if( apos > 0 ) carry += a[--apos] - '0';
if( bpos > 0 ) carry += b[--bpos] - '0';
result.push_back('0' + (carry%10));
carry /= 10;
}
// The result string is backwards. Reverse and return it.
reverse( result.begin(), result.end() );
return result;
}
Note that, for clarity, this code doesn't even attempt to handle errors. It also doesn't do negatives, but it's not hard to fix that.
You need a a BigInt implementation. You can find several different ones here.
Whatever BigInt implementation you choose, needs to have conversion to and from string (they usually do).
Here is the code for your question:
#include <iostream>
#include <string>
using namespace std;
string StrAdd(string a, string b) {
string::reverse_iterator rit_a = a.rbegin();
string::reverse_iterator rit_b = b.rbegin();
string c;
int val_c_adv = 0;
while(rit_a != a.rend() && rit_b != b.rend() ) {
int val_a_i = *rit_a - '0';
int val_b_i = *rit_b - '0';
int val_c_i = val_a_i + val_b_i + val_c_adv;
if(val_c_i >= 10 ) {
val_c_adv = 1;
val_c_i -= 10;
} else {
val_c_adv = 0;
}
c.insert(0,1, (char)(val_c_i+'0'));
++rit_a;
++rit_b;
}
if(rit_a == a.rend() ) {
while( rit_b != b.rend() ) {
int val_b_i = *rit_b - '0';
int val_c_i = val_b_i + val_c_adv;
if(val_c_i >= 10 ) {
val_c_adv = 1;
val_c_i -= 10;
} else {
val_c_adv = 0;
}
c.insert(0, 1, (char)(val_c_i+'0'));
++rit_b;
}
} else if( rit_b == b.rend() ) {
while( rit_a != a.rend() ) {
int val_a_i = *rit_a - '0';
int val_c_i = val_a_i + val_c_adv;
if(val_c_i >= 10 ) {
val_c_adv = 1;
val_c_i -= 10;
} else {
val_c_adv = 0;
}
c.insert(0, 1, (char)(val_c_i+'0'));
++rit_a;
}
}
return c;
}
int main() {
string res, a, b;
cout << "a=" << endl;
cin >> a;
cout << "b=" << endl;
cin >> b;
res = StrAdd(a, b);
cout << "Result=" << res << endl;
}
If you just want to handle positive numbers without having to worry about bringing in an entire bignum library like GMP (along with its tendency to just abort on out-of-memory errors, something I find unforgivable in a general purpose library), you can roll your own, something like:
static std::string add (const std::string& num1, const std::string& num2) {
// Make num1 the wider number to simplify further code.
int digit, idx1 = num1.length() - 1, idx2 = num2.length() - 1;
if (idx1 < idx2) return add (num2, num1);
// Initialise loop variables.
int carry = 0;
std::string res; // reserve idx1+2 chars if you want.
// Add digits from right until thinner number finished.
while (idx2 >= 0) {
digit = num1[idx1--] - '0' + num2[idx2--] - '0' + carry;
carry = (digit > 9);
res.insert (0, 1, (digit % 10) + '0');
}
// Then just process rest of wider number and any leftover carry.
while (idx1 >= 0) {
digit = num1[idx1--] - '0' + carry;
carry = (digit > 9);
res.insert (0, 1, (digit % 10) + '0');
}
if (carry) res.insert (0, 1, '1');
return res;
}
You can add efficiencies like reserving space in the target string in advance, and setting specific indexes of it rather than inserting but, unless you're handling truly massive strings or doing it many time per second, I usually prefer code that is simpler to understand and maintain .

C++ removing leading zeros in a binary array

I am making a program that adds two binary numbers (up to 31 digits) together and outputs the sum in binary.
I have every thing working great but I need to remove the leading zeros off the solution.
This is what my output is:
char c[32];
int carry = 0;
if(carry == '1')
{
cout << carry;
}
for(i = 0; i < 32; i++)
{
cout << c[i];
}
I tried this but it didn't work:
char c[32];
int carry = 0;
bool flag = false;
if(carry == '1')
{
cout << carry;
}
for(i=0; i<32; i++)
{
if(c[i] != 0)
{
flag = true;
if(flag)
{
for(i = 0; i < 32; i++)
{
cout << c[i];
}
}
}
}
Any ideas or suggestions would be appreciated.
EDIT: Thank you everyone for your input, I got it to work!
You should not have that inner loop (inside if(flag)). It interferes with the i processing of the outer loop.
All you want to do at that point is to output the character if the flag is set.
And on top of that, the printing of the bits should be outside the detection of the first bit.
The following pseudo-code shows how I'd approach this:
set printing to false
if carry is 1:
output '1:'
for each bit position i:
if c[i] is 1:
set printing to true
if printing:
output c[i]
if not printing:
output 0
The first block of code may need to be changed to accurately output the number with carry. For example, if you ended up with the value 2 and a carry, you would want either of:
1:10 (or some other separator)
100000000000000000000000000000010 (33 digits)
Simply outputting 110 with no indication that the leftmost bit was a carry could either be:
2 with carry; or
6 without carry
The last block ensures you have some output for the value 0 which would otherwise print nothing since there were no 1 bits.
I'll leave it up to you whether you should output a separator between carry and value (and leave that line commented out) or use carry to force printing to true initially. The two options would be respectively:
if carry is 1:
output '1 '
and:
if carry is 1:
output 1
set printing to true
And, since you've done the conversion to C++ in a comment, that should be okay. You state that it doesn't work, but I typed in your code and it worked fine, outputting 10:
#include <iostream>
int main(void)
{
int i;
int carry = 0;
int c[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
bool print = false;
// This is the code you gave in the comment, slightly modified.
// vvvvvv
if(carry == 1) {
std::cout << carry << ":";
}
for (i = 0; i < 32; i++) {
if (c[i] == 1) {
print = true;
}
if (print) {
std::cout << c[i];
}
}
// ^^^^^^
std::cout << std::endl;
return 0;
}
const char * begin = std::find(c, c+32, '1');
size_t len = c - begin + 32;
std::cout.write(begin, len);
Use two fors over the same index. The first for iterates while == 0, the second one prints starting from where the first one left off.