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

Unit II

The document covers fundamental concepts of computer science, focusing on statements, blocks, conditional statements (if-else-if, switch), and loops (while, do-while, for). It explains the structure and usage of these programming constructs in C#, including declaration and expression statements, as well as control flow mechanisms like break and continue. Additionally, it contrasts structured programming with unstructured programming, emphasizing the importance of modular code and control flow in structured programming.

Uploaded by

thejegan31
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Unit II

The document covers fundamental concepts of computer science, focusing on statements, blocks, conditional statements (if-else-if, switch), and loops (while, do-while, for). It explains the structure and usage of these programming constructs in C#, including declaration and expression statements, as well as control flow mechanisms like break and continue. Additionally, it contrasts structured programming with unstructured programming, emphasizing the importance of modular code and control flow in structured programming.

Uploaded by

thejegan31
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

FUNDAMENTALS OF COMPUTER SCIENCE (U23CBT101)

Unit- II

2.1 Statements and Blocks


Statements
A statement is a basic unit of execution of a program. A program consists of multiple
statements.
For example:
int age = 21;
int marks = 90;
In the above example, both lines above are statements.
There are different types of statements in C#. In this tutorial, we’ll mainly focus on two of
them:

• Declaration Statement
• Expression Statement
Declaration Statement
Declaration statements are used to declare and initialize variables.
For example:
char ch;
int maxValue = 55;
Both char ch; and int maxValue = 55; are declaration statements.
Expression Statement
An expression followed by a semicolon is called an expression statement.
For example:
/* Assignment */

1|SMVEC / CSBS
area = 3.14 * radius * radius;
/* Method call is an expression*/
Printf("Hello");
Here, 3.14 * radius * radius is an expression and area = 3.14 * radius * radius; is an
expression statement.
Likewise, Printf("Hello"); is both an expression and a statement.
Beside declaration and expression statement, there are:
• Selection Statements (if...else, switch)
• Iteration Statements (do, while, for)
• Jump Statements (break, continue, goto)
Blocks
These statements are grouped into blocks, a block is identified by curly brackets...There are
two types of block.
Statement blocks
if ( i == j)
{
printf("martin \n");
}
The statement block containing the printf is only executed if the i == j expression evaluates to
TRUE.
Function blocks
int add( int a, int b) /* Function definition */
{
int c;
c = a + b;
return c;
}
The statements in this block will only be executed if the add function is called
2.2 If-Else-if
The if-else-if statement is a conditional statement in C programming that allows you to
execute different blocks of code based on the evaluation of multiple conditions. It is similar to
the nested if-else statement, but it is more concise and easier to read.

2|SMVEC / CSBS
Here is the syntax of the if-else-if statement:
if (condition1) {
// block of code to execute if condition1 is true
} else if (condition2) {
// block of code to execute if condition1 is false and condition2 is
true
} else if (condition3) {
// block of code to execute if condition1 is false and condition2 is
false and condition3 is true
} else {
// block of code to execute if all conditions are false
}

The if-else-if statement works by evaluating the conditions from top to bottom. If the first
condition is true, then the block of code associated with that condition is executed. If the first
condition is false, then the second condition is evaluated. If the second condition is true, then
the block of code associated with that condition is executed. If the second condition is false,
then the third condition is evaluated, and so on. If none of the conditions are true, then the block
of code associated with the else statement is executed.
Here is an example of how to use the if-else-if statement to determine the grade for a student
based on their score:
int score = 95;

if (score >= 90) {


printf("A");
} else if (score >= 80) {
printf("B");
} else if (score >= 70) {
printf("C");
} else if (score >= 60) {
printf("D");
} else {
printf("F");
}

This code will print the letter grade A because the score is 95, which is greater than or equal
to 90.

2.3 Switch
C has a built-in multi way decision statement known as a switch. The switch statement tests
the value of a given variable (or expression) against a list of case values and when a match is
found, a block of statements associated, with that case is executed. The general form of the
switch statement is as shown below:

3|SMVEC / CSBS
The expression is an integer expression or characters. Value-1, value-2… are constants or
constant expressions and are known as case labels. Each of these values should be unique
within a switch statement. block-1, block-2…are statement list and may contains zero or
more statements. There is no need to put braces around these blocks. Note that case labels
end with a colon (:).
When the switch is executed, the value of the expression is successfully compared against the
values value-1, value-2,… if a case is found whose value matches with the value of the
expression, then the block of statements that follows the case are executed
The break statement at the end of each block signal the end of a particular case and causes an
exit from the switch statement, transferring the control to the statement-x following the
switch.
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values. If not present, no action takes place if
all matches fail and the control goes to the statement-x.

