C Variables – Examples

1. Declaring and Initializing Variables

#include <stdio.h>

int main() {
int age = 25; // integer variable
float height = 5.9; // float variable
char grade = 'A'; // character variable

printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Grade: %c\n", grade);

return 0;
}

Output:

Age: 25
Height: 5.9
Grade: A

2. Changing Variable Values

Variables can change values during program execution:

#include <stdio.h>

int main() {
int counter = 10;
printf("Initial Counter: %d\n", counter);

counter = 20; // updating value
printf("Updated Counter: %d\n", counter);

counter += 5; // using compound operator
printf("After Increment: %d\n", counter);

return 0;
}

Output:

Initial Counter: 10
Updated Counter: 20
After Increment: 25

3. Declaring Multiple Variables

#include <stdio.h>

int main() {
int a = 5, b = 10, c = 15; // multiple integers
float x = 1.1, y = 2.2; // multiple floats
char grade1 = 'A', grade2 = 'B'; // multiple characters

printf("a = %d, b = %d, c = %d\n", a, b, c);
printf("x = %.1f, y = %.1f\n", x, y);
printf("grade1 = %c, grade2 = %c\n", grade1, grade2);

return 0;
}

Output:

a = 5, b = 10, c = 15
x = 1.1, y = 2.2
grade1 = A, grade2 = B

4. Using scanf() to Assign Variable Values

#include <stdio.h>

int main() {
int age;
float height;
char grade;

printf("Enter your age: ");
scanf("%d", &age);

printf("Enter your height: ");
scanf("%f", &height);

printf("Enter your grade: ");
scanf(" %c", &grade); // space before %c to consume newline

printf("\nYou entered:\n");
printf("Age: %d\nHeight: %.1f\nGrade: %c\n", age, height, grade);

return 0;
}

Sample Output:

Enter your age: 25
Enter your height: 5.9
Enter your grade: A

You entered:
Age: 25
Height: 5.9
Grade: A


5. Example: Using Variables in Calculations

#include <stdio.h>

int main() {
int num1, num2, sum;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);

sum = num1 + num2; // calculation
printf("Sum = %d\n", sum);

return 0;
}

Sample Output:

Enter two numbers: 10 20
Sum = 30

Key Points from Examples:

  1. Variables must be declared before use.

  2. You can assign values during declaration or later.

  3. Multiple variables of the same type can be declared together.

  4. Use printf() to display values and scanf() to take input.

  5. Variable values can be updated or used in calculations anytime.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *