# C Program to check if a number belongs to a particular base or not

CServer Side ProgrammingProgramming

Given a number as a string and a base; the task is to check whether the given number of is of that given base or not.

We have to check the number and the base according to the number system in which there are bases like 2 for a binary number, 8 for an octal number, 10 for decimal number and 16 for a Hexadecimal number. According to this we have to find whether the given number in a string belongs to a particular base or not, If it belongs to a particular base then we have to print “Yes” on the output screen; else “No” on an output screen.

Like we know that, the number/expression “1A6” is of the base 16 and “1010” is of base 2, but this can be judged by just visually analysis now we have to find a way to solve the problem with help of a program.

## Example

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

Approach we will be using to solve the given problem

• Check if the base lies between 2 to 16.
• Then will check each digit of a strig belongs to the particular base or not.
• If it belongs to then return true, else 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 are till 16 (Hexadecimal)
if (base > 16)
return false;
// If base is below or equal to 10, then all
// digits should be from 0 to 9.
else if (base <= 10) {
for (int i = 0; i < strlen(str); i++)
if (!(str[i] >= '0' and
str[i] < ('0' + base)))
return false;
}
// If base is below or equal to 16, then all
// digits should be from 0 to 9 or from '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

yes