0% found this document useful (0 votes)
0 views

Explain different types of variables with Example

The document explains various types of variables in C, including local, global, static, automatic, and external variables, along with examples for each. It also covers branching statements such as if, if-else, else-if ladder, and switch statements, providing examples for decision-making in code. Additionally, it discusses loop statements (for, while, do-while) and operators (arithmetic, relational, logical, assignment) in C, with examples demonstrating their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Explain different types of variables with Example

The document explains various types of variables in C, including local, global, static, automatic, and external variables, along with examples for each. It also covers branching statements such as if, if-else, else-if ladder, and switch statements, providing examples for decision-making in code. Additionally, it discusses loop statements (for, while, do-while) and operators (arithmetic, relational, logical, assignment) in C, with examples demonstrating their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

1. Explain different types of variables with Example.

Types of Variables in C

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1()

int x=10;//local variable

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable


void function1()
{
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
void function1()
{
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented value
in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We
can explicitly declare an automatic variable using auto keyword.
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
External Variable
We can share a variable in multiple C source files by using an external variable. To declare an
external variable, you need to use extern keyword.

myfile.h
extern int x=10;//external variable (also global)
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
2. Explain branching statement in c with Example.

Branching Statements in C:
Branching statements in C allow the program to make decisions based on certain conditions.
These statements control the flow of execution and help in performing different actions based
on specific conditions. The primary branching statements in C are:

 if statement
 if-else statement
 else-if ladder
 switch statement

1. if Statement:

 The if statement is used to test a condition. If the condition is true, the block of code
inside the if is executed; if false, it is skipped.
 Syntax:
if (condition) {
// code to be executed if the condition is true
}

Example:
#include <stdio.h>

int main() {
int num = 10;

if (num > 0) {
printf("The number is positive.\n");
}

return 0;
}
In this example, since num is greater than 0, the message "The number is positive." will be
printed.
2. if-else Statement:
The if-else statement executes one block of code if the condition is true, and another block if
the condition is false.
Syntax:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example
#include <stdio.h>

int main() {
int num = -5;

if (num > 0) {
printf("The number is positive.\n");
} else {
printf("The number is non-positive.\n");
}

return 0;
}
 Here, since num is negative, the program will print "The number is non-positive."

3. else-if Ladder:
An else-if ladder is used when you have multiple conditions to check. It allows for checking
several conditions in sequence and executes the corresponding block of code for the first
condition that is true.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if none of the conditions are true
}
Example:

#include <stdio.h>

int main() {
int num = 0;

if (num > 0) {
printf("The number is positive.\n");
} else if (num < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}

return 0;
}
 In this case, the condition num == 0 is true, so "The number is zero." will be printed.

4. switch Statement:
The switch statement is used when you have multiple possible values for a variable and want
to execute different code blocks based on the value of that variable. It is an alternative to
using multiple if-else statements when you are comparing one variable to many possible
values.
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
case value3:
// code to be executed if expression == value3
break;
default:
// code to be executed if expression doesn't match any value
}
 break: Exits the switch block once a case is matched.
 default: If no case matches the expression, the code in the default block is executed.
Example:

#include <stdio.h>

int main() {
int day = 3;

switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}

return 0;
}
 Since day is 3, the program will print "Wednesday".
 If the day was not 1, 2, 3, 4, or 5, the default case would be executed.

3. Explain loop statement in c?


Loop Statements in C:
Loop statements in C are used to repeat a block of code multiple times based on a condition.
They allow you to execute a set of instructions repeatedly, which is essential for tasks that
require iteration. There are three main types of loops in C:

 for loop
 while loop
 do-while loop
Let’s break down each type:

1. for Loop:
The for loop is used when you know in advance how many times you want to repeat a block
of code. It’s commonly used for iterating over arrays or performing a fixed number of
iterations.
Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed in each iteration
}
Initialization: Defines the starting point (usually a variable).
Condition: Determines whether the loop will continue. The loop executes as long as this
condition is true.
Increment/Decrement: Updates the loop variable (e.g., increases or decreases it).
Example:
#include <stdio.h>