4|SMVEC / CSBS
2.4 Loop – while, do while, for
“When sequences of statements are executed repeatedly up to some condition then it is
known as Program Loop.”
A loop consists mainly two parts:
Body of loop :
This part contains the sequences of statements, which are to be executed repeatedly.
Control statement:
This part contains certain conditions, which indicates how many times we have to execute the
body of loop. The control statement should be writing carefully otherwise it may possible
your loop is executed infinite times which is known as Infinite Loop. Loop contains one or
more variable, which control the execution of loop that is known as the Loop Counter.
Loop is executed basically in following steps:
1. Setting and initialization of Loop Counter.
2. Test the condition.
3. Executing the body of loop.

5|SMVEC / CSBS
4. Incrementing or decrementing the Loop Counter value.
In above steps, 2nd and 3rd steps may be executed interchangeably that means either we can
perform step 2 first or step 3 first.
In general there are two types of loops: Entry Controlled loop and Exit controlled loop.
Entry-controlled loop
In entry-controlled loop we first check the condition and then the body of loop is executed. If
at first time condition is false then the body of loop and not executed any time. In C
programming language while loop and for loop is example of entry-controlled loop.

Exit-controlled loop
In exit-controlled loop we first execute the body of the loop and then check the condition and if
condition is true then next again executed the body of the loop otherwise not. In exitcontrolled loop it
is sure the body of loop is executed once. In C programming language dowhile loop is example of the
exit-controlled loop.

6|SMVEC / CSBS
While Loop
While loop is entry-controlled loop, in which first condition is evaluated and if condition is
true the body of loop is executed. After executing the body of loop the test condition is again
evaluated and if it is true then again body of loop is executed. This process is going to
continue up to your test condition is true. If the test condition is false on initial stage then
body of loop is never executed. The format of while loop is:

7|SMVEC / CSBS
Body of loop has one or more statements. Here the curly bracket is not necessary if body of
loop contains only one statement. Consider following example to print10 numbers start from1.

Here above program print the number from 1-10. First loop counter ‘i’ is 1. Out test condition
is ‘i <=10’ that means the value of ‘i’ is less than or equal to 10. If test condition is true then
we are getting the value of ‘i’. After printing the ‘i’ value the value of ‘i’ is incremented by 1
and again check the test condition. This process is continuing till test condition is true.

do…while loop
As we known that ‘while’ loop is entry-controlled loop in which test condition is
evaluated first and if test condition is true then body of loop is executed. If test condition is
false on first time then body of loop is never executed. But sometimes we have such a condition
in which it is mandatory to execute the body of loop once whether test condition is true or false.
At that time we have to use do-while loop. do-while loop is exit-controlled loop, in which first
condition body of loop is executed first and then the test condition is evaluated and if the test

8|SMVEC / CSBS
condition is true then again body of loop is executed. This process is repeated continuously till
test condition is true. Here the body of loop must be executed at least once.
The format of do-while loop is:

Consider one example of do-while loop in which we have to read the data till the number is
less than 100 and if number is greater than 100 then we have to terminate the loop.

Here first body of loop is executed mean we are reading number and then test condition is
evaluated (number is less than or equal to 100) if it is true then again we reading another
number otherwise the loop is terminated.

for loop
for loop is entry-controlled loop, in which first condition is evaluated and if condition is true
the body of loop is executed. After executing the body of loop the test condition is again
evaluated and if it is true then again body of loop is executed. This process is going to
continue up to your test condition is true. If the test condition is false on initial stage then
body of loop is never executed. The format of for loop is:

9|SMVEC / CSBS
In above format the first line contain initialization, test-condition, and increment-decrement
portion that means in ‘for’ loop initialization, condition and increment/decrement is done in
only one line. First the loop counter is initialized. After initialization the test condition is
evaluated and if it true then body of loop is executed and after execution of body of loop
increment or decrement of loop counter is done. Again the test condition is evaluated and it is
true then the same process is done again. This is continuing till the test condition is true. The
flow chart of the for loop can be drawn in Fig. 5
Consider the example of for loop in which we are determining the factorial of given number.

Here the loop counter ‘i’ is initialized by 1 at first time. Then test condition (The value of ‘i’
is less than or equal to ‘n’) is evaluated and if it is true then ‘fact’ is multiplied with ‘i’ and
again assign to ‘fact’. After executing the body of loop the value of ‘i’ is incremented by 1.
Next again test condition is evaluated and if it is true then we are proceeding in same way.

