Variables are a fundamental concept in computer programming. They are named storage locations that hold values that can change during the execution of a program. The key aspects of variables are:
Declaration: Variables are declared by specifying a name and a data type, which determines the kind of value the variable can hold (e.g. integer, float, string, etc.).
Initialization: Variables are typically initialized, or assigned an initial value, when they are declared. This gives the variable a starting value.
Naming Conventions: Variable names should be descriptive and follow the naming rules of the programming language, such as not starting with a number and avoiding special characters. Longer names are often preferred for clarity.
Scope: A variable's scope determines where in the program the variable can be accessed and modified. Variables can have local, global, or other scopes depending on how they are defined. Proper management of variable scope is crucial to avoid naming conflicts and unintended side effects.
Assignment and Retrieval: The value stored in a variable can be assigned and retrieved using the assignment operator (=). Variables act as containers that hold data for use throughout the program.
In summary, variables are essential building blocks of computer programs that allow for the storage and manipulation of data. Understanding how to properly declare, initialize, name, and manage the scope of variables is a fundamental skill for any programmer.
To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. For example:
int a = 40;
Here, age is a variable of int type and we have assigned an integer value 25 to it.
The value of a variable can be changed, hence the name variable.
char c = 'd';
// some code
c = 'l';
If you want to define a variable whose value cannot be changed, you can use the const keyword. This will create a constant. For example,
const double PI = 3.14;
Here, PI is a symbolic constant; its value cannot be changed.
const double PI = 3.14;
PI = 2.9; //Error
You can also define a constant using the #define preprocessor directive.
In C, the main types of literals are:
Represent whole numbers, such as 42, -10, 0b101010, 0x2A.
Can be expressed in decimal, binary (with 0b prefix), octal (with 0 prefix), or hexadecimal (with 0x prefix) formats.
Integer literals have a default type of int, but can also be long, long long, or unsigned variants.
Represent decimal numbers with a fractional part, like 3.14, -2.718, 1.0e6.
Can use scientific notation with an exponent (e.g., 1.0e-3).
Floating-point literals have a default type of double, but can also be float or long double.
Represent a single character enclosed in single quotes, such as 'A', '9', '\n'.
Can use escape sequences to represent special characters, like newline ('\n'), tab ('\t'), or Unicode characters.
Character literals have a type of int, but are often treated as char.
Represent a sequence of characters enclosed in double quotes, like "Hello, world!".
Can span multiple lines and include escape sequences.
String literals have a type of char * (pointer to char), representing an array of characters.
Represent the logical values true (1) and false (0).
Introduced in the C99 standard, but not available in older versions of C.
These literal types are used extensively in C programs to represent constant values, initialize variables, and build more complex expressions and data structures.
In C programming, data types are declarations for variables. This determines the type and size of data associated with variables. For example,
int age;
Here, age is a variable of int (integer) type. The size of int is 4 bytes.
Integers are whole numbers that can have both zero, positive and negative values but no decimal values. For example, 0, -5, 10
We can use int for declaring an integer variable.
int id;
Here, id is a variable of type integer.
You can declare multiple variables at once in C programming. For example,
int id, age;
The size of int is usually 4 bytes (32 bits). And, it can take 232 distinct states from -2147483648 to 2147483647.
float and double are used to hold real numbers.
float salary;
double price;
In C, floating-point numbers can also be represented in exponential. For example,
float normalizationFactor = 22.442e2;
What's the difference between float and double?
The size of float (single precision float data type) is 4 bytes. And the size of double (double precision float data type) is 8 bytes.
Keyword char is used for declaring character type variables. For example,
char test = 'h';
The size of the character variable is 1 byte.
void is an incomplete type. It means "nothing" or "no type". You can think of void as absent.
For example, if a function is not returning anything, its return type should be void.
Note that, you cannot create variables of void type.
If you need to use a large number, you can use a type specifier long. Here's how:
long a;
long long b;
long double c;
Here variables a and b can store integer values. And, c can store a floating-point number.
If you are sure, only a small integer ([−32,767, +32,767] range) will be used, you can use short.
short d;
You can always check the size of a variable using the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;
printf("size of short = %lu bytes\n", sizeof(a));
printf("size of long = %lu bytes\n", sizeof(b));
printf("size of long long = %lu bytes\n", sizeof(c));
printf("size of long double= %lu bytes\n", sizeof(d));
return 0;
}
In C, signed and unsigned are type modifiers. You can alter the data storage of a data type by using them:
signed - allows for storage of both positive and negative numbers
unsigned - allows for storage of only positive numbers
For example,
// valid codes
unsigned int x = 35;
int y = -35; // signed int
int z = 36; // signed int
// invalid code: unsigned int cannot hold negative integers
unsigned int num = -35;
Here, the variables x and num can hold only zero and positive values because we have used the unsigned modifier.
Considering the size of int is 4 bytes, variable y can hold values from -231 to 231-1, whereas variable x can hold values from 0 to 232-1.
printf (print formatted) in C, writes out a cstring to stdout (standard output). The provided cstring may contain format specifiers( beginning with % in the cstring).
If there are format specifiers, those are replaced with their respective arguments that follow the cstring to the printf call. These format specifiers may also contain its length, precision, and other flags.
Syntax:
int printf (const char* c-string, ...);
Return Value: If the function successfully executes, it returns the total number of characters written to the standard output. If an error occurs, a negative number is returned.
Arguments: c-string is the string passed to the function. There can be additional arguments following c-string, if there exist format specifiers in the c-string, as discussed above.
/* Example for printf() */
#include <stdio.h>
int main(){
printf ("Integers: %i %u \n", -3456, 3456);
printf ("Characters: %c %c \n", 'z', 80);
printf ("Decimals: %d %ld\n", 1997, 32000L);
printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.14159, 3.14159, 3.14159);
printf ("Preceding with empty spaces: %10d \n", 1997);
printf ("Preceding with zeros: %010d \n", 1997);
printf ("Width: %*d \n", 15, 140);
printf ("%s \n", "IT");
return 0;
}
The scanf function in C is used to read formatted input from the standard input stream (usually the keyboard). It reads data from the user and stores it in the specified variables. Here are some key points about scanf:
The basic syntax of scanf is:
int scanf(const char *format, ...);
int is the return type.
const char *format specifies the format string.
... indicates that the function accepts a variable number of arguments.
scanf uses format specifiers to determine how to read and store the input data. Some common format specifiers are:
%d for integers
%f for floating-point numbers
%c for characters
%s for strings
%ld for long integers
%lld for long long integers
Here is a simple example of using scanf to read an integer:
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}
scanf returns an integer value indicating the number of input items successfully matched and assigned. If no matches are made, scanf returns EOF.
Reading a Single Value: scanf can read a single value of a specified type. For example, to read an integer, you would use scanf("%d", &var);.
Reading Multiple Values: scanf can also read multiple values by separating the format specifiers with spaces. For example, to read an integer and a character, you would use scanf("%d %c", &var1, &var2);.
String Input: When reading strings, scanf considers whitespace as a terminating character, which can limit input to a single word. For multiple words, fgets is often used instead.
Error Handling: scanf returns a value indicating success or failure. If an error occurs, such as a read error or end-of-file, scanf returns a negative value.
Here is an example of reading multiple values:
#include <stdio.h>
int main() {
int age;
float height;
char initial;
char surname[20];
printf("Enter your age, height (in meters), first initial: ");
int result = scanf("%d %f %c", &age, &height, &initial);
if (result == 3) {
printf("You entered: Age = %d, Height = %.2f, Initial = %c\n", age, height, initial);
} else {
printf("Failed to read all values.\n");
}
printf("Enter a surname: ");
scanf("%s",surname);
printf("Your Surname is: %s",surname);
return 0;
}
This example demonstrates how scanf can be used to read multiple values and handle the results accordingly.