int main() {
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
Explanation: The loop will execute 5 times, printing "Iteration 1" to "Iteration 5".

2. while Loop:
The while loop is used when you want to repeat a block of code as long as a condition is true.
The condition is evaluated before the execution of the loop.

Syntax:
while (condition) {
// code to be executed while condition is true
}
The loop continues as long as the condition is true.
If the condition is false from the beginning, the code inside the loop won’t execute at all.
Example:
#include <stdio.h>
int main() {
int i = 1;

while (i <= 5) {
printf("Iteration %d\n", i);
i++; // Incrementing i
}

return 0;
}
Explanation: The loop continues as long as i <= 5. The value of i is incremented each time,
and the loop executes 5 times, printing "Iteration 1" to "Iteration 5".

3. do-while Loop:
The do-while loop is similar to the while loop, except that the condition is checked after the
loop body is executed. This guarantees that the code inside the loop will execute at least once,
even if the condition is initially false.

Syntax:
do {
// code to be executed
} while (condition);
The block of code is executed first, and then the condition is checked to see if the loop should
continue.
Example:

#include <stdio.h>

int main() {
int i = 1;

do {
printf("Iteration %d\n", i);
i++; // Incrementing i
} while (i <= 5);

return 0;
}
Explanation: The loop executes at least once even if i is initially greater than 5. After the first
iteration, it checks if i <= 5 to decide whether to continue.

Loop Control Statements:


There are a few control statements that can be used within loops to control the flow of
execution:

break: Exits the loop immediately, regardless of the condition.

Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exits the loop when i is 3
}
printf("Iteration %d\n", i);
}
continue: Skips the current iteration of the loop and moves to the next iteration.

Example:

for (int i = 1; i <= 5; i++) {


if (i == 3) {
continue; // Skips iteration when i is 3
}
printf("Iteration %d\n", i);
}

Nested Loops in C:
A nested loop in C refers to a loop inside another loop. It is used when you need to perform
repetitive actions in a multi-dimensional structure (like a matrix or grid) or when you need to
perform multiple iterations inside another iteration.
The outer loop controls the number of iterations for the entire process, and the inner loop
executes its entire cycle for every iteration of the outer loop.
1. Nested for Loop
Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the
equivalent flow diagram for nested ‘for’ loops:
Syntax:

for ( initialization; condition; increment ) {

for ( initialization; condition; increment ) {

// statement of inside loop


}

// statement of outer loop


}
2. Nested while Loop
A nested while loop refers to any type of loop that is defined inside a ‘while’ loop. Below is
the equivalent flow diagram for nested ‘while’ loops:
Syntax:

while(condition) {

while(condition) {

// statement of inside loop


}
// statement of outer loop
}
3. Nested do-while Loop
A nested do-while loop refers to any type of loop that is defined inside a do-while loop.
Below is the equivalent flow diagram for nested ‘do-while’ loops:
Syntax:

do{

do{

// statement of inside loop


}while(condition);

// statement of outer loop


}while(condition);
Note: There is no rule that a loop must be nested inside its own type. In fact, there can
be any type of loop nested inside any type and to any level.
Syntax:

do{

while(condition) {

for ( initialization; condition; increment ) {

// statement of inside for loop


}

// statement of inside while loop


}

// statement of outer do-while loop


}while(condition);

What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables.
Types of Operators in C
C language provides a wide range of operators that can be classified into 6 types based on
their functionality:

Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
1. Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on
operands. There are 9 arithmetic operators in C language:
Example of C Arithmetic Operators
// C program to illustrate the arithmatic operators
#include <stdio.h>
int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a + b = %d\n", a + b);
printf("a - b = %d\n", a - b);
printf("a * b = %d\n", a * b);
printf("a / b = %d\n", a / b);
printf("a % b = %d\n", a % b);
printf("+a = %d\n", +a);
printf("-a = %d\n", -a);
printf("a++ = %d\n", a++);
printf("a-- = %d\n", a--);

return 0;
}
Output
a + b = 30
a - b = 20
a * b = 125
a/b=5
a%b=0
+a = 25
-a = -25
a++ = 25
a-- = 26

2. Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.

These are a total of 6 relational operators in C:


Example of C Relational Operators
// C program to illustrate the relational operators
#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a < b : %d\n", a < b);
printf("a > b : %d\n", a > b);
printf("a <= b: %d\n", a <= b);
printf("a >= b: %d\n", a >= b);
printf("a == b: %d\n", a == b);
printf("a != b : %d\n", a != b);
return 0;
}
Output
a<b :0
a>b :1
a <= b: 0
a >= b: 1
a == b: 0
a != b : 1
Here, 0 means false and 1 means true.

3. Logical Operator in C
Logical Operators are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false.

Example of Logical Operators in C


// C program to illustrate the logical operators
#include <stdio.h>

