Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (anonymous):

In C++,How can I initialize a big number into array? For Example if a want to assign 123456789 into a array num[8] then can I write num[8]=1,2,3,4,5,6,7,8,9; or will I have to write num[0]=1; num[1]=2; num[2]=3; num[3]=4; num[4]=5; num[5]=6; num[6]=7; num[7]=8; num[8]=9; It is a 100 digit number.Is there any other alternative?

OpenStudy (anonymous):

have you ever used java or python? what so the need to 100 digit number for?

OpenStudy (anonymous):

C++ assignment in school.

OpenStudy (anonymous):

ok, are you wanting to do operations on it like addition, multiplication, etc ?

OpenStudy (anonymous):

yup

OpenStudy (anonymous):

well to answer your current question you could do something like this. at the moment i'm wasting a lot of space though #include <iostream> #include <string.h> #include <stdlib.h> int main() { char* number = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; int len = strlen(number); printf("Digits: %d\n", len); int digits[100]; char tempNum[2]; tempNum[1] = 0; for(int i = 0; i != len; i++) { tempNum[0] = number[i]; digits[i] = atoi(tempNum); } for(int i = 0; i != len; i++) { printf("%d", digits[i]); } printf("\n"); }

OpenStudy (anonymous):

thx

OpenStudy (anonymous):

The answer that was given has a few issues: - It cannot handle numbers with more than 100 digits. Buffer overflow occurs in that case. - Even though the 'atoi' conversion in the main for loop is correct, there may be another way of achieving the conversion without using an extra buffer, and this is done by using the ASCII code of each char. I would implement the solution as follows: #include <string.h> #include<stdlib.h> #include<iostream> int main() { char* number = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"; int len = strlen(number); printf("Digits: %d\n", len); //allocating memory char *digits = new char[len]; for(int i = 0; i < len; i++) { digits[i] = number[i] - '0'; } for(int i = 0; i != len; i++) { printf("%d", digits[i]); } printf("\n"); //free up the memory delete digits; } ~

OpenStudy (anonymous):

try using exponential form....

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!