C Programming

Variable Declarations and Data Types

Variable Declarations

Variable declarations specify the type and name of a variable before it can be used in a program.

The memory cells used for storing a program's input data and its computational results are called variables because the values stored in variables can change during the execution of the program.

The variable declarations in a C program communicate to the C compiler the names of all variables used in a program.

They also specify the type of data that can be stored in each variable and how the memory for each variable is allocated.

In C, a variable declaration has the following syntax:

data_type variable_name;

Thus, you specify the data type, followed by a space and then the variable name. Every statement ends with a semicolon so the declaration also ends with a semicolon.

Where data_type specifies the type of data that the variable can hold (e.g., int, float, char, etc.) and variable_name is the name of the variable.

For example, the declaration int radius; tells the compiler that the variable radius can hold integer values and that the compiler should allocate memory for it accordingly.

Variable declarations are typically placed at the beginning of a function, before any executable statements.

In the example program, the variable declarations are:

int radius;

float area;

These declarations tell the compiler that the program will use two variables: radius of type int and area of type float.

After the variable declarations, the program can use these variables to store and manipulate data.

In the example program, the variable radius is used to store the radius of a circle, and the variable area is used to store the calculated area of the circle.

Variable declarations are essential for the compiler to understand how to allocate memory and perform operations on the variables correctly.

Variable declarations reserves memory space for each variable based on its data type.

Using a variable without declaring it first is like trying to conceive with no womb

Explanation to the womb analogy

A womb provides the necessary space, environment, and structure for something to exist and grow. If you try to use a variable (the "child") without declaring it (the "womb"), the computer has no memory allocated to hold that data.

The Declaration: You're telling the system, "Hey, I need some space reserved for something specific."

The Error: Without that declaration, the compiler or interpreter hits a wall. It doesn't know what the variable is, how much space it needs, or where it's supposed to live.

The Result: In most strict languages (like C++ or Java), the program won't even start; in others (like JavaScript in strict mode), it'll throw a ReferenceError and crash

It is therefore important to declare variables before using them.

Data Types

Data types specify the type of data that a variable can hold and how much memory it will occupy.

In C, there are several basic data types, including:

  1. int: Used for integers (whole numbers). It typically occupies 4 bytes of memory and can store values from -2,147,483,648 to 2,147,483,647.
  2. float: Used for single-precision floating-point numbers (decimal numbers). It typically occupies 4 bytes of memory and can store values with a precision of about 7 decimal places.
  3. double: Used for double-precision floating-point numbers. It typically occupies 8 bytes of memory and can store values with a precision of about 15 decimal places.
  4. char: Used for single characters. It typically occupies 1 byte of memory and can store any character from the ASCII character set (values from -128 to 127).
  5. void: Used to indicate that a function does not return a value or to specify a pointer to an unknown type.

Examples of information to declare as int:

  1. Age of a person
  2. Number of students in a class
  3. Count of items in inventory
  4. Number of pages in a book
  5. Number of cars in a parking lot
  6. Number of days in a month
  7. Number of hours in a day
  8. Number of minutes in an hour
  9. Number of seconds in a minute
  10. Number of employees in a company
  11. Number of votes in an election
  12. Number of stars in a galaxy
  13. Number of planets in a solar system
  14. Number of countries in the world
  15. Number of languages spoken in a region
  16. Number of books in a library
  17. Number of songs in a playlist

You can therefore declare the above information as follows:

  1. int age = 25;
  2. int numStudents = 30;
  3. int itemCount = 100;
  4. int numPages;
  5. int numCars;
  6. int numDays;
  7. int numHours = 24;
  8. int numMinutes = 60;
  9. int numSeconds = 60;
  10. int numEmployees = 100;
  11. int numVotes = 1000;
  12. int numStars = 1000000;
  13. int numPlanets = 8;
  14. int numCountries = 195;
  15. int numLanguages = 7000;
  16. int numBooks = 10000;
  17. int numSongs = 100;

Note: you can declare a variable with or without an initial value.

As you can see, in example int numPages;, the variable is declared without an initial value.

The above statements reserves memory for each variable.

Examples of information to declare as float:

  1. Temperature in Celsius
  2. Height of a person in meters
  3. Weight of an object in kilograms
  4. Price of an item in dollars
  5. Distance between two cities in kilometers
  6. Speed of a car in miles per hour
  7. Time taken to complete a task in seconds
  8. Area of a circle in square meters
  9. Volume of a box in cubic centimeters
  10. Average score of students in a class
  11. Interest rate on a loan
  12. Percentage of students who passed an exam
  13. Body mass index (BMI) of a person
  14. Amount of rainfall in millimeters
  15. Length of a piece of string in centimeters
  16. Width of a rectangle in inches
  17. Depth of a swimming pool in feet
  18. Power output of an engine in horsepower
  19. Frequency of a sound wave in hertz

You can therefore declare the above information as follows:

  1. float temperature = 36.5;
  2. float height = 1.75;
  3. float weight = 70.5;
  4. float price = 19.99;
  5. float distance = 500.0;
  6. float speed = 60.0;
  7. float timeTaken = 120.5;
  8. float area = 78.5;
  9. float volume = 1000.0;
  10. float averageScore = 85.5;
  11. float interestRate = 3.5;
  12. float percentagePassed = 75.0;
  13. float bmi = 22.5;
  14. float rainfall = 50.0;
  15. float length = 100.0;
  16. float width = 50.0;
  17. float depth = 6.0;
  18. float powerOutput = 150.0;
  19. float frequency = 440.0;