int main()
{

int a = 25, b = 5;

// using operators and printing results


printf("a && b : %d\n", a && b);
printf("a || b : %d\n", a || b);
printf("!a: %d\n", !a);

return 0;
}
Output
a && b : 1
a || b : 1
!a: 0

4. Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left
side otherwise the compiler will raise an error.

The assignment operators can be combined with some other operators in C to provide
multiple operations using single operator. These operators are called compound operators.

In C, there are 11 assignment operators :


Example of C Assignment Operators
// C program to illustrate the assignment operators
#include <stdio.h>
int main()
{
int a = 25, b = 5;

// using operators and printing results


printf("a = b: %d\n", a = b);
printf("a += b: %d\n", a += b);
printf("a -= b: %d\n", a -= b);
printf("a *= b: %d\n", a *= b);
printf("a /= b: %d\n", a /= b);
printf("a %%= b: %d\n", a %= b);
printf("a &= b: %d\n", a &= b);
printf("a |= b: %d\n", a |= b);
printf("a >>= b: %d\n", a >>= b);
printf("a <<= b: %d\n", a <<= b);

return 0;
}
Output
a = b: 5
a += b: 10
a -= b: 5
a *= b: 25
a /= b: 5
a %= b: 0
a &= b: 0
a |= b: 5
a >>= b: 0
a <<= b: 0
Identifier
In C programming, an identifier is the name used to identify variables, functions, arrays, or
any other user-defined items. It is essentially a label or a name given to something in your
code. Here are the rules for creating valid identifiers in C:

 It must start with a letter (a-z, A-Z) or an underscore (_).


 The rest of the identifier can include letters, digits (0-9), or underscores.
 Identifiers are case-sensitive, so Variable, variable, and VARIABLE would be
considered three different identifiers.
 They cannot be a C keyword (like int, return, for, etc.).