10 | S M V E C / C S B S
How for loop differs from other while loop:
• We have all initialization, condition and increment/decrement statement are only in one
line.
• We can use multiple initialization or multiple increment/decrement statements by using the
comma operator. For example,

• We can omit any section of all section. (That means we can omit initialization, condition, or
increment/decrement section) For example,

11 | S M V E C / C S B S
Here the second loop has omitted all the sections means this loop is infinite loop since there
is no any condition to check so it is always true and body of loop is executed continuously.

DELAY (NULL)
LOOP When we put the semicolon after for loop or while loop statement then body of loop
is never executed that mean we are using useless loop. This loop is used to generate the delay
and so it is known as delay loop or null loop.
for( i =1 ; i<=10000 ; i++) ;
Here we have put semicolon after the loop means this loop is executed but without body of
loop.
NESTED for LOOP
When we put loop inside the loop it is known as the nested loop. The nesting is allowed up to
15 levels in ANSI C but many compilers allow more. Consider the example of nested loop. In
which the we are using two loops one is outer loop and another is inner loop which is used to
read marks and calculate the total of 4 students

Here the outer loop is having the loop counter ‘i’ and inner loop has loop counter ‘j’. First
outer loop is counter ‘i’ is initialized by 1 and if test condition (i< = 4) is true then next inner
loop is executed in which the loop counter ‘j’ is initialized by 1 and if test condition (j <=6 )
is true then the marks of students are read and total is calculated, then the loop counter ‘j’ is
incremented. This is continuing till the condition for the inner loop is true. When condition
for inner loop is false the loop counter ‘i’ for outer loop is incremented and again same
process is done
2.5 break and continue
break statement
break statement is used to terminate the loop. When computer execute break statement the
control automatically goes to next immediate statement after loop. We cannot transfer the
control at any other place. When you put break in nested loop then the only one loop in which
break statement is encounter is terminated.

12 | S M V E C / C S B S
If the ‘condition1’ is true then computer encounter break statement and terminate the loop.

Here when computer encounter your desired number then computer print the position of
number and terminate the loop and go to next immediate statement getch( ).
continue statement
During loop operations, it may be necessary to skip the part of the body of the loop during
certain condition. We are using continue statement to skip the portion of loop. For example we
are determining the square root of any number and print it. But our condition is that if number
is negative then we don’t want to determine square root. At that time we can use continue
statement to skip the body of loop for negative number.

13 | S M V E C / C S B S
Let’s see the example of skipping negative number printing using ‘continue’. Here we are
reading the number until number is not greater than 1000. If the number is negative then we
have to not print it otherwise print it

2.6 goto labels


The C goto statement is a jump statement which is sometimes also referred to as an
unconditional jump statement. The goto statement can be used to jump from anywhere to
anywhere within a function.
Syntax:

In the above syntax, the first line tells the compiler to go to or jump to the statement marked as
a label. Here, the label is a user-defined identifier that indicates the target statement. The

14 | S M V E C / C S B S
statement immediately followed after ‘label:’ is the destination statement. The ‘label:’ can also
appear before the ‘goto label;’ statement in the above syntax.

Example:
#include<stdio.h>
void main()
{
int age;
g: //label name
printf("you are Eligible\n");
s: //label name
printf("you are not Eligible");
printf("Enter you age:");
scanf("%d", &age);
if(age>=18)
goto g; //goto label g
else
goto s; //goto label s
}
2.7 Structured and un-structured programming
Structured programming
Structured programming is a programming paradigm that emphasizes dividing code into small,
reusable modules called functions. These functions have well-defined inputs and outputs, and

15 | S M V E C / C S B S
they perform specific tasks. Structured programming also emphasizes using control flow
constructs such as if-else statements and loops to control the flow of execution.
In C programming, structured programming can be implemented using various control flow
constructs, including:

• if-else statements: These statements allow for conditional execution of code blocks
based on the evaluation of Boolean expressions.
• switch-case statements: These statements provide a more compact way of handling
multiple conditional branches.
• loops: Loops allow for repeated execution of code blocks until a specific condition is
met. Common loop types include for loops, while loops, and do-while loops.
Here's an example of structured programming in C:
int grade = 95;

if (grade >= 90) {


printf("Grade: A\n");
} else if (grade >= 80) {
printf("Grade: B\n");
} else if (grade >= 70) {
printf("Grade: C\n");
} else if (grade >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}