Examples of information to declare as double:

  1. Distance from Earth to the Sun in kilometers
  2. Mass of the Earth in kilograms
  3. Speed of light in meters per second
  4. Gravitational constant in m^3 kg^-1 s^-2
  5. Planck's constant in J s
  6. Avogadro's number in mol^-1
  7. Boltzmann constant in J K^-1
  8. Electron charge in coulombs
  9. Pi (π) value
  10. Euler's number (e) value
  11. Golden ratio (φ) value
  12. Speed of sound in air at sea level in m/s
  13. Density of water at 4°C in kg/m^3
  14. Standard atmospheric pressure in Pa
  15. Radius of the Earth in kilometers
  16. Radius of the Moon in kilometers
  17. Radius of the Sun in kilometers
  18. Age of the universe in years
  19. Hubble constant in km/s/Mpc
  20. Salary of an employee

You can therefore declare the above information as follows:

  1. double distanceToSun = 149597870.7;
  2. double massOfEarth = 5.972e24;
  3. double speedOfLight = 299792458.0;
  4. double gravitationalConstant = 6.67430e-11;
  5. double plancksConstant = 6.62607015e-34;
  6. double avogadrosNumber = 6.02214076e23;
  7. double boltzmannConstant = 1.380649e-23;
  8. double electronCharge = -1.602176634e-19;
  9. double piValue = 3.141592653589793;
  10. double eulerNumber = 2.718281828459045;
  11. double goldenRatio = 1.618033988749895;
  12. double speedOfSound = 343.0;
  13. double densityOfWater = 1000.0;
  14. double atmosphericPressure = 101325.0;
  15. double radiusOfEarth = 6371.0;
  16. double radiusOfMoon = 1737.4;
  17. double radiusOfSun = 696340.0;
  18. double ageOfUniverse = 13.8e9;
  19. double hubbleConstant = 70.0;
  20. double salary;

Examples of information to declare as char:

  1. Grade of a student
  2. Initial of a person's name
  3. Gender of a person
  4. Status of a person (e.g., single, married, etc.)
  5. Blood type of a person (e.g., A, B, AB, O)
  6. Marital status (e.g., S for single, M for married, D for divorced, W for widowed)
  7. Type of a vehicle (e.g., C for car, T for truck, M for motorcycle)
  8. Grade level of a student (e.g., A, B, C, D, F)
  9. Type of a product (e.g., E for electronics, F for food, C for clothing)
  10. Type of a ticket (e.g., A for adult, C for child, S for senior)
  11. Type of a subscription (e.g., M for monthly, Y for yearly)
  12. Type of a payment method (e.g., C for credit card, D for debit card, P for PayPal)
  13. Type of a user (e.g., A for admin, U for user, G for guest)
  14. Type of a document (e.g., R for report, I for invoice, M for memo)
  15. Type of a file (e.g., T for text file, P for PDF file, I for image file)
  16. Type of a message (e.g., E for email, S for SMS, M for instant message)

You can therefore declare the above information as follows:

  1. char grade = 'A';
  2. char initial = 'J';
  3. char gender = 'M';
  4. char status = 'S';
  5. char bloodType = 'O';
  6. char maritalStatus = 'M';
  7. char vehicleType = 'C';
  8. char gradeLevel = 'B';
  9. char productType = 'E';
  10. char ticketType = 'A';
  11. char subscriptionType = 'M';
  12. char paymentMethod = 'C';
  13. char userType = 'U';
  14. char documentType = 'R';
  15. char fileType = 'T';
  16. char messageType = 'E';

In the above examples, we declare variables of type char to store single characters such as a grade, an initial, a gender, or a status.

Note that the character value is enclosed in single quotes (' ') when declaring a variable of type char.

Using the correct data type for each variable is important for efficient memory usage and to ensure that the program behaves as expected when performing operations on the variables.

For example, if you try to store a decimal number in an int variable, you will lose the decimal part and only the whole number will be stored. Similarly, if you try to store a large integer value in a char variable, it may cause an overflow and lead to unexpected results.

Therefore, it's crucial to choose the appropriate data type for each variable based on the kind of data it will hold and the operations that will be performed on it.

The ASCII Code

The ASCII (American Standard Code for Information Interchange) is a character encoding standard that assigns unique numbers to characters. Each character has a corresponding ASCII value, which can be used in programming.

For example, the ASCII value for the character 'A' is 65, and the ASCII value for 'a' is 97. This means that if you declare a variable of type char and assign it the value 'A', it will actually store the ASCII value 65 in memory.

In C, you can also use the ASCII values directly to assign values to char variables. For example, you can declare a variable as follows:

char letter = 65;

In this case, the variable letter will store the character 'A' because 65 is the ASCII value for 'A'.

Understanding the ASCII code is important when working with characters in C, as it allows you to manipulate and compare characters based on their ASCII values.

List of Common ASCII Values

Character ASCII Value
'A' 65
'a' 97
'0' 48
' ' 32
'\n' 10
'\t' 9
'!' 33
'@' 64
'#' 35
'$' 36
'%' 37
'^' 94
'&' 38
'*' 42
'(' 40
')' 41
'-' 45
'+' 43
'=' 61
'/' 47
'\\' 92