I need a method to print a long with leading zeros in the form 123,456 with a comma between 3rd and 4th digit. I have this code for now:
#include <stdio.h>
void printWithComma (long num);
int main (void)
{
long number;
printf ("\nEnter a number with up to 6 digits: ");
scanf ("%ld", &number);
printWithComma (number);
return 0;
}
void printWithComma (long num)
{
//method to print the 6 digit number separated by comma
}
Example Output
Run 1
Enter a number with up to 6 digits: 123456
The number you entered is 123,456
Run 2
Enter a number with up to 6 digits: 12
The number you entered is 000,012
#include <stdio.h>
void printWithComma (long num);
int main()
{
long number;
printf("\nEnter a number with up to 6 digits: ");
scanf ("%ld", &number);
printWithComma(number);
return 0;
}
void printWithComma (long num)
{
int i, divisor, x;
char s[8];
divisor = 100000;
for(i = 0; i < 7; i++ ){
if( i == 3){
s[i] = ',';
continue;
}
if(divisor == 1){
s[i] = num % 10 + '0';
break;
}
x = num / divisor;
num %= divisor;
s[i] = x + '0';
divisor = divisor / 10;
}
s[7] = '\0';
printf("\n%s\n", s);
}
void printWithComma (long num) {
//method to print the 6 digit number separated by comma
char n[] = "000,000";
char *p[6] = { n+6, n+5, n+4, n+2, n+1, n };
int i;
for(i=0;num && i<6;++i, num/=10){
*p[i] += num % 10;
}
printf("\nThe number you entered is %s\n", n);
}
Related
I want to input an array of integers then print out the even numbers from the inputted numbers..
example is if I input 2466688992,
it will output 24666882;
I have a my code below:
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array of numbers: ");
scanf("%d",&a);
for(i=0; i<sizeof(a); i++){
if(a[i]%2==0)
printf("%d",a[i]);
}
getch();
return 0;
}
It resulted into garbage : 2468000075416640419940000004225568000
This is the function that prints even numbers in an integer :
#include<stdio.h>
int main(){
int num,rem,even=0,digit;
printf(" Enter an integer number: ");
scanf("%d",&num);
printf("\n The even digits present in %d are \n",num);
while(num>0){
digit = num % 10;
num = num / 10;
rem = digit % 2;
if(rem == 0)
even++;
printf("\n %d.",digit);
}
return 0;
}
You should scan the array as a string (unless you want to impose the number of items in the array), and then parse the string to store the different numbers:
long a[50];
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
int j = 0;
for (int i = 0; i < len; ) {
long sign = 1;
long n = 0;
if (buf[i] == '+') {
++i;
}
else if (buf[i] == '-') {
sign = -1;
++i;
}
if (isdigit(buf[i])) {
while (isdigit(buf[i])) {
n = 10 * n + buf[i++] - '0';
}
a[j] = n * sign;
}
else
i++;
}
for (int i = 0; i < j; i++)
if (!(a[i] ℅ 2)) // true if even
printf("%ld ", a[i]);
This will store all your digits in your array a of size j.
Edit: if you are talking about digits then its easier:
char buf[1024];
printf("Enter array of numbers: ");
scanf("%s",buf);
int len = strlen(buf);
for (int i = 0; i < len; i++)
if (isdigit(buf[i]) && !((buf[i] - '0') ℅ 2)) // true if even, note that '0' equals 0x30 so there is no need to sub it to check for odd/even in reality.
printf("%c ", buf[i]);
(Purpose of the code is write in the title) my code work only if i put the same number once and in the end like - 123455 but if i write 12345566 is dosent work or 11234 it dosent wort to someone know why? i have been trying for a few days and i faild agine and agine.
while(num)
{
dig = num % 10 // dig is the digit in the number
num /= 10 // num is the number the user enter
while(num2) // num2 = num
{
num2 /= 10
dig2 = num2 % 10 // dig2 is is the one digit next to dig
num2 /= 10
if(dig2 == dig) // here I check if I got the same digit twice to
// not include him
{
dig2 = 0
dig = 0
}
}
sum = sum + dig + hold
}
printf("%d", sum)
Well your code's almost correct but there's are somethings wrong ,
When you declared num2 to be equal to num1 it was out of the loop so as soon as one full loop execution is done , num2 still remains to be less than zero or to be zero if it was a unsigned int, so according to the condition the second loop wont execute after its first run.
So mind adding ,
num2 = num1
inside your first loop .
Also your updating num2 twice which i think you wont need to do after the first change .
Full code which i tried
#include<stdio.h>
int main(void)
{
int num;
int num2;
int sum = 0;
int dig, dig2;
scanf_s("%d", &num);
while (num>0)
{
dig = num % 10; //dig is the digit in the number
num /= 10;
num2 = num;// num is the number the user enter
while (num2>0) // num2 = num
{
dig2 = num2 % 10; // dig2 is is the one digit next to dig
if(dig2 == dig) // here i check if i got the same digit twice to //not include him
{
dig = 0;
}
num2 /= 10;
}
sum = sum + dig ;
}
printf("%d", sum);
return 0;
}
O(n)
#include <stdio.h>
int main () {
unsigned int input = 0;
printf("Enter data : ");
scanf("%u", &input);
int sum = 0;
int dig = 0;
int check[10] = {0};
printf("Data input: %u\n", input);
while(input) {
dig = 0;
dig = input%10;
input = input/10;
if (check[dig] == 0) {
check[dig]++;
sum += dig;
}
}
printf("Sum of digits : %d\n", sum);
return 0;
}
My program uses a character array (string) for storing an integer. We convert its every character into an integer and I remove all integers repeated and I calculate the sume of integers without repetition
My code :
#include <stdio.h>
#include <stdlib.h>
int remove_occurences(int size,int arr[size])
{int s=0;
for (int i = 0; i < size; i++)
{
for(int p=i+1;p<size;p++)
{
if (arr[i]==arr[p])
{
for (int j = i+1; j < size ;j++)
{
arr[j-1] = arr[j];
}
size--;
p--;
}
}
}
for(int i=0;i<size;i++)
{
s=s+arr[i];
}
return s;
}
int main()
{
int i=0, sum=0,p=0;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
int T[strlen(n)];
while (n[i] != '\0')
{
T[p]=n[i] - '0'; // Converting character to integer and make it into the array
p++;i++;
}
printf("\nThe sum of digits of this number :%d\n",remove_occurences(strlen(n),T));
return 0;
}
Example :
Input : 1111111111 Output : 1
Input : 12345566 Output : 21
Or ,you can use this solution :
#include <stdio.h>
#include <stdbool.h>
bool Exist(int *,int,int);
int main ()
{
unsigned int n = 0;
int m=0,s=0;
printf("Add a number please :");
scanf("%u", &n);
int T[(int)floor(log10(abs(n)))+1];
// to calculate the number of digits use : (int)floor(log10(abs(n)))+1
printf("\nThe length of this number is : %d\n",(int)floor(log10(abs(n)))+1);
int p=0;
while(n!=0)
{
m=n%10;
if(Exist(T,p,m)==true)
{
T[p]=m;
p++;
}
n=n/10;
}
for(int i=0;i<p;i++)
{
s=s+T[i];
}
printf("\nSum of digits : %d\n", s);
return 0;
}
bool Exist(int *T,int k,int c)
{
for(int i=0;i<k;i++)
{
if(T[i]==c)
{
return false;
}
}
return true;
}
I am starter in the C.I wrote a simple code which are calculating how many digits are the entered Number and sum of entered number’s digits.Code calculating digit count right but sum of digits being given as ‘0’ every time.Could you say where is my error?thanks.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
int ndigit(int val) {
if (val == 0)
return 0;
int digit_count = 1;
while ((val = getchar() != '\n')) {
digit_count++;
val /= 10;
}
return digit_count;
}
int sumdigit(int number) {
int result = 0;
while ((number = getchar()) != '\n'){
result += number - '0';
}
return result;
}
int main()
{
int a;
printf("Bir tam sayi giriniz: \n");
a = getchar();
printf("Bu sayinin basamak sayisi =%d", ndigit(a));
printf("Bu sayinin basamak degeri toplami= %d", sumdigit(a));
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
The program does not make sense. To enter a number you should use one function. That is the number of digits and the sum of digits must be calculated for the same number.
This condition in the while statement
while ((val = getchar() != '\n')) {
is equivalent to
while ( ( val = ( getchar() != '\n' ) ) ) {
and as a result the integer val gets either 1 or 0.
As the variable val stores an internal representation of a character (for example its ASCII value) then this statement
val /= 10;
also does not make sense. Also the user can enter a non-digit character.
You should either use a character array for the entered number by means of calls of the function getchar or use the function scanf to enter a value of an integer object.
If to use a character array then the program can look the following way
#include <stdio.h>
char * get_number( char *number, size_t n )
{
size_t i = 0;
int c;
while( i + 1 < n && ( c = getchar() ) != EOF && c != '\n' && '0' <= c && c <= '9' )
{
number[i++] = c;
}
number[i] = '\0';
return number;
}
size_t ndigit( const char *number )
{
size_t n = 0;
while ( number[n] != '\0' ) ++n;
return n;
}
unsigned int sumdigit( const char *number )
{
unsigned int sum = 0;
while ( *number != '\0' )
{
sum += *number++ - '0';
}
return sum;
}
int main(void)
{
enum { N = 50 };
char number[N];
printf( "Bir tam sayi giriniz: " );
get_number( number, N );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look like
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
If to use an integer number then the program can look the following way
#include <stdio.h>
size_t ndigit( unsigned long long number )
{
const unsigned long long Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
unsigned int sumdigit( unsigned long long number )
{
const unsigned long long Base = 10;
unsigned int sum = 0;
do
{
sum += number % Base;
} while ( number /= Base );
return sum;
}
int main(void)
{
unsigned long long number = 0;
printf( "Bir tam sayi giriniz: " );
scanf( "%llu", &number );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look as it is shown above.
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
You code has 3 getchar() that are independent. Just use one getchar, either in main, or ndigit or sumdigit.
I propose, you should get the number in main function using scanf instead of getchar(), then pass the number as the argument to the other functions (ndigit and sumdigit). Because getchar reads character by character, and it does not guarantee the character is a digit or not.
The main function becomes:
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\n number of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
For two function ndigit and sumdigit, you can change to:
ndigit function:
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
num /= 10;
} while(num != 0);
return count;
}
sumdigit function:
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
The complete code:
#include <stdio.h>
#include <stdlib.h>
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
number /= 10;
} while(number != 0);
return count;
}
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\nnumber of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
The output of test:
enter the number: 222333
sum of digits = 15
number of digits = 6
After using scanf, change your sumdigit while loop to:
while (number > 0) {
result += number % 10;
number /= 10;
}
How do I separate number with 5 spaces in between the numbers without reversing the number using while loop and pow function?
User can enter any number of numbers. It is not restricted to example just 3.
User will be asked to input n-number of numbers.
User will be asked to enter the numbers.
Print out the numbers without using arrays but only basic while loop and pow function.
Hope to get some help, thank you!
I've tried but below is my result
Please enter number of digit: 3
Please enter the 3 digit number: 123
Output:
3 2 1
Expected output:
1 2 3
int num;
int digit;
// int final;
int n;
int counter;
printf("Number of digits: ");
scanf("%d", &num);
printf("\nDigit number: ", num);
scanf("%d", &n);
counter = 0;
while (counter < n) {
digit = n % 10;
n = n / 10;
counter++;
printf("%d ", digit);
}
Use the %n specifier to confirm that the required number of digits are entered. With an int this may be about 10 digits.
Since the first effort produced a reversed result, reverse the number twice to get the desired output.
Pay attention to inputs such as 1000 and 0001 to print the correct leading and trailing zeros.
Check the return of scanf, an input of abc can't be parsed as an integer and scanf will return zero. scanf returns the number of items scanned.
#include <stdio.h>
int main( void) {
int num = 0;
int digits = 0;
int digit = 0;
int zeros = 0;
int temp = 0;
int reverse = 0;
int counter = 0;
int start = 0;
int stop = 0;
printf("Number of digits: ");
fflush ( stdout);
if ( 1 == scanf("%d", &digits)) {
printf("\nDigit number: ");
fflush ( stdout);
if ( 1 == scanf(" %n%d%n", &start, &num, &stop)) {
if ( digits != stop - start) {
fprintf ( stderr, "enter %d digit number\n", digits);
return 0;
}
counter = 0;
temp = num;
zeros = digits;
while (temp) {//reverse number
reverse *= 10;
reverse += temp % 10;
temp = temp / 10;
zeros--;//deduct for leading zeros
}
counter = 0;
while ( zeros) {//print leading zeros
counter++;
zeros--;
printf ( "0 ");
}
while (counter < digits) {//reverse again and print
digit = reverse % 10;
reverse = reverse / 10;
counter++;
printf("%d ", digit);
}
printf("\n");
}
else {
fprintf ( stderr, "could not parse number\n");
return 0;
}
}
else {
fprintf ( stderr, "could not parse number of digits\n");
return 0;
}
return 0;
}
Print out the numbers without using arrays but only basic while loop and pow function.
This specifies use of pow(), a floating point function, to solve an integer problem - not a good strategy to learn.
Further, "%d" is an array so "without using arrays" is unclear.
The following meets the restrictions imposed.
void foo(int count, int i) {
if (count > 1) {
foo(count - 1, i / 10);
for (int space = 0; space < 5; space++) {
putchar(' ');
}
}
putchar(i%10 + '0');
}
int main() {
foo(3, 123);
}
Output:
1 2 3
I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?
#include <stdio.h>
int main()
{
int i, x, n, c, j;
int d=0;
printf ("enter total digits in number: ");
scanf ("%d", &i);
printf ("\nenter number: ");
scanf ("%d", &n);
j=n;
for (x=1; x<=i; x++)
{
c= j%10;
d=c*(10^(i-x))+d;
j=(j-c)/10;
}
if (d==n)
{
printf ("\npalindrome");
}
else
{
printf ("\nnon palindrome");
}
return 0;
}
^ is the xor operator.
In order to raise power, you need to include math.h and call pow
d = (c * pow(10, i - x)) + d;
this algorithm is as simple as human thinking, and it works
#include <stdio.h>
int main() {
int i=0,n,ok=1;
char buff[20];
printf("Enter an integer: ");
scanf("%d", &n); // i am ommiting error checking
n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
if(n<2) return 0;
i=n/2;
n--;
while(i && ok) {
i--;
//printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
ok &= (buff[i]==buff[n-i]);
}
printf("%s is %spalindrome\n",buff, ok?"":"not ");
return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, rn, tn;
printf("Enter an integer: ");
scanf("%d", &n);
// reverse the number by repeatedly extracting last digit, add to the
// previously computed partial reverse times 10, and keep dropping
// last digit by dividing by 10
for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
if (rn == n) printf("%d is palindrome\n", n);
else printf("%d is not palindrome\n", n);
}
A loop like this might do:
int src; // user input
int n; // no of digits
int res = 0;
int tmp; // copy of src
// .... read the input: n and src ....
tmp = src;
for(int i = 0; i < n; i ++)
{
int digit = tmp % 10; // extract the rightmost digit
tmp /= 10; // and remove it from source
res = 10*res + digit; // apend it to the result
}
// ...and test if(res == src)...