Un-Structured programming
Unstructured programming, on the other hand, is a programming paradigm that does not follow
these principles. Unstructured programs are typically written as one large block of code, and
they may use unstructured control flow constructs such as the goto statement.
Here is a table that summarizes the key differences between structured and unstructured
programming:

16 | S M V E C / C S B S
unstructured programming in C might involve direct jumps within the code using the 'goto'
statement. While this allows for unrestricted control flow, it can make the code difficult to
follow and maintain.
Example:
int score = 50;

if (score >= 90) {


printf("Grade: A\n");
} else {
goto fail;
}

if (score >= 80) {


printf("Grade: B\n");
} else {
goto fail;
}

if (score >= 70) {


printf("Grade: C\n");
} else {
goto fail;
}

if (score >= 60) {


printf("Grade: D\n");
} else {
fail:
printf("Grade: F\n");
}

2.8 Basics of functions


A function in C is a set of statements that when called perform some specific task. It is
the basic building block of a C program that provides modularity and code reusability. The
programming statements of a function are enclosed within { } braces, having certain meanings
and performing certain operations. They are also called subroutines or procedures in other
languages.
Syntax of Functions in C
The syntax of function can be divided into 3 aspects:
• Function Declaration
• Function Definition
• Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and the number
and type of its parameters. A function declaration tells the compiler that there is a function with
the given name defined somewhere else in the program.
Syntax

17 | S M V E C / C S B S
return_type name_of_the_function (parameter_1, parameter_2);
The parameter name is not mandatory while declaring functions. We can also declare the
function without using the name of the data variables.
Example
int sum(int a, int b);
int sum(int , int);

Function Definition
The function definition consists of actual statements which are executed when the function is
called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function definition
always starts with the function declaration so we do not need to declare it explicitly. The below
example serves as both a function definition and a declaration.
return_type function_name (para1_type para1_name, para2_type para2_name)
{
// body of the function
}

18 | S M V E C / C S B S
Function Call
A function call is a statement that instructs the compiler to execute the function. We use the
function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum function.
After the function call sum of a and b is returned and control is also returned back to the main
function of the program.

Example:
// C program to show function
// call and definition
#include <stdio.h>

// Function that takes two parameters


// a and b as inputs and returns
// their sum
int sum(int a, int b)
{
return a + b;
}

// Driver code
int main()
{
// Calling sum function and
// storing its value in add variable
int add = sum(10, 30);

printf("Sum is: %d", add);


return 0;
}

19 | S M V E C / C S B S
Output:
Sum is: 40

2.9 Parameter passing and returning type


In C programming language, functions can be called either with or without arguments and
might return values. They may or might not return values to the calling functions.

• Function with no arguments and no return value


• Function with no arguments and with return value
• Function with argument and with no return value
• Function with arguments and with return value
Passing Parameters to Functions
The data passed when the function is being invoked is known as the Actual parameters. In the
below program, 10 and 30 are known as actual parameters. Formal Parameters are the variable
and the data type as mentioned in the function declaration. In the below program, a and b are
known as formal parameters.
Call by Value
Call by value in C is where in the arguments we pass value and that value can be used in
function for performing the operation. Values passed in the function are stored in temporary
memory so the changes performed in the function don’t affect the actual value of the variable
passed.
Example:
#include <stdio.h>

// Call by value
int sum(int x, int y)
{
int c;
c = x + y;

// Integer value retured


return c;
}

// Driver Code
int main()
{
// Integer Declared
int a = 3, b = 2;

// Function Called
int c = sum(a, b);
printf("Sum of %d and %d : %d", a, b, c);

20 | S M V E C / C S B S
return 0;
}

Call by Reference
Call by reference is the method in C where we call the function with the passing address as
arguments. We pass the address of the memory blocks which can be further stored in a pointer
variable that can be used in the function. Now, changes performed in the values inside the
function can be directly reflected in the main memory.
Example:
#include <stdio.h>

// Call by reference
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}

// Driver Code
int main()
{
// Declaring Integer
int x = 1, y = 5;
printf("Before Swapping: x:%d , y:%d\n", x, y);

// Calling the function


swap(&x, &y);
printf("After Swapping: x:%d , y:%d\n", x, y);

return 0;
}

1. Function with arguments and return value

21 | S M V E C / C S B S
Syntax:
Function declaration: int function ( int );
Function call: function( x );
Function definition:
int function( int x )
{
statements;
return x;
}
Example:
#include <stdio.h>
#include <string.h>

int function(int, int[]);

