Post

Variables, Format Specifiers Of C

Variables, Format Specifiers Of C

In C, variables are used to store data values. A variable has a data type, a name, and a value. Here’s a breakdown of variables in C:


1.Declaring and Initializing Variables

To declare a variable:

1
data_type variable_name;
1
    int x;            //declaration

To declare and initialize:

1
data_type variable_name = value;
1
2
    int x;            //declaration
    x = 123;       //initialization

Example:

1
2
3
4
5
int age = 25;   // Integer variable
float gpa = 2.05;       //floating point number
char grade = 'C';        //single character
char name[] = "Bro"; //array of characters
float pi = 3.14;  // Floating-point variable

2.C Format Specifiers

Format specifiers in C are used with functions like printf() and scanf() to specify the type of data being printed or read.

1. Integer Format Specifiers

SpecifierDescriptionExample
%d or %iSigned integer (decimal)printf("%d", 42);
%uUnsigned integerprintf("%u", 42);
%oOctal integerprintf("%o", 42);52
%xHexadecimal (lowercase)printf("%x", 42);2a
%XHexadecimal (uppercase)printf("%X", 42);2A

2. Floating-Point Format Specifiers

SpecifierDescriptionExample
%fFloating-point (decimal notation)printf("%f", 3.14159);3.141590
%.nfFixed decimal places (n digits)printf("%.2f", 3.14159);3.14
%e or %EScientific notationprintf("%e", 3.14159);3.141590e+00
%g or %GShortest representation (%f or %e)printf("%g", 3.14159);3.14159

3. Character & String Format Specifiers

SpecifierDescriptionExample
%cCharacterprintf("%c", 'A');A
%sStringprintf("%s", "Hello");Hello

4. Pointer Format Specifier

SpecifierDescriptionExample
%pPrints memory addressprintf("%p", ptr);

5. Miscellaneous

SpecifierDescriptionExample
%%Prints%printf("%%");%

6. Width & Precision Modifiers

You can control the width and precision of output.

  • Width (%mX): Specifies minimum width.
  • Precision (%.nX): Controls decimal places for floating points.

Example:

1
2
3
printf("%10d", 42);   // Output: "        42" (right-aligned)
printf("%-10d", 42);  // Output: "42        " (left-aligned)
printf("%.2f", 3.14159); // Output: "3.14"

7. Example Program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

int main() {
    int num = 42;
    float pi = 3.14159;
    char ch = 'A';
    char str[] = "Hello";
    char name[] = "Bro"; //array of characters
    char grade = 'C';        //single character
    float gpa = 2.05;       //floating point number

    printf("Integer: %d\n", num);
    printf("Float: %.2f\n", pi);
    printf("Character: %c\n", ch);
    printf("String: %s\n", str);
    printf("Hexadecimal: %x\n", num);
    printf("Pointer: %p\n", (void*)&num);
    printf("Hello %s\n", name);
    printf("Your average grade is %c\n", grade);
    printf("Your gpa is %f\n", gpa);

    return 0;
}
This post is licensed under CC BY 4.0 by the author.