Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to put a number like 123456 in to a array of digits. Could you please give me a hint to the process? Can i define an array with unknown number of elements?
First calculate no of digits
int count = 0;
int n = number;
while (n != 0)
{
n /= 10;
cout++;
}
Now intialize the array and assign the size:
if(count!=0){
int numberArray[count];
count = 0;
n = number;
while (n != 0){
numberArray[count] = n % 10;
n /= 10;
count++;
}
}
If you don't mind using char as the array element type, you can use snprintf():
char digits[32];
snprintf(digits, sizeof(digits), "%d", number);
Each digit will be represented as the character values '0' though '9'. To get the integer value, subtract the character value by '0'.
int digit_value = digits[x] - '0';
"Can i define an array with unknown number of elements ?"
If the number is too large you can input it as string and then accordingly extract digits from it
Something like following :
char buf[128];
int *array;
//fscanf(stdin,"%s",buf);
array = malloc(strlen(buf) * sizeof(int)); //Allocate Memory
int i=0;
do{
array[i] = buf[i]-'0'; //get the number from ASCII subtract 48
}while(buf[++i]); // Loop till last but one
int x[6];
int n=123456;
int i=0;
while(n>0){
x[i]=n%10;
n=n/10;
i++;
}
Here are teh steps. First, get the size needed to store all the digits in the number -- do a malloc of an array. Next, take the mod of the number and then divide the number by 10. Keep doing this till you exhaust all digits in the number.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to print my characters BEFORE the previously printed character using printf. For example:
printf("1")
printf("0")
would need to output:
01
Is there a way to do this? I cannot use arrays. To be clear I'm printing in base two (binary) representation using a divide by two algorithm:
for(int i = 0; i < 16; i++){ // 16 bit int
tmp = num % 2;
if(tmp == 1){
printf("1");
} else {
printf("0");
}
num /= 2;
}
The above code prints the binary representation backwards.
Here is my solution to print binary without using array. you can ignore initial zeros by adding another if condition.
#include<stdio.h>
int main(){
int num =50;
int i;
for(i=15;i>=0;i--){
if( (1<<i) & num){
printf("1");
}
else printf("0");
}
return 0;
}
output:
0000000000110010
Recursion can perform like a "print before". #rici
The below does not always print 16 digits, just the decimal digits needed.
void print_binary(unsigned n) {
// Break the digits into 2 groups: 1) the one least digit and 2) the rest.
unsigned last_digit = n/10;
unsigned all_the_other_more_significant_digits = n/10;
// Let us print those more significant digits first;
if (all_the_other_more_significant_digits > 0) {
print_binary(all_the_other_more_significant_digits);
}
// Now print the last digit
printf("%u", last_digit);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried this problem using for loop but i did not got the correct output as specified . i do not know what is the problem in my code ?
#include <stdio.h>
int main()
{
int T,N;
scanf("%d %d" ,&T,&N);
for(int i=N;i>0;i=i/10)
{
int r=N%10;
int sum=0;
sum=sum+r;
printf("The sum is : %d" ,sum);
}
}
The sum is : 5The sum is : 5The sum is : 5The sum is : 5The sum is : 5
The output is coming like this while we just need sum of digits printed
for(int i = N; i > 0 ; i = i/10)
{
int r = N % 10; // calculating remainder of UNMODIFIED input, so will
// ALWAYS be last digit
int sum = 0; // you are initializing the sum to 0 for every single iteration
sum = sum + r; // so this will *always* result in 0 + N % 10
printf("The sum is : %d", sum);
}
To fix, you need to initialise the sum just once to collect all of the single digits. Additionally, you need to use the modified value:
int sum = 0;
for(int i = N; i > 0 ; i = i/10)
{
int r = i % 10;
// ^ (!)
sum += r; // alternative variant...
printf("The sum is : %d\n", sum);
// ^^ for better output formatting
}
Until now we are still printing the sum with every iteration as well. That might be useful, if you want to follow how the sum evolves (assuming input was 1210):
The sum is 0
The sum is 1
The sum is 3
The sum is 4
But actually, you'd rather want to print only the result, wouldn't you? So you'd move the printing out of the loop as well:
for(...)
{
...
}
printf("The sum is : %d\n", sum);
Alternative variant: If you don't need the value of N afterwards any more anyway, you can iterate directly on it:
for( ; N > 0; N /= 10)
// ^ empty initialization, nothing to be done...
{
int r = N % 10; // NOW using N is fine...
...
}
Finally: if you compare with != instead of >, you can cover negative intput (as you use signed integers...) as well.
Edit according to question:
it asked input and output like this. Input 3 12345 31203 2123 Output 15 9 8
Well, in this case, you need a double loop:
int t;
// well, actually, you should check if you did get correct input:
if(scanf("%d", &t) != 1))
{
// invalid input
// appropriate error handling, e. g. printing a message and:
return -1;
}
for( ; t > 0; --t) // handles the number of tasks to solve
{
int n; // inside loop: read in a new value with every task
scanf("%d", &n); // TODO: check input, see above
int sum = 0;
for(...) { ... } // loop handling the input value, see above
printf(...);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I do the sum of the digits like that:
while(number>0)
{
sum+=number%TEN;
number=number/TEN;
}
but I need that if the number is (for example) 123444 so it'll include only one 4 in the sum. how can I do that?
Have an array of all digits initialized to zero
int digits[10] = { 0 };
Then before adding a digit you check if digits[that_digit] is zero, if yes you set it to 1 and add to sum, if no keep going ...
while(number>0)
{
int one = number%TEN;
if ( ! digits[one]) {
sum+=one;
digits[one] = 1;
}
number=number/TEN;
}
Edit, no array version
Add an int initialized to 0, the bit i indicates if that digit i has already been summed.
If 1 was added, bit 1 set to 1, if 2, bit 2 set to 1 etc...
int bits = 0;
while(number>0)
{
int one = number%TEN;
if (!(bits & (1<<one))) {
sum+=one;
bits |= 1<<one;
}
number=number/TEN;
}
First you should put some code here whatever you tried, to give you basic idea to solve your problem I am putting simple code below.
#include<stdio.h>
#include<malloc.h>
int main()
{
int input, digit, temp, sum = 0;
printf("Enter Input Number :\n");
scanf("%d",&input);
temp = input;
//first find how many digits are there
for(digit = 0 ; temp != 0 ;digit++, temp /= 10);
//create one array equal to no of digits, use dynamic array because once you find different digits you can re-allocate memory and save some memory
int *p = malloc(digit * sizeof(int));
//now store all the digits in dynamic array
p[0] = input % 10;//1
for(int i = 0; i < digit ;i++) {
input /= 10;
p[i+1] = input %10;
if(p[i] != p[i+1])
sum = sum + p[i];
}
printf("sum of different digits : = %d \n",sum);
free(p);
p = 0;
return 0;
}
Explanation of this code I mentioned in comments itself, it may not work for all test case, remaining try yourself.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have to implement Rijndael algorithm in C. I start with this:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i=0,j;
char m[5000];
char message[5000];
char ch;
printf("Introduce the message\n\n");
while((ch=getchar())!='\n')
{
message[i]=ch;
i++;
}
message[i]='\0';
i=0;
while(message[i]!='\0')
{
sscanf(&message[i],"%x",&m);
i++;
}
printf("\nResult\n");
for(j=0;j<i;j++)
{
printf(" %x",&m[j]);
}
printf("\n");
}
I need an array in which for example "Hello"(where array1[0] will show H) will be written as 48656c6c6f, and when calling array2[0] it will show 48.
Do you want a hexadecimal representation of message's contents? If so, what you need is this:
char messageHex[sizeof(message)*2];
memset(messageHex, 0, sizeof(messageHex));
size_t len = strlen(message);
for (size_t i = 0; i < len; i++)
{
sprintf(messageHex + i*2, "%02X", message[i] & 0xFF);
}
What use would it be to you to make an array that contains the hexadecimal value in a decimal representation? It's the same numeric value after all.
Printing it would be as simple as printf("%x\n", arr[0]);.
If you insist, then you can have an array of strings (char*) with each containing the string of the hexadecimal value then you might want to use sprintf() (so you won't need to do any calculations yourself) as following:
unsigned char** hex_arr = malloc(arrLen); //arrLen is the integer array length
for(i = 0 ; i < arrLen ; i++) //declare i first
{
hex_arr[i] = malloc(3); //2 characters and null (two hexadecimal notes can represent up to 255 which is the size of the wide ASCII table)
sprintf(hex_arr[i], "%x", (uint8_t)arr[i]); //as arr is your integer array
}
Note that you can also organize everything unto one string (char*) where every character in spot of i in the integer array would be represented by two characters: xArr[i*2] and xArr[i*2+1]
Cheers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For example:
1: 123456 should be converted to 214365
2: 12345 should be converted to 103254
int32_t conv(int32_t n){
char buff[16], *p = &buff[1];
int i, v = n < 0 ? -n : n;
sprintf(p, "%010d", v);
for(i=0;i<5;++i,++p){
char c;
c = *p;
*p = p[1];
*(++p) = c;
}
buff[0] = (n < 0) ? '-' : ' ';
return atoi(buff);
}
size_t conv(size_t n){
size_t q, r, wk, mul=1, ret = 0;
for(;n;n/=100, mul*=100){
wk = n % 100;
r = wk % 10;
q = wk / 10;
ret += (r * 10 + q)*mul;
}
return ret;
}
,
First to clarify: there's a difference between an integer and the decimal representation of that integer in a string. You want the second.
As H2CO3 points out you can do this on your own using modulo's: decompose your number into the decimal base, do the swaps then recompose the number (only mul/add).
Here's another way:
Create a string from your integer using malloc and sprintf.
Loop through the string and do the swapping of characters
print that string or if you want convert it back to an integer with atoi