int main()
{
int i, a = 20;
int arr[5] = { 10, 20, 30, 40, 50 };

a = function(a, &arr[0]);

printf("value of a is %d\n", a);


for (i = 0; i < 5; i++) {
printf("value of arr[%d] is %d\n", i, arr[i]);
}

return 0;
}

int function(int a, int* arr)


{
int i;
a = a + 20;

arr[0] = arr[0] + 50;


arr[1] = arr[1] + 50;
arr[2] = arr[2] + 50;
arr[3] = arr[3] + 50;
arr[4] = arr[4] + 50;

return a;

22 | S M V E C / C S B S
}

2. Function with arguments but no return value


When a function has arguments, it receives any data from the calling function but it returns no
values. These are void functions with no return values.
Syntax:
Function declaration : void function ( int );
Function call : function( x );
Function definition:
void function( int x )
{
statements;
}
Example:
#include <stdio.h>

void function(int, int[], char[]);

int main()
{
int a = 20;
int ar[5] = { 10, 20, 30, 40, 50 };

char str[30] = "geeksforgeeks";

// function call
function(a, &ar[0], &str[0]);

return 0;
}

23 | S M V E C / C S B S
void function(int a, int* ar, char* str)
{
int i;
printf("value of a is %d\n\n", a);

for (i = 0; i < 5; i++) {


printf("value of ar[%d] is %d\n", i, ar[i]);
}

printf("\nvalue of str is %s\n", str);


}

3. Function with no argument and no return value


When a function has no arguments, it does not receive any data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data from
the called function.
Syntax:
Function declaration : void function();
Function call : function();
Function definition :
void function()
{
statements;
}

24 | S M V E C / C S B S
Example:
#include <stdio.h>

void value(void);

void main() {
value();
}

void value(void)
{
float year = 1, period = 5, amount = 5000,
inrate = 0.12;
float sum;
sum = amount;
while (year <= period) {
sum = sum * (1 + inrate);
year = year + 1;
}
printf(" The total amount is :%f", sum);
}

4. Function with no arguments but returns a value


There could be occasions where we may need to design functions that may not take any
arguments but returns a value to the calling function. An example of this is getchar function
which has no parameters but it returns an integer and integer-type data that represents a
character.
Syntax:
Function declaration : int function();
Function call : function();
Function definition :
int function()
{
statements;
return x;
}

25 | S M V E C / C S B S
Example:
#include <math.h>
#include <stdio.h>

int sum();

int main()
{
int num;
num = sum();
printf("Sum of two given values = %d", num);
return 0;
}

int sum()
{
int a = 50, b = 80, sum;
sum = sqrt(a) + sqrt(b);
return sum;
}

2.10 C main return as integer


In C programming, the main() function is the entry point of the program, and it is
required to have a return type of int. This means that the main() function must return an integer
value to the operating system when it finishes executing. The value returned by main() is
typically used to indicate the success or failure of the program.
A return value of 0 from main() indicates that the program executed successfully. Any other
non-zero return value indicates that the program encountered an error or did not execute as
expected. The specific meaning of non-zero return values is typically defined by the
programmer.
Here is an example of how to return an integer value from the main() function:
int main() {
// Do some processing
// Return 0 to indicate success
return 0;
}

26 | S M V E C / C S B S
2.11 External, Auto, Local, Static, Register variables
What is Storage Class in C?
A storage class represents the visibility and a location of a variable. It tells from what part of
code we can access a variable. A storage class in C is used to describe the following things:

• The variable scope.


• The location where the variable will be stored.
• The initialized value of a variable.
• A lifetime of a variable.
• Who can access a variable?
Thus a storage class is used to represent the information about a variable.
Types of Storage Classes
There are total four types of standard storage classes. The table below represents the storage
classes in C.

Auto Storage Class in C


The variables defined using auto storage class are called as local variables. Auto stands
for automatic storage class. A variable is in auto storage class by default if it is not explicitly
specified.
The scope of an auto variable is limited with the particular block only. Once the control
goes out of the block, the access is destroyed. This means only the block in which the auto
variable is declared can access it.
A keyword auto is used to define an auto storage class. By default, an auto variable contains a
garbage value.
Example,
auto int age;
The program below defines a function with has two local variables
int add(void) {
int a=13;

27 | S M V E C / C S B S
auto int b=48;
return a+b;
}
We take another program which shows the scope level “visibility level” for auto variables in
each block code which are independently to each other:
#include <stdio.h>
int main( )
{
auto int j = 1;
{
auto int j= 2;
{
auto int j = 3;
printf ( " %d ", j);
}
printf ( "\t %d ",j);
}
printf( "%d\n", j);}
OUTPUT:
321
Extern Storage Class in C

