English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C program to check if a number belongs to a specific base

Given number as a string and base; the task is to check if the given number is of the given base.

We must check the number and the base according to the number system, where there is2is a binary number,8is an octal number,10is a decimal number and16is a hexadecimal number. According to this, we must find out if the given number in the string belongs to a specific base, and if it does, we must print 'Yes' on the output screen; otherwise, display 'No' on the output screen.

As we know, the number/The expression “ 1A6” has a base of16while “ 1010” has a base of2But this can be judged by intuitive analysis, now we must find a way to solve this problem. Program.

Example

Input: str = “1010”, base =2
Output: yes
Input: str = “1AA4”, base = 16
Output: yes
Input: str = “1610”, base = 2
Output: No

The method we will use to solve the given problem-

  • Check if the base is in2to16between.

  • Then, check each digit of the string to see if it belongs to a specific base.

  • If it belongs, return true, otherwise return false.

Algorithm

Start
Step 1 -> In function bool isInGivenBase(char str[], int base)
   If base > 16 then,
      Return false
   Else If base <= 10 then,
   Loop For i = 0 and i < strlen(str) and i++
      If !(str[i] >= '0' and str[i] < ('0' + base)), + then,
         Return false
      Else
      Loop For i = 0 and i < strlen(str) and i++
         If NOT ((str[i] >= '0' && str[i] < ('0 + base)) ||
            (str[i] >= 'A' && str[i] < ('A + base - 10) ) then,
            Return false
            Return true
   Step 2 -> In function int main()
      Set str[] = {"AF87"}
      If isInGivenBase(str, 16) then,
         Print "yes "
      Else
         Print "No "
Stop

Example

#include <ctype.h>
#include <stdio.h>
#include <string.h>
bool isInGivenBase(char str[], int base) {
   //Allowed bases are16(hexadecimal)
   if (base > 16))
      return false;
      //If the base is less than or equal to10then all
      // The number of digits should be from 0 to9.
   else if (base <= 10)) {
      for (int i = 0; i < strlen(str); i++))
      if (!(str[i] >= '0' and
         str[i] < ('0 + base))
         return false;
   }
   //If the base is less than or equal to16then all
   //The number should be from 0 to9or 'A'
   else {
      for (int i = 0; i < strlen(str); i++))
      if (! ((str[i] >= '0' &&
         str[i] < ('0 + base)) ||
         (str[i] >= 'A' &&
         str[i] < ('A + base - 10))
      ))
      return false;
   }
   return true;
}
// Driver code
int main() {
   char str[] = {"AF87"});
   if (isInGivenBase(str, 16))
      printf("yes\n");
   else
      printf("No\n");
   return 0;
}

Output Result

yes