#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b,c;
b=1;
a=0;
scanf("%d", &a);
while (a>0)
{
c=a%10;
if (c==0)
b=b*1;
else {
b=b*(a%10);
a=a/10;
}
}
printf("Proizvedenie: %d\n", b);
return 0;
}
It doesnt work when I add 0 in any position of number, but i added if and dont know why it doesnt work, cycle just does not end, pls help
01234 - 24; Right
1234 - 24; Right
12304 - doesnt work
12340 - doesnt work
WHY PLS HELP =(
You're only dividing a by 10 when the current digit is not 0. When the digit is 0 a stays the same and you and up in an infinite loop.
Move the update of a to outside of the if block. Also, b=b*1 is a no-op, so you can remove that.
while (a>0)
{
c=a%10;
if (c!=0) {
b=b*c;
}
a=a/10;
}
You're only doing a = a/10 in the else block. So when you get to a 0 digit, you stop dividing by 10 and get stuck in an infinite loop.
Take that line out of the if/then, since it needs to be done every time.
while (a>0)
{
c=a%10;
if (c!=0) {
b *= c;
}
a /= 10;
}
unsigned int product(int x)
{
int result = !!x;
while(x)
{
if(x % 10) result *= abs(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
int testData[] = {0, 1234, 12304, 12340, -1234, -12304, -012340 /* <- octal number!! */};
for(int x = 0; x < sizeof(testData)/sizeof(testData[0]); x ++)
printf("%d - %u\n", testData[x], product(testData[x]));
}
https://godbolt.org/z/T8T1a5YEE
Use functions.
integers can be negative as well
You need to handle zero too.
In your code:
c=a%10;
if (c==0)
b=b*1;
else {
b=b*(a%10);
a=a/10;
}
you need to move a = a / 10 outside the if as it is only executed when a % 10 is not zero. If it is, a does not change and you are in an infinitive loop
Others have noted the flaw in your code (location of a=a/10; inside else code block.
Here is a branchless way to achieve your objective. "Branching" (using an if() conditional) can make code run much slower when the processor's pipeline prediction turns out to be wrong. When processing millions (or billions) of data items, this may be a significant cost in time.
#include <stdio.h>
#include <stdlib.h>
int main() {
int a = 0, prod = 1;
if( scanf( "%d", &a ) != 1 ) {
fprintf( stderr, "scanf failed\n" );
return 1;
}
for( a = abs(a); a; a /= 10 ) {
int r = a%10;
prod *= r+(r==0); // branchless technique
}
printf( "Proizvedenie: %d\n", prod );
return 0;
}
54300012
Proizvedenie: 120
When the value of r is one of 1-9, r==0 has the value 0.
When the value of r is 0 and r==0 has the value 1.
So the 10 different rhs values can be 1, 1, 2, 3, 4, 5, 6, 7, 8 or 9.
Related
So I need to calculate the reverse of a number using pointers in a function. I get junk memory when I run it.Here is what I tried.(When I remove the p ,it works, I don't get any junk memory but than I can calculate only the remainder , I don't get why?)
I m sorry for the earlier post. I read the rules of Stack Overflow.
Here is the code:
int Invers(int x , int *Calculinvers ){
int rem = 0;
int p = 1
while(x!=0){
rem = x % 10 ;
*Calculinvers = p*10 + rem;
x = x / 10;
}
return *Calculinvers;
}
int main(){
int a;
printf("Introduceti numarul caruia vreti sa-i calculati inversul : \n");
scanf("%d" , &a);
int Calcul;
Invers(a , &Calcul);
printf("Inversul numarului este : %d\n" , Calcul);
return 0;
}
Two problems and fixes:
(1)*Calculinvers needs to be initialized to 0, or system will give you unexpected value.
(2)Replace *Calculinvers = p*10 + rem; to *Calculinvers = *Calculinvers*10 + rem; because you did not add the previous value.
I threw together this, it seems to work:
#include <stdio.h>
int reverse(int x)
{
out = 0;
while (x != 0)
{
const int ones = x % 10;
out *= 10;
out += ones;
x /= 10;
}
return out;
}
int main(void) {
const int num[] = { 0, 1, 10, 47, 109, 4711, 1234, 98765432 };
printf("I got:\n");
for (int i = 0; i < sizeof num / sizeof *num; ++i)
{
printf(" %d -> %d\n", num[i], reverse(num[i]));
}
return 0;
}
It prints:
I got:
0 -> 0
1 -> 1
10 -> 1
47 -> 74
109 -> 901
4711 -> 1174
Obviously when we're working with actual integers, trailing zeroes turn into leading zeroes which don't really exist unless we store the original number's length and pad when printing. That's why 10 turns to 1, for instance.
This is better suited as a pure string-space operation, since then each digit exists as part of the string rather than as part of the representation of a number (which has other conventions).
Update:
If you really want to use pointers, you can of course wrap the above in a more pointery shroud:
void reverse_at(int *x)
{
const int rev = reverse(*x);
*x = rev;
}
but as stated in comments (and hopefully illustrated by my code) a more functional approach where the return value calues the result of a function is generally more easily understood, safer, and just better.
I'm trying to print prime numbers between 0 and 100 but my code ends up giving 2,3 and every number from 5 to 99. What am I doing wrong?
#include <stdio.h>
#include<math.h>
void main()
{
int n=0,i=2,flag;
while(n<=100){
if(n<2){flag=0;}
else if(n==2 || n==3){printf("%d\n",n);}
else{
while(i<=sqrt(n)){
if(n%i==0){flag=0;break;}
else{flag=1;}
i++;//at this point no. is prime
}
if(flag==1){printf("%d\n",n);}
}
n++;
}
}
Rather than testing inside the loop for n==2 || n==3, you should just print the values 2 and 3 outside the loop, and start the loop at 5. Since no even numbers are prime after 2, only test odd numbers starting at 5. And you need to start testing for factors starting at i=3 (since you know they're not even you don't have to test 2). And you shouldn't check the value of flag (for primality) until the i-loop is done.
#include <stdio.h>
#include <math.h>
int main(void)
{
printf("2\n3\n");
for (int n = 5; n <= 100; n+= 2) {
int flag = 1;
for (int i = 3; i <= sqrt(n); ++i) {
if (n % i == 0) {
flag = 0;
break;
}
}
if (flag == 1)
printf("%d\n",n);
}
}
I think the problem is with the for-loop but I cannot understand it. This is an assignment in school that I only should use for-loops and if statements to solve!
#include <stdio.h>
int is_prime(int n){
for (int i=2;i<n;i++){
if (n%i!=0){
return 1;
}
else{
return 0;
};
};
}
int main(void){
printf("%d\n", is_prime(11)); // 11 is a prime. Should print 1.
printf("%d\n", is_prime(383)); // 383 is a prime. Should print 1.
printf("%d\n", is_prime(987)); // 987 is not a prime. Should print 0.
}
For starters the null statement after the if statement and the for loop itself
for (int i=2;i<n;i++){
if (n%i!=0){
return 1;
}
else{
return 0;
};
^^^
};
^^^
is redundant.
Due to the if statement the for loop is interrupted as soon as either n % i is not equal to 0 or is equal to 0. So in general the behavior of the function does not depend on whether the passed number is prime or not prime.
If you will move the return statement
return 1;
outside the loop as others advised nevertheless the function will be still incorrect. It will show that 0 and 1 are prime numbers while they are not.
Also the condition of the loop makes the loop inefficient at least because it is clear before entering the loop that any even number except 2 is not a prime number.
Pay attention to that the function parameter should have unsigned integer type.
The function can be defined the following way
#include <stdio.h>
int is_prime( unsigned long long int n )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned long long int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
return prime;
}
int main(void)
{
printf( "%d\n", is_prime( 11 ) );
printf( "%d\n", is_prime( 383 ) );
printf( "%d\n", is_prime( 987 ) );
return 0;
}
The program output is
1
1
0
The problem is return 1 inside the loop. When you find one i that is not a factor of n, you assume n to be prime. But you have to ensure that all i are not a factor of prime, so the return 1 must be placed after the loop. However, that would cause numbers < 2 to be considered prime, as they do not enter the loop at all. Therefore, you also have to add an additional if at the beginning.
By the way: Every divisor of n (expect n itself) must be <= sqrt(n), therefore you can speed up your function quite a bit.
#include <math.h>
int is_prime(int n) {
if (n < 2)
return 0;
int max_divisor = sqrt(n);
for (int i = 2; i <= max_divisor; i++) {
if (n % i == 0)
return 0;
}
return 1;
}
Problem: return statement
return 1;
}
else{
return 0;
It causes the loop to exit then and there. In your case too, it exits as soon as the first '1' is achieved.
Solution: Instead you should try to store the values in a variable and compare with '1' or '0' at the end of loop
I am trying to code a Fibonacci generator, and so far I was able to calculate it and got accurate results, but I keep receiving trailing commas and I wanted to add a period(.) at the end of the result.
#include <stdio.h>
int f1=0,f2=1,i,sum=0,n,a;
printf("Please enter the number for Fibonacci numbers.\n");
scanf("%d",&n);
if(n==0){
printf("%d.",n);
}
else if(n==1){
a = n-1;
printf("%d, %d.",a,n);
}
else{
for(i=0;i<=n;i++){
printf("%d, ",f1);
sum = f1+f2;
f1 = f2;
f2 = sum;
}
}
return 0;
}
For example, n = 6
I wanted:
0, 1, 1, 2, 3, 5, 8.
What I got earlier:
0, 1, 1, 2, 3, 5, 8,
Fetching the idea from the comments:
// I'd prefer unsigned as negative numbers are meaningless anyway
unsigned int f1 = 0, f2 = 1;
unsigned int n = 7;
printf("0"); // 0 is printed in *any* case
while(--n) // or with for loop from 0 as long as < (not <= any more!)
// note the first value *is* printed already
{
printf(", %d", f2); // prepending the comma, one value is already there
// f2: now using the larger of the two,
// as the smaller *is* printed already
unsigned int sum = f1 + f2; // (limiting scope of to where it
// actually is needed)
f1 = f2;
f2 = sum;
}
puts(".");
Bonus: No special cases necessary any more...
Just start the loop with the second number :-)
else{ else{
printf("0"); // 0 here
for(i=0;i<=n;i++){ for(i=1;i<=n;i++){ // start at 1
printf("%d, ",f1); printf(", %d",f1); // change order
sum = f1+f2; sum = f1+f2;
f1 = f2; f1 = f2;
f2 = sum; f2 = sum;
} }
printf(".\n"); // add period
} }
If it was me, i'd keep the code simple, i wouldn't use negative indices, and i wouldn't start from position 1 instead of 0. What I would do is as follows:
#include <stdio.h>
int main(){
// Always initialise variables, integers cost nothing to initialise
// We use long because Fibonacci numbers can get quite large quite quickly.
long long int f1=0,f2=1,iterations=0;
printf("Please enter the number for Fibonacci numbers.\n");
if(scanf("%lld",&iterations)!=1){
// This means we've failed to read a number.
puts("Something is wrong with the input, exiting.");
return -1;
}
// ++iterations; // uncomment if you want iterations+1 Fibonacci numbers
for(long long int i=0;i<iterations;++i){
printf("%lld",f1);
int f3=f1+f2;
f1=f2;
f2=f3;
if(i<iterations-1){
printf(", ");
}
}
if(iterations>0){
puts(".");
}
return 0;
}
To compile and run:
martyn#Atlas:~$ gcc Deleteme.c
martyn#Atlas:~$ ./a.out
Please enter the number of Fibonacci numbers.
6
0, 1, 1, 2, 3, 5.
martyn#Atlas:~$
Note that your original program outputs 7 Fibonacci numbers, rather than 6. If you want 1 more than you input, then increment iterations before the loop, by doing something like ++iterations;
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char **argv)
{
int n = argc > 1 ? strtol(argv[1], NULL, 0) : 10;
int f[2] = {1,1};
while( n-- ) {
printf("%d%s", f[0], n ? ", " : ".\n");
int t = f[0] + f[1];
f[0] = f[1];
f[1] = t;
}
return 0;
}
I have a question: I’m supposed to build a program where when I enter an integer below a hundred, all numbers smaller than said integer and containing the digit “3″ appear on the screen (etc, if I enter 14, the numbers “3, 13″ should appear).
However, there’s something wrong with my code, please help! Thank you!
The code:
#include <stdio.h>
int main(int argc, const char * argv [])
{
int wholenumber;
printf("百以内の整数を入力してください\n");
scanf_s("%d", &wholenumber);
while(0 <wholenumber)
{
wholenumber--;
while(0 < wholenumber){
wholenumber = 3 %10;
wholenumber = 3 /10;
if (wholenumber == 3);
{printf("%3d",wholenumber);}
}
}
return 0;
}
If x is an integer between 0 and 99, the following will check whether either of its digits is a 3:
if (x / 10 == 3 || x % 10 == 3) {
...
}
I leave the rest as an exercise for the reader.
I have no idea what your intention was with this code:
wholenumber = 3 % 10;
wholenumber = 3 / 10;
First line sets the variable to 3, the second to 0.. which forces the program to exit from the loop.
Code:
#include<stdio.h>
int main()
{
int i,num;
int t1,t2; // Variable to store data temporary
printf("\nEnter the number : \n");
scanf("%d",&num);
for(i=0;i<num;i++)
{
t1= i/10;
t2= i%10;
if((t1==3) || (t2 ==3)) //check if number has 3 in it
printf(" %d", i);
}
return 0;
}
This is code which is required.Thanks to #amulous for pointing out mistake.
Note: It is assumed that entered number is less than 100 as required by user who asked question.
#include <stdio.h>
int contain3(int n){
if(n == 0) return 0;
return (n % 10 == 3) ? 1 : contain3(n/10);
}
int main(void){
int i, wholenumber;
printf("百以内の整数を入力してください\n");
scanf_s("%d", &wholenumber);
for(i=3;i<wholenumber;++i)
if(contain3(i))
printf("%3d", i);
return 0;
}
#include <stdio.h>
#include <limits.h>
int main(void){
int i, wholenumber;
int data[]={3,13,23,30,31,32,33,34,35,36,37,38,39,43,53,63,73,83,93,INT_MAX};
printf("百以内の整数を入力してください\n");
scanf_s("%d", &wholenumber);
for(i=0;data[i]<wholenumber;++i)
printf("%3d", data[i]);
return 0;
}
OP solution is conceptionallly close but needs changes.
The while() loop test destroys wholenumber. The test for '3' containment should use a copy of wholenumber
the syntax of wholenumber = 3 /10; should be wholenumber_test /= 10;
other syntax errors.
void whole(int wholenumber, int digit) {
while (0 < wholenumber) {
int test = wholenumber; // form test value
while (0 < test) {
if ((test%10) == digit) {
printf("%3d\n", wholenumber);
break; // no need to test other digits
}
test /= 10; // move onto next digit
}
wholenumber--;
}
}
You can write this more efficiently, and this will work for any upper limit:
#include <stdio.h>
int main(int argc, const char * argv [])
{
int wholenumber;
printf("百以内の整数を入力してください\n");
scanf("%d", &wholenumber);
for (int tens = 1; tens < wholenumber; tens *= 10) {
for (int i = 3 * tens; i < wholenumber; i+= 10*tens) {
printf("%3d\n", i);
}
}
return 0;
}