The extern storage class in C programming is used to declare variables or


functions that have been defined elsewhere in the program. It does not allocate
memory for the variable; instead, it simply tells the compiler that the variable exists
and can be accessed from the current file.
Purpose of the extern Storage Class
The extern storage class is used for two main purposes:
1. Sharing global variables between files: When you have multiple files in a C
program, you can use the extern storage class to share global variables
between those files. This allows different parts of the program to access and
modify the same data.
2. Declaring functions that are defined in other files: If a function is defined in
another file, you can use the extern storage class to declare it in the current

28 | S M V E C / C S B S
file. This allows the compiler to know that the function exists and can be called
from the current file.

Syntax of the extern Storage Class


The syntax for declaring a variable or function with the extern storage class is
as follows:
extern <data_type> <variable_name>;
or
extern void <function_name>(<parameter_list>);

In the first example, <data_type> is the data type of the variable, and
<variable_name> is the name of the variable. In the second example,
<function_name> is the name of the function, and <parameter_list> is a list of the
function's parameters.

Example of Using the extern Storage Class


Here is an example of how to use the extern storage class to share a global
variable between two files:
File 1: global.c

extern int global_variable;

int global_variable = 10;


File 2: main.c

#include <stdio.h>

extern int global_variable;

int main() {
printf("The value of global_variable is: %d\n", global_variable);

global_variable = 20;

printf("The value of global_variable is now: %d\n", global_variable);

return 0;
}
When you compile and run these two files, the output will be:
The value of global_variable is: 10
The value of global_variable is now: 20
As you can see, the value of the global_variable can be accessed and modified
from both files. This is because the extern storage class allows the variable to be
shared between the two files.

29 | S M V E C / C S B S
.Static Storage Class in C
The static variables are used within function/ file as local static variables. They can also
be used as a global variable
Static local variable is a local variable that retains and stores its value between function calls
or block and remains visible only to the function or block in which it is defined.
Static global variables are global variables visible only to the file in which it is declared.
Example: static int count = 10;
Keep in mind that static variable has a default initial value zero and is initialized only once in
its lifetime.
#include <stdio.h> /* function declaration */
void next(void);
static int counter = 7; /* global variable */
main() {
while(counter<10) {
next();
counter++; }
return 0;}
void next( void ) { /* function definition */
static int iteration = 13; /* local static variable */
iteration ++;
printf("iteration=%d and counter= %d\n", iteration, counter);}
Result:
iteration=14 and counter= 7
iteration=15 and counter= 8
iteration=16 and counter= 9
Global variables are accessible throughout the file whereas static variables are
accessible only to the particular part of a code.
The lifespan of a static variable is in the entire program code. A variable which is declared or
initialized using static keyword always contains zero as a default value.
Register Storage Class in C
You can use the register storage class when you want to store local variables within functions
or blocks in CPU registers instead of RAM to have quick access to these variables. For
example, “counters” are a good candidate to be stored in the register.

30 | S M V E C / C S B S
Example: register int age;
The keyword register is used to declare a register storage class. The variables declared using
register storage class has lifespan throughout the program.
It is similar to the auto storage class. The variable is limited to the particular block. The only
difference is that the variables declared using register storage class are stored inside CPU
registers instead of a memory. Register has faster access than that of the main memory.
The variables declared using register storage class has no default value. These variables are
often declared at the beginning of a program.
#include <stdio.h>
main()
{
register int weight;
int *ptr=&weight ;/*it produces an error when the compilation occurs ,we cannot get a memory
location when dealing with CPU register*/}
}
OUTPUT:
error: address of register variable 'weight' requested
2.12 Scope Rules
The scope of a variable in C is the block or the region in the program where a variable is
declared, defined, and used. Outside this region, we cannot access the variable and it is treated
as an undeclared identifier.
• The scope is the area under which a variable is visible.
• The scope of an identifier is the part of the program where the identifier may directly
be accessible.
• We can only refer to a variable in its scope.
• In C, all identifiers are lexically(or statically) scoped.
Types of Scope Rules in C
C scope rules can be covered under the following two categories:
1. Global Scope
2. Local Scope
1. Global Scope in C
The global scope refers to the region outside any block or function.

