Multiply every other number with out using an array - c++

So my problem is bigger but I just do not know what to do with my code. I can do what I want if I use an array works just fine but we are not using arrays yet so I have no idea how to do it. So I have to take user input as a string validate that the string is 16 characters long, all of them are digits, and most importantly I have to multiply every other or even character by 2. Then if it is a double digit add the two digit (ex. 10 1+0). Oh by the way I do not know why but every time I do i%2 == 0 I get the odd numbers. Is it because i is unsigned?
for(unsigned i = 1; i < card.length(); i++){
if (i % 2 == 1){
}
else {
}
}
return sum;
}

You could use an array of strings where each string contains a number.
Go through them checking for 2 conditions:
Double the number if it is even (i.e., i % 2 == 0)
Add the digits if the number has 2 digits (i.e., string's length is 2)
Code:
#include <iostream>
#include <iterator> using namespace std;
int TOTAL_CARDS = 16;
void printCards(string msg, string *array) {
cout<<msg<<endl;
for(int i = 0; i < TOTAL_CARDS; i++) {
cout<<"array["<<i<<"]="<<array[i]<<endl;
}
cout<<"\n"<<endl; }
int main() {
string cards[TOTAL_CARDS];
// hardcoded numbers 0 up to TOTAL_CARDS for demo purposes
for(int i = 0; i < TOTAL_CARDS; i++) {
cards[i] = to_string(i);
}
printCards("Before:", cards);
for (unsigned i = 1; i < TOTAL_CARDS; i++){
// double if even
if (i % 2 == 0){
cards[i] = to_string(stoi(cards[i]) * 2);
}
// add digits if double digit number
if (cards[i].length() == 2) {
// get each digit
string currentNum = cards[i];
int firstDigit = currentNum[0] - '0'; // char - '0' gives int
int secondDigit = currentNum[1] - '0';
// do sum and put in array
int sum = firstDigit + secondDigit;
cards[i] = to_string(sum);
}
}
printCards("After:", cards); }
Output:
Before:
array[0]=0
array[1]=1
array[2]=2
array[3]=3
array[4]=4
array[5]=5
array[6]=6
array[7]=7
array[8]=8
array[9]=9
array[10]=10
array[11]=11
array[12]=12
array[13]=13
array[14]=14
array[15]=15
After:
array[0]=0
array[1]=1
array[2]=4
array[3]=3
array[4]=8
array[5]=5
array[6]=3
array[7]=7
array[8]=7
array[9]=9
array[10]=2
array[11]=2
array[12]=6
array[13]=4
array[14]=10
array[15]=6
If you wanted to get user input for the numbers:
// get user to enter numbers
cout<<"Please enter "<<TOTAL_CARDS<<" numbers: "<<endl;
for(int i = 0; i < TOTAL_CARDS; i++) {
cin>>cards[i];
}

I found the answer to it. I first needed to create char variable named num. Convert the char to an int using chnum and then multiply.
for(unsigned i = 0; i < card.length(); i++){
if (i % 2 == 1){
num = card.at(i);
chnum = (num -'0');
add = chnum * 2;
if(add >= 10){
char ho = (add + '0');
string str(1,ho);
for (unsigned j = 0; j < str.length();j++){
char digi = str.at(j);
int chub = (digi - '0');
cout << digi;
//add = (chub) + (chub);
}
}
sum += add;
}

Related

Multiplying two ridiculously large number stored in an array of chars C++

I have an assignment which requires me to write a program that multiplies two large numbers that are each stored in an array of characters with the maximum length of 100. After countless efforts and debugging and multiplying 10 digit numbers step by step and by hand I have now written the following piece of messy code:
#include <iostream>
#include <string.h>
using namespace std;
const int MAX_SIZE = 100;
int charToInt(char);
char IntToChar(int);
long long int pow10(int);
bool isNumber(char[]);
void fillWith0(char[], int);
void multiply(char[], char[], char[]);
int main(){
char first_num[MAX_SIZE + 1], second_num[MAX_SIZE + 1], product[2 * MAX_SIZE + 1];
cout << "A =\t";
cin.getline(first_num, MAX_SIZE);
cout << "B =\t";
cin.getline(second_num, MAX_SIZE);
multiply(first_num, second_num, product);
cout << "A * B = " << product << endl;
return 0;
}
int charToInt(char ch){
return ch - '0';
}
char intToChar(int i){
return i + '0';
}
long long int pow10(int pow){
int res = 1;
for (int i = 0; i < pow ; i++){
res *= 10;
}
return res;
}
bool isNumber(char input[]){
for (int i = 0; input[i] != '\0'; i++){
if (!(input[i] >= '0' && input[i] <= '9')){
return false;
}
}
return true;
}
void fillWith0(char input[], int size){
int i;
for (i = 0; i < size; i++){
input[i] = '0';
}
input[i] = '\0';
}
void multiply(char first[], char second[], char prod[]){
_strrev(first);
_strrev(second);
if (isNumber(first) && isNumber(second)){
fillWith0(prod, 2 * MAX_SIZE + 1);
int i, j, k;
long long int carry = 0;
for (i = 0; second[i] != '\0'; i++){
for (j = 0; first[j] != '\0'; j++){
long long int mult = (pow10(i) * charToInt(first[j]) * charToInt(second[i])) + carry + charToInt(prod[j]);
prod[j] = intToChar(mult % 10);
carry = mult / 10;
}
k = j;
while (carry != 0){
carry += charToInt(prod[k]);
prod[k] = intToChar(carry % 10);
carry = carry / 10;
k++;
}
}
prod[k] = '\0';
_strrev(first);
_strrev(second);
_strrev(prod);
}
}
My problem is that it does not work with numbers that have more than 10 digits (1234567891 * 1987654321 works fine but nothing with more digits than that), as the output in those cases is a set of weird characters I presume the issue is somewhere something is overflowing and causing weird issues, although I have used long long int to store the only two numeric integers in the algorithm, doing so helped me bump from 6 digits to 10 but nothing more. Is there any suggestions or possibly solutions I can implement?
P.S. : As I mentioned before this is an assignment, so using libraries and other stuff is not allowed, I've already seen this implemented using vectors but unfortunately for me, I can't use vectors here.
The core mistake is using a long long int to store the intermediate multiplied number. Instead, use another char[] so the core of your multiply becomes simply:
for (i = 0; second[i] != '\0'; i++){
char scratch[2 * MAX_SIZE + 1];
// Fill up the first i positions with 0
fillWith0(scratch, i);
// Store second[i] * first in scratch, starting at position i.
// Make sure to 0-terminate scratch.
multiplyArrWithNumber(&scratch[i], intToChar(second[i]), first);
// Add pairwise elements with carry, stop at the end of scratch
addArrays(scratch, prod);
}

Converting an integer into it's binary equivalent

I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}

Why The Elements of 2 Identical arrays Equal each other

I should mention the purpose of this code is to tackle a leading zero scenario when finding date palindromes in dates in format MMDDYYY.
Here is the code.
#include <iostream>
using namespace std;
unsigned numDigits (unsigned num)//this works
{
if (num < 10) return 1;
return 1+ numDigits(num/10);
}
int main ()
{
unsigned date = 1111110;//01/11/1110(jan 11th of 1110 is palindrome)
cout<<numDigits(date)<<"num of dig"<<endl;
if (numDigits(date) == 7)
{
unsigned array[8];
unsigned number = date;
unsigned revArr[8];
for (int h = 7; h >= 0; h--) //this pops array withdate
{
array[h] = number % 10;
number /= 10;
cout<<array[h]<<endl;
}
cout<<"vs"<<endl;
for (int i = 0; i < 8; i++) //this pops revarray withdate
{
revArr[i] = number % 10;
number /= 10;
cout<<array[i]<<endl;
}
for (int j = 0; j < 8; j++)
{
if (array[j] == revArr[j])
{
cout<<j<<"th digit are" <<" equal"<<endl;
}
}
}
return 0;
}
In this case both of the arrays are identical, I don't underdtdanwd why array[0] == revArr[0] but array[1] != revArr[1] and so on but array[7] == revArr[7] again... its boggling my mind.
The loops traverse all elements of the array. Even when the expression number /= 10 is equal to 0. In this case the zero is stored in the array elements because 0 / 10 gives again 0.
Before the second loop write
number = date;

Sum of two arrays, carry over operation C++

Beginner here, and I'm stuck. The main program is provided to us, and we're supposed to write 3 functions. readBig(), addBig(), and printBig(). I'm stuck on the addBig() function. It's supposed to sum two arrays, and perform the carry operation. I cannot figure out where I'm going wrong. The carry operation is working out for me.
Any help/direction is appreciated.
#include <iostream>
using namespace std;
//This program will test three functions capable of reading, adding,
//and printing 100-digit numbers.
// Do not change these function prototypes:
void readBig(int[]);
void printBig(int[]);
void addBig(int[], int[], int[]);
// This constant should be 100 when the program is finished.
const int MAX_DIGITS = 100;
//There should be no changes made to the main program when you turn it
in.
int main(){
// Declare the three numbers, the first, second and the sum:
int num1[MAX_DIGITS], num2[MAX_DIGITS], sum[MAX_DIGITS];
bool done = false;
char response;
while (not done)
{
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(num1);
cout << "Please enter a number up to "<<MAX_DIGITS<< " digits: ";
readBig(num2);
addBig(num1, num2, sum);
printBig(num1);
cout << "\n+\n";
printBig(num2);
cout << "\n=\n";
printBig(sum);
cout << "\n";
cout <<"test again?";
cin>>response;
cin.ignore(900,'\n');
done = toupper(response)!='Y';
}
return 0;
}
//ReadBig will read a number as a string,
//It then converts each element of the string to an integer and stores
it in an integer array.
//Finally, it reverses the elements of the array so that the ones digit
is in element zero,
//the tens digit is in element 1, the hundreds digit is in element 2,
etc.
void readBig(int num[])
{
for(int i = 0; i < MAX_DIGITS; i++){
num[i] = 0;
}
string numStr;
getline(cin,numStr);
string temp;
//store into array
for (int i = 0; i < numStr.length(); i++){
temp = numStr.at(i);
num[i] = stoi(temp);
}
int arrayLength = MAX_DIGITS;
int temp2;
for (int i = 0; i < (arrayLength/2); i++){
temp2 = num[i];
num[i] = num[(arrayLength - 1) - i];
num[(arrayLength - 1) - i] = temp2;
}
}
//AddBig adds the corresponding digits of the first two arrays and
stores the answer in the third.
//In a second loop, it performs the carry operation.
void addBig(int num1[], int num2[], int sum[])
{
for (int i = 0; i < MAX_DIGITS; i++){
sum[i] = num1[i] + num2[i];
if (sum[i] > 9){
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 10;
}
}
}
//PrintBig uses a while loop to skip leading zeros and then uses a for
loop to print the number.
void printBig(int array[])
{
int i = 0;
while (array[i] == 0){
i++;
}
for (int j = i; j < MAX_DIGITS;j++){
cout << array[j] << endl;
}
}
Looks like readBig function isn't correct, it stores least significiant digit into num[numStr.length()-1], after reversing it became num[MAX_DIGITS -1 - ( numStr.length()-1], but addNum assumes last digit is num[0].
Correct variant:
void readBig(int num[])
{
//clear num, read numStr...
//store into array
int count = 0;
for (int i = numStr.length()-1; i >= 0; --i){
temp = numStr.at(i);
num[count++] = stoi(temp);
}
|
So this
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 10;
should most likely be this
sum[i] = sum[i] - 10;
sum[i+1] = sum[i+1] + 1;
Since its the next decimal place it shouldnt be incremented by 10
Also when you get to the last cell in your array
sum[i+1] = sum[i+1] + 1;
this will be out of bounds, so depending on the requirments you will want to change this

Disallowed system call: SYS_socketcall - Error when trying to verify ISBN

I'm trying to verify ISBN numbers in C but when I run the program I get the following error: Disallowed system call: SYS_socketcall
This is for a homework assignment in a CS class. I've done all the work so it's not like I'm asking people to do my assignment for me. I'm just wondering why I'm getting this error as I'm new to the C language; I come from a Java background as well as some web programming languages. Anyways, here's the assignment description if it'll help:
Perform a check on the characters in an ISBN to verify correctness.
The check character is computed as follows:
First, compute the sum of the first digit plus two times the second digit
plus three times the third digit, ... , plus nine times the ninth digit. The
last character is the remainder when the sum is divided by 11. If the
remainder is 10, the last character is X. For example, the sum for
the ISBN 0-8065-0959-7 is
1*0 + 2*8 + 3*0 + 4*6 + 5*5 + 6*0 + 7*9 + 8*5 + 9*9 = 249
The remainder when 249 is divided by 11 is 7, the last character in the ISBN.
The check character is used to validate an ISBN.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int checkISBN( char[] );
#define size 18L
int main() {
int i,j;
char* s[size] = {
"0-8065-0959-7",
"0-534-37964-8",
"0-618-50298-X",
"0-8065-0959-8",
"0-534-37964-9",
"0-618-50298-5",
"0-534-37964-8",
"0-618-50298-X",
"032121353X",
"0321199553",
"0201794896",
"0870495275",
"0452264464",
"0536901562",
"158901104X",
"080801076X",
"80-902734-1-6"
"158901104X" };
for( i = 0; i < size; i++){
if( checkISBN( s[i] ) == 1 )
printf("%-15s is a valid ISBN \n",s[i]);
else
printf("%-15s is NOT a valid ISBN*****\n",s[i]);
}
putchar('\n'); //write a newline
system("pause");`enter code here`
return EXIT_SUCCESS;
}
int checkISBN( char s[] )
{
int result = 0;
int i;
int n = 1;
int sum = 0;
char ch[10];
int final[10];
int sizeOfArray = strlen(s);
for(i=0; i<sizeOfArray; i++){
if(s[i] == '-'){
++i;}
if(s[strlen(s)-1] == 'X'){
s[strlen(s)-1] = 10;}
ch[i] = s[i];
}
for(i=0; i<10; i++){
final[i] = atoi(&ch[i]);}
for(i=0; i<9; i++){
sum+= final[i]*n;
++n;}
int checkCharacter = sum%11;
if(checkCharacter == final[9]){
result = 1;}
return result;}
#include <ctype.h>
int checkISBN( char s[] ) {
int i, n = 1, sum = 0, checksum;
for(i=0; s[i]; ++i){
if(s[i] == '-')
continue;
if(n<10 && isdigit(s[i]))
sum += n++*(s[i] - '0');
else if(n==10){
if(s[i] == 'X')
checksum = 10;
else if(isdigit(s[i]))
checksum = s[i] - '0';
}
}
return sum % 11 == checksum;
}
also
"80-902734-1-6", //need comma