user3197769
user3197769

Reputation: 21

How to make a C program that finds the numbers in the array and then multiplies it?

I wanted to make a C program that finds the numbers in the input array and then multiplies it all together, I made the program but it got an issue that I don't know, can anybody help me with it!?

Here is the code!

#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char t[10];
  int n, z;
  n = 0;

  printf ("please enter a code: \n");
  scanf ("%s", t);
  while (n != '\0')
    {
      if (isdigit (t[n] == 0))
        {
          n++;
        }
      else
        {
          z = t[n];
          z *= z;
        }
    }
  printf ("%d", z);
}

Upvotes: 0

Views: 119

Answers (4)

chouaib
chouaib

Reputation: 2817

#include <stdio.h>
#include <string.h>

main()
{
   char a[5] ;
   int b=1, n=0,m=0;
   scanf("%s",a);

   while (n <5 )
   {
       if (!isdigit(a[n])) 
       {
           n++;
           m++;
       }
       else{
           b *= (a[n]-'0');
           n++;
       }
   }

   if(m==5) b=0;
   printf("%d\n",b);

}

Upvotes: 0

Klas Lindb&#228;ck
Klas Lindb&#228;ck

Reputation: 33273

Here is updated code. There is a comment for each bug that needed correction. (Note that the comment describes the intention of the corrected code, it doesn't describe the bug.)

int temp;

z=1;                          // Initialize z
printf ("please enter a code: \n");
scanf ("%s", n);
while (t[n] != '\0') {        // While there are more characters in the string 
  if (isdigit (t[n])) {       // Check if the character is a digit
      temp = t[n] - '0';      // Convert character digit to corresponding number.
      z *= temp;
  }
  n++;
}

Upvotes: 1

Kiran
Kiran

Reputation: 11

z should be initialized to 1. and remove "z = t[n];"

Upvotes: 0

Sergey L.
Sergey L.

Reputation: 22542

Your first problem is that you don't actually use t in your while loop. Your while loop only uses n which is set to 0 and never modified.

Your second problem is that you may be better off to use scanf("%d", &number); to scan numbers straight away.

Upvotes: 0

Related Questions