31 | S M V E C / C S B S
• The variables declared in the global scope are called global variables.
• Global variables are visible in every part of the program.
• Global is also called File Scope as the scope of an identifier starts at the beginning of
the file and ends at the end of the file.
Example:
#include <stdio.h>
// variable declared in global scope
int global = 5;
// global variable accessed from
// within a function
void display()
{
printf("%d\n", global);
}
// main function
int main()
{
printf("Before change within main: ");
display();
// changing value of global
// variable from main function
printf("After change within main: ");
global = 10;
display();
}
Output:

2. Local Scope in C
The local scope refers to the region inside a block or a function. It is the space enclosed
between the { } braces.

32 | S M V E C / C S B S
• The variables declared within the local scope are called local variables.
• Local variables are visible in the block they are declared in and other blocks nested
inside that block.
• Local scope is also called Block scope.
• Local variables have internal linkage.
Example
#include <stdio.h>
// Driver Code
int main()
{
{
int x = 10, y = 20;
{
// The outer block contains
// declaration of x and
// y, so following statement
// is valid and prints
// 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again,
// so outer block y is
// not accessible in this block
int y = 40;
// Changes the outer block
// variable x to 11
x++;
// Changes this block's
// variable y to 41
y++;
printf("x = %d, y = %d\n", x, y);

33 | S M V E C / C S B S
}
// This statement accesses
// only outer block's
// variables
printf("x = %d, y = %d\n", x, y);
}
}
return 0;
}
Output
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20

2.13 Block Structure


In C programming, a block is a sequence of declarations, definitions, and statements
enclosed within curly braces ({ }).
Blocks serve several important purposes in C programming:
• Grouping statements together: Blocks allow you to group together statements that are
related to each other. This makes your code more readable and easier to understand.
• Defining scope: Blocks define the scope of variables and functions. The scope of a
variable or function is the region of the program where it can be accessed.
• Controlling program flow: Blocks can be used to control the flow of program
execution using control flow statements like if-else, while, and for loops.
• Defining functions: Function definitions are blocks that contain the code for a
particular function.
Types of Blocks in C Programming
There are two main types of blocks in C programming:
Compound statements: A compound statement is a block that contains one or more
statements. Compound statements are often used in control flow statements like if-else, while,
and for loops.
Function definitions: A function definition is a block that contains the code for a particular
function. Function definitions always contain a compound statement, which is the body of the
function.

34 | S M V E C / C S B S
Nesting Blocks
Blocks can be nested inside other blocks. This means that a block can contain other blocks.
Nesting blocks is a powerful way to organize your code and control the scope of variables and
functions.
Example of Block Structure
Here is an example of a C program that illustrates the use of blocks:
#include <stdio.h>
int main()
{
int x = 10;
int y = 20;
if (x > y)
{
printf("x is greater than y\n");
}
else
{
printf("y is greater than or equal to x\n");
}
return 0;
}
In this example, there are three blocks:

• The main function block


• The if-else block
• The else block
The if-else block is nested inside the main function block. The else block is also nested inside
the if-else block.
2.14 Initialization

Initialization in C programming is the process of assigning an initial value to a


variable or object. It's a crucial part of programming, ensuring that variables have
meaningful values before they're used.

35 | S M V E C / C S B S
Types of Initialization in C
C programming supports two primary methods for initializing variables:
1. Initialization at declaration: This involves assigning a value to a variable when
declaring it. For instance:
C
int age = 25; // Initializes 'age' with the value 25
2. Initialization with assignment statements: This involves assigning a value to a
variable after it's declared. For example:
C
int number;
number = 10; // Assigns the value 10 to the previously declared
'number' variable
Specific Cases of Initialization
C handles initialization differently for certain data types:
1. Static variables: Static variables are initialized to 0 by default if no explicit
initialization is provided.
2. Global variables: Global variables are initialized to 0 by default if no explicit
initialization is provided.
3. Arrays: Arrays can be initialized using initializer lists, where each element is
assigned a value. For example:

int numbers[] = {1, 2, 3, 4, 5}; // Initializes an array 'numbers' with


elements 1 to 5
4. Structures: Structures can be initialized using designated initializers, where
each member is assigned a value. For example:

struct Point {
int x;
int y;
};

struct Point point = {10, 20}; // Initializes a struct 'point' with


members 'x' and 'y' having values 10 and 20, respectively
Importance of Initialization
Initializing variables is essential for several reasons:
1. Prevents unpredictable behavior: Using uninitialized variables can lead to
unexpected values and program crashes.
2. Improves code readability: Explicit initialization makes code clearer and easier
to understand.
3. Ensures data integrity: Assigning meaningful initial values ensures that
variables hold valid data before usage.
Guidelines for Proper Initialization

