Understanding Variables, Constants, Number Systems, and Division in C

Variable Declaration and Initialization in C

Declaration

A variable in C must be declared before it is used. A declaration tells the compiler the name and type of the variable.

Syntax

data_type variable_name;

For example:

int age;
float temperature;
char grade;

Here, age is an integer variable, temperature is a floating-point variable, and grade is a character variable.

Initialization

A variable can be initialized at the time of declaration:

Syntax

data_type variable_name = value;

For example:

 

int age = 25;
float temperature = 36.5;
char grade = ‘A’;

Constants in C

Constants are fixed values that do not change throughout the execution of a program. Constants in C can be represented in different number systems: decimal, binary, octal, and hexadecimal.

Decimal

A number in base 10 (0-9 digits):

int decimalNum = 100; // Decimal representation

Binary

A number in base 2 (0 and 1 digits), prefixed with 0b .

int binaryNum = 0b1010; // Binary for 10

Octal

A number in base 8 (0-7 digits), prefixed with 0

int octalNum = 012; // Octal 12 = Decimal 10

Hexadecimal

A number in base 16 (0-9 and A-F digits), prefixed with 0x

int octalNum = 012; // Octal 12 = Decimal 10

Number System Conversion

Binary to Decimal

To convert binary to decimal, multiply each bit by powers of 2 and sum them:
Example: 1011 in binary → 1×2³ + 0×2² + 1×2¹ + 1×2⁰ = 11

Octal to Decimal

Multiply each digit by powers of 8:
Example: 075 in octal → 7×8¹ + 5×8⁰ = 61


Hexadecimal to Decimal

Multiply each digit by powers of 16:
Example: 0x2F → 2×16¹ + 15×16⁰ = 47

Decimal to Other Bases

  • To Binary: Repeatedly divide by 2 and collect remainders.
  • To Octal: Repeatedly divide by 8 and collect remainders.
  • To Hexadecimal: Repeatedly divide by 16 and collect remainders.

Sample C Questions and Output

Example 1: Addition of Decimal and Octal Numbers

#include <stdio.h>

int main() {
int a = 15; // Decimal
int b = 0101; // Octal (Equivalent to 65 in decimal)

printf(“%d”, a + b); // Output: 80
return 0;
}

Output: 15 + 65 = 80 (since 0101 is interpreted as octal 65 in decimal)

Example 2: Hexadecimal and Octal Addition

#include <stdio.h>
int main() {
int x = 0xA; //Hexadecimal (equivalent to 10)
int y = 012; // //Octal (equivalent to 10)
printf(“%d”, x + y);
return 0;
}

Output: 10 + 10 = 20 (Hexadecimal 0xA is 10, Octal 012 is 10 in decimal)

Leave a Comment

Your email address will not be published.