Examples of valid identifiers:
count
_total
x1
maxValue
Examples of invalid identifiers:
1number (cannot start with a number)
int (it's a keyword)
#define (contains special characters)

Tokens
In C programming, tokens are the smallest units in a program. They are the building blocks
of the language and are recognized by the compiler. There are six types of tokens in C:

1. Keywords

Keywords are reserved words in C that have special meanings. They cannot be used as
identifiers (like variable or function names). Some examples include:

 int
 return
 if
 while
 for

2. Identifiers

Identifiers are names given to variables, functions, arrays, etc., as we discussed earlier.
Examples include:

 sum
 totalAmount
 maxValue

3. Constants

Constants are literal values that do not change. There are two types:

 Integer Constants: Numeric values like 10, -20, etc.


 Floating-point Constants: Values with a decimal point like 3.14, -0.005, etc.
 Character Constants: A single character enclosed in single quotes, e.g., 'A', '5'.

4. String Literals

These are sequences of characters enclosed in double quotes. For example:

 "Hello"
 "World"

5. Operators

Operators perform operations on variables and values. There are several types of operators in
C:

 Arithmetic Operators: +, -, *, /, %
 Relational Operators: ==, !=, <, >, <=, >=
 Logical Operators: &&, ||, !
 Assignment Operators: =, +=, -=, etc.
 Bitwise Operators: &, |, ^, <<, >>
 Increment/Decrement Operators: ++, --
 Conditional (Ternary) Operator: ? :

6. Punctuation (Separators)

These are symbols used to separate statements or parts of a program. Common punctuation
tokens include:

 Semicolon (;): Used to end statements.


 Comma (,): Used to separate variables or parameters.
 Parentheses (()): Used in function calls, expressions, etc.
 Curly Braces ({}): Used to define the beginning and end of code blocks or functions.
 Square Brackets ([]): Used to define arrays or access array elements.
 Period (.): Used to access members of a structure.
 Arrow (->): Used to access members of a structure via a pointer.

Example of Tokens in a C Program:

#include <stdio.h>
int main()
{
int x = 5; // x, =, 5 are tokens
if (x > 3) { // if, (, x, >, 3, ) are tokens
printf("x is greater than 3\n"); // printf, (, "x is greater than 3\n", ) are tokens
}
return 0; // return, 0 are tokens
}

Keywords

In C programming, keywords are reserved words that have special meaning and purpose
within the language. These words cannot be used as identifiers (names for variables,
functions, etc.), as they are part of the syntax of the language itself.
List of C Keywords
Here is a list of the 32 keywords in C:
1. auto - Used to define local variables (rarely used in modern C).
2. break - Exits from a loop or switch statement.
3. case - Used in a switch statement to mark a potential match.
4. char - Used to define a character type variable.
5. const - Defines constant values that cannot be modified.
6. continue - Skips the rest of the current loop iteration and proceeds to the next
iteration.
7. default - Specifies the default case in a switch statement.
8. do - Starts a do-while loop.
9. double - Defines a variable of type double-precision floating-point number.
10. else - Defines the alternative block of code in an if-else statement.
11. enum - Defines an enumerated type, allowing you to specify a set of named integer
constants.
12. extern - Specifies that a variable or function is defined in another file.
13. float - Defines a variable of type single-precision floating-point number.
14. for - Starts a for loop.
15. goto - Transfers control to another part of the program (use cautiously, as it can make
code harder to follow).
16. if - Defines a conditional statement.
17. inline - Requests the compiler to insert the code of a function directly at the point of
call (o int - Defines an integer variable.
18. long - Defines a long integer type (larger than int).
19. register - Suggests that a variable should be stored in a CPU register for fast access
(rarely used in modern C).
20. restrict - Used in pointer declarations to indicate that the pointer is the only way to
access a particular object (optimization hint).
21. return - Exits from a function and optionally returns a value.
22. short - Defines a short integer type (smaller than int).
23. signed - Specifies that a variable can hold both positive and negative values (default
for most integer types).
24. sizeof - Returns the size (in bytes) of a data type or object.
25. static - Defines a variable or function that has a permanent local scope or is limited to
the current file.
26. struct - Defines a structure type (a collection of different data types).
27. switch - Starts a switch statement, used to select one of many code blocks to execute.
28. typedef - Creates a new name (alias) for an existing data type.
29. union - Defines a union, which allows different types to share the same memory
location.
30. unsigned - Defines a variable that can only hold non-negative values.
31. void - Defines a function that does not return a value, or specifies an empty pointer
type.ptional optimization).
Important Notes:
Case Sensitivity: C keywords are case-sensitive, so int is a keyword, but Int or INT
would not be recognized as keywords.
Cannot Use as Identifiers: You cannot use these keywords as variable names, function
names, or any other identifiers in your program. For example, int and for cannot be used
as variable names.

Differences between Keyword and Identifier


Format Specifiers in C
The format specifier in C is used to tell the compiler about the type of data to be printed or
scanned in input and output operations. They always start with a % symbol and are used in
the formatted string in functions like printf(), scanf, sprintf(), etc.

The C language provides a number of format specifiers that are associated with the different
data types such as %d for int, %c for char, etc.
List of Format Specifiers in C
The below table contains the most commonly used format specifiers in C
Examples of Format Specifiers in C
1. Character Format Specifier – %c in C
The %c is the format specifier for the char data type in C language. It can be used for both
formatted input and formatted output in C language.

Syntax:
scanf("%d...", ...);
printf("%d...", ...);
2. Integer Format Specifier (signed) – %d in C
We can use the signed integer format specifier %d in the scanf() and print() functions or other
functions that use formatted string for input and output of int data type.

Syntax:
scanf("%d...", ...);
printf("%i...", ...);
Floating-point format specifier – %f in C
The %f is the floating point format specifier in C language that can be used inside the
formatted string for input and output of float data type. Apart from %f, we can use %e or %E
format specifiers to print the floating point value in the exponential form.

Syntax:
printf("%f...", ...);
scanf("%e...", ...);
printf("%E...", ...);

String Format Specifier – %s in C


The %s in C is used to print strings or take strings as input.

Syntax:
printf("%s...", ...);
scanf("%s...", ...);

Standard Output Function – printf()


The printf() function is used to print formatted output to the standard output stdout (which is
generally the console screen). It is one of the most commonly used functions in C.

Syntax

printf(“formatted_string”, variables/values);
Example
#include <stdio.h>
int main() {

// Prints some text


printf("First Print");

return 0;
}

Output
First Print
Explanation: The printf() function sends the string “First Print” to the output stream,
displaying it on the screen.

Standard Input Function – scanf()


scanf() is used to read user input from the console. It takes the format string and the addresses
of the variables where the input will be stored.

Syntax

printf(“formatted_string”, address_of_variables/values);

Remember that this function takes the address of the arguments where the read value is to be
stored.

Example
#include <stdio.h>

int main() {
int age;
printf("Enter your age: ");

// Reads an integer
scanf("%d", &age);

// Prints the age


printf("Age is: %d\n", age);
return 0;
}

Output:

Enter your age: 25 (Entered by the user)


Age is: 25
Explanation: %d is used to read an integer; and &age provides the address of the variable
where the input will be stored.

You might also like