36 | S M V E C / C S B S
• Initialize variables as soon as possible: This prevents them from holding
garbage values.
• Use appropriate initial values: Assign values that make sense for the
variable's purpose.
• Consider default initialization: Static and global variables are initialized to 0 by
default, which may be suitable in certain cases.
By following these guidelines, you can ensure that your C programs are well-
behaved, reliable, and easy to maintain.

2.15 Recursion
Recursion is the process of calling a function itself repeatedly until a particular
condition is met. A function that calls itself directly or indirectly is called a recursive function
and such kind of function calls are called recursive calls.
In C, recursion is used to solve a complex problem. Using recursion we can solve a
complex problem in a small piece of code by breaking down the problem. We can solve large
numbers of problems using recursion for example factorial of a number, generating Fibonacci
series, generating subsets etc.
Recursive Functions
A function that calls a copy of itself is called Recursive Function. The recursive
functions contain a call to themselves somewhere in the function body. Moreover, such
functions can contain multiple recursive calls
Basic Structure of Recursive Functions
The basic syntax structure of the recursive functions is:
type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}

Example of Recursion in C
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);

37 | S M V E C / C S B S
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

2.16 Pre-processor

In C programming, a preprocessor is a program that processes the source code before


it is compiled. It is a separate step in the compilation process, and it is typically invoked
by the compiler automatically. The preprocessor performs a number of tasks,
including:

38 | S M V E C / C S B S
• File inclusion: It allows you to include the contents of other files in your
program using the #include directive. This is useful for sharing common code
across multiple files.
• Macro definition: It allows you to define macros, which are simple
substitutions for longer constructs. This can make your code more concise and
readable.
• Conditional compilation: It allows you to conditionally include or exclude
code based on preprocessor directives. This can be used to create different
versions of your program for different platforms or configurations.
How to Use the Preprocessor
The preprocessor is used by adding preprocessor directives to your C source code.
Preprocessor directives are lines of code that start with a # character. The most
common preprocessor directives are:
• #include: Inserts the contents of another file into the current file.
• #define: Defines a macro, which is a simple substitution for a longer construct.
• #ifdef: Checks if a macro is defined.
• #ifndef: Checks if a macro is not defined.
• #if: Conditionally includes or excludes code based on a condition.
• #elif: Provides an alternative condition for conditional inclusion or exclusion
of code.
• #else: Provides the default code for conditional inclusion or exclusion.
• #endif: Ends a conditional block.
Benefits of Using the Preprocessor
The preprocessor can be a powerful tool for improving the readability, maintainability,
and flexibility of your C code. By using the preprocessor, you can:
• Reduce code duplication: Avoid duplicating code by including common code
from other files.
• Make code more concise: Define macros for longer constructs to make code
more readable.
• Support conditional compilation: Create different versions of your program for
different platforms or configurations.
Examples of Preprocessor Usage
Here are a few examples of how the preprocessor can be used in C programming:
• Including a header file: The following line of code includes the contents of the
stdio.h header file, which contains definitions for standard input/output
functions:

#include <stdio.h>

39 | S M V E C / C S B S
• Defining a macro: The following line of code defines a macro called MAX that
expands to the value 100:

#define MAX 100


• Using a conditional statement: The following code snippet conditionally
includes a block of code based on whether the macro DEBUG is defined:

#ifdef DEBUG
printf("Debug message\n");
#endif
2.17 Standard Library function and return types

The C Standard Library is a collection of functions and data types that are
available to all C programs. It provides a wide range of functionality, including
input/output, string manipulation, memory management, and mathematical
operations.

Here are some of the most commonly used Standard Library functions and their
return types:

• printf(): Formats and prints data to the standard output stream. Returns an
integer indicating the number of characters printed.
• scanf(): Reads formatted input from the standard input stream. Returns the
number of items successfully converted and stored.
• strcpy(): Copies a string from one location in memory to another. Returns a
pointer to the destination string.
• strlen(): Returns the length of a string.
• malloc(): Allocates memory from the heap. Returns a pointer to the allocated
memory or NULL on failure.
• free(): Frees memory that was previously allocated with malloc().
• abs(): Returns the absolute value of an integer.
• sqrt(): Returns the square root of a double-precision floating-point number.
• sin(): Returns the sine of a double-precision floating-point number.
• cos(): Returns the cosine of a double-precision floating-point number.

40 | S M V E C / C S B S

You might also like