Programming in C - Module 2 - v1
Programming in C - Module 2 - v1
Module Number: 02
1
Data Types, Decision Control and Looping
Statements
Syllabus
Data Types, Input/Output Statements in C, Constants, Variables, Scope of Variables, Operators,
Expressions. Type conversion, Type casting, Decision control- if, if-then-else, nested if, nested
else. Looping statements- while, Do-While, for, switch, break continue and goto statements.
Type modifiers and storage class specifiers for data types.
2
Data Types, Decision Control and Looping
Statements
AIM:
The main aim is to understand the different data types, statements, variables, control structures,
Looping statements, Type modifiers and storage classes in C.
3
Data Types, Decision Control and Looping
Statements
Objectives:
The objectives of this module are to:
•Understand different data types, input/output statements in C.
•Interpret the usage of Constants, Variables, Operators and Expressions.
•Compare different decision control structures.
•Illustrate different looping statements.
•Discuss different type modifiers and storage class specifiers.
4
Data Types, Decision Control and Looping
Statements
Outcomes:
At the end of this module, the students will be abl:
•Explain different data types,input/output statements in C.
•Apply Constants, Variables, Operators & Expressions to different programs.
•Analyse different decision control structures.
•Demonstrate different looping statements.
•Implement different type modifiers and storage class specifiers.
5
Data Types, Decision Control and Looping
Statements
Table of Content:
• Data Types • Looping statements- while, Do-While, for.
• Input/Output Statements in C • Break continue and goto statements
• Constants & Variables • Type modifiers and storage class specifiers
• Scope of variables for data types.
• Operators & Expressions
• Type Casting & Type Conversion
• Decision control-if, if-then-else, nested if,
nested else.
6
Data Types, Decision Control and Looping
Statements
Data Types Character char, signed char,
(char) unsigned char
Void int, short int ,
Signed long int
Integer
(Int) int, short int ,
unsigned
Primary Data long int
types Float float, double, long
(float) double
Double
C Data Types
Array
Structure
Derived Data
types Pointers
Enums
typedefined
User defined
enumerated 7
Data Types, Decision Control and Looping
Statements
Data Types (Contd… )
• To become a powerful programming language, it should handle a brand range of data types.
Broadly C supports two different types of data types. The figure in the previous slide shows
the classification of C data types.
• C language is specially designed to handle five basic data types:
They are- character (char), integer (int), float (float), double precision floating point
(double) and void (void).
• In addition, C can handle various secondary data types such as array, pointer, structure,
union and enumeration.
8
Data Types, Decision Control and Looping
Statements
Data Types (Contd…)
Memory requirements for several data types are different as illustrated below:
Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes or (4bytes for -9223372036854775808 to 9223372036854775807
9
32 bit OS)
Data Types, Decision Control and Looping
Statements
Data Types (Contd…)
Along with that, C also supports user defined data types in which a user may define an identifier
that would represent an existing data type.
General form of user-defined data type is as follows:
typedef data-type identifier
For example,
typedef int day
Day Monday, Wednesday, Friday
typedef float subject
subject computer, English, network
10
Data Types, Decision Control and Looping
Statements
Keywords and Identifiers
In the context of C language, some specific meanings have been assigned for some words which
are known as keywords. Keywords are considered as reserved words. All keywords in ANSI C
are listed below:
auto break case char const continue default do
11
Data Types, Decision Control and Looping
Statements
Keywords and Identifiers (Contd….)
There are some restrictions on using the keywords:
Keywords have to be written in lowercase.
To avoid any kind of errors (runtime or compilation), keywords should not be used as variable
names.
Identifiers are the names given to the program elements such as variables, arrays and functions.
For example, variable is also an identifier. It follows the same rule as variables .
12
Data Types, Decision Control and Looping
Statements
Input/output statements in C
In C, input and output operations can be performed using standard input/output library functions. The
most commonly used functions for input and output are printf() and scanf().
The printf() function is used to print output to the console or terminal. It has a format string that
specifies the type and order of the values to be printed, and it can accept multiple arguments.
For example, the following statement prints the message "Hello, World!" to the console:
printf("Hello, World!\n");
The \n character is used to add a newline after the output.
The scanf() function is used to read input from the user. It can accept a format string that specifies the
type and order of the values to be read, and it can also accept multiple arguments.
For example, the following statement reads an integer from the user and stores it in the variable num:
13
int num; scanf("%d", &num);
Data Types, Decision Control and Looping
Statements
Input/output statements in C (Contd…)
The %d specifier is used to indicate that an integer value is expected, and the & symbol is used to get
the address of the variable num so that the input value can be stored there.
It is important to note that both printf() and scanf() functions are part of the standard I/O library
(stdio.h), and thus, you need to include this header file at the beginning of your code if you want to use
these functions.
#include <stdio.h> int main()
{ printf("Hello, World!\n");
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0; } 14
Data Types, Decision Control and Looping
Statements
Input/output statements in C (Contd…)
This is an example program that uses both printf() and scanf() functions to print a message to the
console and read an integer value from the user. The output of this program would look
something like this:
Hello, World! Enter an integer: 42
You entered: 42
15
Data Types, Decision Control and Looping
Statements
Constant and Variables
Constant: As the name suggests, constant is a fixed value entity. The value of constant data type
cannot be changed. Once it is stored in a memory location, the address has to be used to refer to
that constant value.
The const keyword is used to define constant in C programming.
const float PI=3.14;
Now, the value of PI variable cannot be changed.
#include<stdio.h>
int main()
{ const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0; } 16
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
Output:
The value of PI is: 3.140000
If you try to change the value of PI, it will render compile time error.
Variable: A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Let us see the syntax to declare a variable:
type variable_list;
17
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
The example of declaring the variable is given below:
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
int a=10,b=20;//declaring 2 variable of integer type
float f=20.8;
char c='A';
18
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
Types of Variables in C
[Link] variable
[Link] variable
[Link] variable
[Link] variable
19
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
1) 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 initialise the local variable before it is used.
20
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
2) 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
}
21
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
3) 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);
22
}
Data Types, Decision Control and Looping
Statements
Constant and Variables (Contd..)
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.
4)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
23
}
Data Types, Decision Control and Looping
Statements
Scope of variables
The scope of a variable in C determines the region of the program where the variable is visible
and can be accessed. In C, there are three types of variable scopes: global scope, function
scope, and block scope.
Global Scope: A variable declared outside of any function has a global scope. It can be accessed
from any part of the program, including all functions. Global variables are initialised to zero by
default.
24
Data Types, Decision Control and Looping
Statements
Scope of variables (Contd…)
Example:
#include <stdio.h>
int count = 0; // global variable
void increment()
{ count++; }
int main()
{ printf("Count is: %d\n", count); // Output: Count is: 0
increment(); printf("Count is: %d\n", count); // Output: Count is: 1
return 0;
}
25
Data Types, Decision Control and Looping
Statements
Scope of variables (Contd…)
Function Scope: A variable declared inside a function has a function scope. It can only be accessed
within the function where it is declared. The variable is initialised with garbage value by default.
Example:
#include <stdio.h>
void display()
{ int num = 10; // local variable
printf("Number is: %d\n", num);
}
int main()
{ display(); // Output: Number is: 10
26
return 0; }
Data Types, Decision Control and Looping
Statements
Scope of variables (Contd..)
Block Scope: A variable declared inside a block (i.e. inside a set of curly braces) has a block scope. It
can only be accessed within the block where it is declared. This includes variables declared inside
loops, if statements, switch statements, etc.
Example:
#include <stdio.h>
int main() In this example, the variable j is declared inside
{ int i; the for loop block and can only be accessed
for(i=1; i<=5; i++) inside the loop. Once the loop is exited, the
{ int j = i * 2; // block scope variable variable j goes out of scope and can no longer
printf("%d\n", j); be accessed.
27
} return 0; }
Data Types, Decision Control and Looping
Statements
Operators and Expressions (Contd…)
Operator is a symbol which operates on a value or a variable.
For example,
‘+’ is an operator which performs the addition operation. C language has a wide range of operators to
perform several operations. Various types of operators are available in C language.
Operators can be categorised based on the number of operands on which an operator functions.
The three categories are as follows:
Unary Operators: It operates on a single operand. For example, -5. Here – is the unary minus operator
and operates on 5 (single operand). Similarly, & (address of operator), sizeof, ! (logical negation), ~
(bitwise negation), ++ (increment), --(decrement) operator are the examples of unary operators.
Binary Operators: These operators operate on two operands. Multiplication (*), division (/), left shift
28
(<<), equality (==), logical AND (&&), bitwise AND (&) are the examples of binary operators.
Data Types, Decision Control and Looping
Statements
Operators and Expressions (Contd…)
Ternary Operators: It operates on three operands. Conditional operator is the example of
ternary operator.
For example, Y = (f<g) ?g :f;
It indicates, if (f<g) condition is true? Then value (g) expr2 : otherwise value f.
An expression may be a single data item or entity (operand), such as a number or a character, or
it may include more operands. Single entity expressions are simply a constant or a variable or an
array element or a reference to a function.
For example, 5 is a single entity expression. Such expressions do not specify any operations to
be performed. Multiple entity expressions may include a combination of various entities,
interconnected by one or more operators.
29
Data Types, Decision Control and Looping
Statements
Operators and Expressions (Contd…)
For example, a= b+c;
It is a meaningful expression which includes three operands (a, b, c) and two operators: (= and
+) assignment operator and arithmetic addition operator. So we can define expression as a
sequence of operands and operators that specify the computation of a value.
30
Data Types, Decision Control and Looping
Statements
Operators and Expressions (Contd…)
The figure lists the various types of operators based on their roles used in C programming with
descriptions.
31
Data Types, Decision Control and Looping
Statements
Type casting and Type conversion
The type casting and the type conversion are used in a program to convert one data type to another
data type. The conversion of data type is possible only by the compiler when they are compatible with
each other. Let us discuss the difference between type casting and type conversion in any
programming language.
Type casting
When a data type is converted into another data type by a programmer or user while writing a
program code of any programming language, the mechanism is known as type casting. The
programmer manually uses it to convert one data type into another. It is used if we want to change the
target data type to another data type. Remember that the destination data type must be smaller than the
source data type. Hence, it is also called narrowing conversion.
32
Data Types, Decision Control and Looping
Statements
Type casting and Type conversion (Contd…)
Syntax:
Destination_datatype = (target_datatype) variable;
(data_type) it is known as casting operator
33
Data Types, Decision Control and Looping
Statements
Type casting and Type conversion(Contd…)
Target_datatype: It is the data type in which we want to convert the destination data type. The
variable defines a value that is to be converted in the target_data type. Let us understand the
concept of type casting with an example.
Suppose, we want to convert the float data type into int data type. Here, the target data type is
smaller than the source data because the size of int is 2 bytes, and the size of the float data type
is 4 bytes. And when we change it, the value of the float variable is truncated and converted into
an integer variable. Casting can be done with a compatible and non-compatible data type.
float b = 3.0;
int a = (int) b; // converting a float value into integer
34
Data Types, Decision Control and Looping
Statements
Type casting and Type conversion (Contd…)
Type conversion
If a data type is automatically converted into another data type at compile time it is known as
type conversion. The conversion is performed by the compiler if both data types are compatible
with each other. Remember that the destination data type should not be smaller than the source
type. It is also known as widening conversion of the data type.
35
Data Types, Decision Control and Looping
Statements
Type casting and Type conversion (Contd…)
Let us understand the type conversion with an example.
Suppose, we have an int data type and want to convert it into a float data type. These are data
types compatible with each other because their types are numeric, and the size of int is 2 bytes
which is smaller than the float data type. Hence, the compiler automatically converts the data
types without losing or truncating the values.
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000 /
* It defines the conversion of int data type to float data type without losing the information. */
36
Data Types, Decision Control and Looping
Statements
Decision controls
A program is a sequence of statements which executes one after another. Generally, statement
computes assign values for variables or calls functions to perform a specific task. Eventually, you will
get a scenario where execution of statement needs to be controlled. Decision making will be essential
when a program will encounter a situation to choose a particular statement among many statements.
The if-else statement in C is used to perform the operations based on some specific condition. The
operations specified in if block are executed if and only if the given condition is true.
These are the following variants of if statement in C language:
• If statement
• If-else statement
• If else-if
37
• Nested if
Data Types, Decision Control and Looping
Statements
Decision controls (Contd…)
38
Data Types, Decision Control and Looping
Statements
If Statement
The if statement is used to check some given condition and perform some operations depending
upon the correctness of that condition. It is mostly used in the scenario where we need to
perform the different operations for different conditions.
The syntax of the if statement is given below:
if(expression)
{
//code to be executed
}
39
Data Types, Decision Control and Looping
Statements
If Statement Example
age = 18 #include <stdio.h>
return 0;
}
40
Data Types, Decision Control and Looping
Statements
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is
an extension to the if statement using which we can perform two different operations, that is, one is
for the correctness of that condition, and the other is for the incorrectness of the condition. Here,, we
must notice that if and else block cannot be executed simultaneously. Using if-else statement is
always preferable since it always invokes an otherwise case with every if condition.
The syntax of the if-else statement is given below:
if(expression)
{//code to be executed if condition is true }
else
{ //code to be executed if condition is false}
41
Data Types, Decision Control and Looping
Statements
If-else Statement Example
#include <stdio.h>
int main() {
int num = 0;
if (num > 0) {
printf("The number is positive.\n");
}
else {
printf("The number is zero or negative.\n");
}
return 0;
} 42
Data Types, Decision Control and Looping
Statements
If else-if
The if-else-if statement is an extension to the if-else statement. It is used in the scenario where there
are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition
is true then the statements defined in the if block will be executed, otherwise if some other condition is
true then the statements defined in the else-if block will be executed, at the last if none of the condition
is true then the statements defined in the else block will be executed. There are multiple else-if blocks
possible. It is similar to the switch case statement where the default is executed instead of else block if
none of the cases is matched.
if(condition1)
{ //code to be executed if condition1 is true
}else if(condition2)
{ //code to be executed if condition2 is true } …..
else{ //code to be executed if all the conditions are false } 43
Data Types, Decision Control and Looping
Statements
if-else-if Statement Example
#include <stdio.h> else {
printf("The number is negative.\n");
int main() { }
int num = 0;
return 0;
printf("Please enter a number: "); }
scanf("%d", &num);
if (num > 0) {
printf("The number is positive.\n");
}
else if (num == 0) {
printf("The number is zero.\n");
}
44
Data Types, Decision Control and Looping
Statements
Nested if
A nested if in C is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement.
That is, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true if (condition2)
{ // Executes when condition2 is true }
}
45
Data Types, Decision Control and Looping
Statements
Nested if Statement Example
#include <stdio.h> else {
printf("The number is negative.\n");
int main() { }
int num = 0;
return 0;
printf("Please enter a number: "); }
scanf("%d", &num);
if (num > 0) {
printf("The number is positive.\n");
}
else if (num == 0) {
printf("The number is zero.\n");
}
46
Data Types, Decision Control and Looping
Statements
Switch statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute
multiple operations for the different possible values of a single variable called switch variable. Here,
we can define various statements in the multiple cases for the different values of a single variable.
The syntax of switch statement is given below:
switch(expression)
{ case value1: //code to be executed;
break; //optional
case value2: //code to be executed;
break; //optional ......
default:
47
code to be executed if all cases are not matched;}
Data Types, Decision Control and Looping
Statements
#include <stdio.h>
case 2:
printf("You chose to subtract.\n");
int main() { break;
int choice; case 3:
printf("You chose to multiply.\n");
printf("Please choose an option:\n"); break;
printf("1. Add\n");
case 4:
printf("2. Subtract\n");
printf("You chose to divide.\n");
printf("3. Multiply\n");
break;
printf("4. Divide\n"); default:
scanf("%d", &choice); printf("Invalid choice.\n");
break;
switch(choice) { }
case 1:
printf("You chose to add.\n"); return 0;
break; } 48
Data Types, Decision Control and Looping
Statements
Loops
Loops cause a program to execute a certain block of code repeatedly until some conditions are
satisfied. In programming, repetitive work is performed by loops. If you want to execute a few
section of codes several times, you need to repeat the execution of that section that many times.
That is possible only using the concept of loop.
In C programming, there are three types of loops:
•for loop
•while loop
•do…while loop
49
Data Types, Decision Control and Looping
Statements
Loops (Contd…)
for loop
Let us start with the syntax of for loop:
for(initial expression; test expression; update expression)
{
Statement or code to be executed
}
For a for loop, the initial expression is initialised at the beginning. Then the program checks the
test expression. If the test expression is true, then the codes are executed and update expression
or else loop is terminated. The same process repeats until the test expression is false.
50
Data Types, Decision Control and Looping
Statements
Loops (Contd…)
Now, we see how for loop works for a simple program of interest calculation.
main ( )
{ int a, b, cal ; float p, q ;
for ( cal = 1 ; cal<= 3 ; cal = cal + 1 )
{ printf ( "\n\n Enter values for a, b, and p " ) ; scanf ( "%d %d %f", &a, &b, &p ) ;
q = a * b * p / 100 ; printf ( "Interest = Rs.%f\n", q ) ; }
}
In the above program, when the for statement is executed for the first time, the value of cal is set to
‘a’ initial value [Link] the next condition cal<=3 is tested. The condition is satisfied because the cal
value is 1. So, loop body will be executed for the first time. Finally, the cal value gets incremented by
51
1 and control go back to the start of the for loop for further execution. Now, the cal value is 2.
Data Types, Decision Control and Looping
Statements
Loops (Contd…)
Again cal value is checked whether it exceeds
3. If the value is within the range 1 to 3, then
it will execute the code inside the ‘for’ braces
and increment the cal value by [Link] cal
reaches 4, the control exits from the loop and
is transferred to the statement immediately
after the body of the for loop.
Like the nested if control, for loop also can be
nested.
52
Data Types, Decision Control and Looping
Statements
While loop
Loops generally consist of two parts: one or more control expressions which control the execution of
the loop and the body, which is the statement or a set of statements which is executed over and over.
General syntax for while loop is:
while (expression)
{ Statement or code to be executed }
The most basic loop in C is the while loop. A while loop has one control expression and executes as
long as that expression is true. Here, before executing the body of the loop, the condition is tested,
therefore it is called an entry-controlled loop. The following example repeatedly doubles the number
2 (2, 4, 8, 16, ...) and print the resulting numbers as long as they are less than 100:
int x = 2; while ( x<100)
53
{ printf(“ %d”, x); x= x * 2;}
Data Types, Decision Control and Looping
Statements
While loop (Contd…)
In a while loop, braces { } are used to enclose the group of statements which are to be executed
together as the body of the loop.
A while loop starts like the if statement: if the condition expressed by the expression is true, the
statement is executed. However, after executing the statement, the condition is tested again and
if it is still true, the statement is executed again. As long as the condition remains true, the body
of the loop is executed over and over again. If the condition is false right at the beginning, the
body of the loop is not executed at all.
54
Data Types, Decision Control and Looping
Statements
While loop (Contd…)
Now, you will see another program to find the largest of n numbers for better understanding of the while
loop.
main( )
{ intnum, large, n, i;
clrscr();
printf("enter number of numbers \n"); scanf(“%d”,&n);
large=0; i=0;
while(i<n)
{ printf("\n enter number "); scanf(“%d”, &num); if(large<num)
large=num; i++;}
printf("\n large = %d”, large);
} 55
Data Types, Decision Control and Looping
Statements
do…while loop
The above-mentioned two looping statements make a test of the conditions before the loop is
executed. If the condition is not satisfied, the body of the loop will never execute. But in some
cases, you may need to execute some instructions first, and then test the loop test at the end. In C
language, this is possible using the do statement.
Syntax for the do statement is:
do
program statement. while(loop _ expression);
As we can see, the above program statement will be executed first, and then the loop expression
within the parenthesis is evaluated. If the expression is true, the program continues to evaluate
the body of the loop once again. This process continues as long as the loop expression is true.
When the expression becomes false, the loop terminates and the control goes to the statement
that appears immediately after the while statement. 56
Data Types, Decision Control and Looping
Statements
Break, continue and goto statements
Sometimes when executing a loop, it becomes desirable to leave the loop as soon as a certain
condition occurs. That is possible using a break statement. Whether it is a for loop, a while loop or a
do loop, the use of break statement forces the program to exit immediately from the loop. The further
statement in the loop is skipped and terminates the execution of the loop. If a break is executed from
within a set of nested loops, only the innermost loop in which the break is executed is terminated.
The syntax for a break statement is as follows:
break;
Similarly, continue statement is similar to the break statement except it does not cause the loop to
terminate. Rather, as its name implies, this statement causes the loop in which it is executed to be
continued.
The syntax for a continue statement is as follows:
continue; 57
Data Types, Decision Control and Looping
Statements
Break, continue and goto statements (Contd…)
The following examples show the difference in using the break and continue statement:
void main ( )
{ int x;
for (x=1; x<=10; x++)
{ if (x==5)
break; /*break loop only if x==5 */
printf(“%d”, x);}
printf (“\nBroke out of loop”);
printf( “at x =%d“);
58
Data Types, Decision Control and Looping
Statements
Break, continue and goto statements (Contd…)
The following examples show the difference in using the break and continue statement:
void main ( )
{ int x;
for (x=1; x<=10; x++)
{if (x==5)
continue; /* skip remaining code in loop
only if x == 5 */
printf (“%d\n”, x);}
printf(“\nUsed continue to skip”);
}
59
Data Types, Decision Control and Looping
Statements
Break, continue and goto statements (Contd…)
A goto statement in C programming provides an unconditional jump from the 'goto' to a labelled
statement in the same function.
NOTE − Use of goto statement is highly discouraged in any programming language because it
makes difficult to trace the control flow of a program, making the program hard to understand and
hard to modify. Any program that uses a goto can be rewritten to avoid them.
The syntax for a goto statement is as follows:
goto label;
...
label: statement;
Here, label can be any plain text, except C keyword, and it can be set anywhere in the C program
60
above or below to goto statement.
Data Types, Decision Control and Looping
Statements
Break, continue and goto statements (Contd…)
61
Data Types, Decision Control and Looping
Statements
Type modifiers and storage class specifiers for data types
Type modifiers are used to modify the size or range of a data type. There are four type modifiers in C:
•short
• long
• signed
• unsigned
short and long are used to modify the size of integer data types. short specifies a 16-bit integer,
while long specifies a 32-bit integer. For example, short int and long int are two data types that can
be used to store smaller or larger integers, respectively.
62
Data Types, Decision Control and Looping
Statements
Type modifiers and storage class specifiers for data types (Contd…)
‘signed’ and ‘unsigned’ modifiers can also be used with integer data types.
For example,
63
Data Types, Decision Control and Looping
Statements
Type modifiers and storage class specifiers for data types (Contd…)
Storage class specifiers
Storage class specifiers are used to specify the scope and lifetime of variables.
•auto
•static
•extern
•register
64
Data Types, Decision Control and Looping
Statements
Type modifiers and storage class specifiers for data types (Contd…)
• auto is the default storage class specifier for local variables.
For example,
void foo( )
printf("%d\n", a); }
Here, a is an auto variable, which means that its value is stored on the stack and it is only visible
within the scope of the function.
65
Data Types, Decision Control and Looping
Statements
Type modifiers and storage class specifiers for data types (Contd…)
• static can be used to specify that a variable should retain its value between function calls.
For example,
void increment( )
{ static int count = 0;
count++; printf("%d\n", count);}
Here, count is a static variable that retains its value between calls to the increment function.
• extern can be used to specify that a variable is defined in another file.
For example,
extern int value;
void print_value( )
66
{ printf("%d\n", value); }
Data Types, Decision Control and Looping
Statements
Type modifiers and storage class specifiers for data types(Contd…)
Here, extern int value tells the compiler that the variable value is defined in another file.
•register can be used to specify that a variable should be stored in a CPU register.
For example,
void foo( )
{
register int a = 10;
printf("%d\n", a);
}
Here, register int a tells the compiler that the variable a should be stored in a register:
67
Data Types, Decision Control and Looping
Statements
Summary
• It begins with data types in the C programming language input/output statements and moves
on to cover the basics of variables, constants and their scope.
• The curriculum delves into operators and expressions, covering concepts such as type
conversion and type casting. It then progresses to decision control statements, including if-
then-else and nested if-else statements, as well as looping statements like while, do-while
and for loops.
• Covers the switch statement, as well as the use of break, continue and goto statements.
• Discusses type modifiers and storage class specifiers for data types, providing students with
a thorough understanding of how to use them effectively.
• Overall, it provides the foundation for mastering the fundamentals of C programming,
68
including how to write efficient, effective and well-structured code
Data Types, Decision Control and Looping
Statements
Self Assessment Question
1. Which of the following is a valid data type in C programming language?
a. Boolean
b. char
c. string
Answer: b
69
Data Types, Decision Control and Looping
Statements
Self Assessment Question
2. What is the difference between a constant and a variable in C?
Answer: a
70
Data Types, Decision Control and Looping
Statements
Self Assessment Question
3. What is the purpose of type conversion in C programming?
Answer: a
71
Data Types, Decision Control and Looping
Statements
Self Assessment Question
4. What is the purpose of the if statement in C programming?
Answer: a
72
Data Types, Decision Control and Looping
Statements
Self Assessment Question
5. Which of the following is a looping statement in C programming?
a. if
b. switch
c. do-while
d. break
Answer: c
73
Data Types, Decision Control and Looping
Statements
Self Assessment Question
6. What is the purpose of the switch statement in C programming?
Answer: a
74
Data Types, Decision Control and Looping
Statements
Self Assessment Question
7. What is the purpose of the break statement in C programming?
Answer: a
75
Data Types, Decision Control and Looping
Statements
Self Assessment Question
8. Which of the following is a type modifier in C programming?
a. unsigned
b. void
c. float
Answer: a
76
Data Types, Decision Control and Looping
Statements
Self Assessment Question
9. What is the output of the following code?
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
} a. 012346789
printf("%d ", i); b. 0123456789
} c. 12346789
Answer: a
77
Data Types, Decision Control and Looping
Statements
Self Assessment Question
10. Which of the following is true about the switch statement in C?
Answer: a
78
Data Types, Decision Control and Looping
Statements
Assignment
• Write a C program that prompts the user to enter a number and then display the square of that
number.
• Define a constant in C programming language and display its value on the screen.
• Write a program that prompts the user to enter two numbers, and then display the sum,
difference, product and quotient of those numbers.
• What is the scope of a variable in C? Explain with an example.
• Write a C program to determine whether a given number is even or odd using decision
control statements.
• Write a program that calculates the average of a set of numbers entered by the user using a
loop statement.
79
Data Types, Decision Control and Looping
Statements
Assignment
• What is the purpose of the switch statement in C programming? Provide an example.
• Explain the difference between the break and continue statements in C programming, and
give an example of each.
• Define the storage class specifier ‘static’ in C programming, and give an example of its use.
80
Data Types, Decision Control and Looping
Statements
Document Link
81
Data Types, Decision Control and Looping
Statements
Video Link
82
Data Types, Decision Control and Looping
Statements
E- Book Link
83