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

Programming in C

Uploaded by

mdshafiquemscc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Programming in C

Uploaded by

mdshafiquemscc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 108

UNIT 1

An Overview of C

Learning Objectives Introduction


At the end of this unit, you will
Dennis M. Ritchie created the general-purpose, high-level language
be able to:
C to create the UNIX operating system at Bell Laboratories. On the
 Define variables, expressions, DEC PDP-11 computer, C was first introduced in 1972.
and assignment

The K&R standard, currently known as the first publicly


 Discuss how we implement
#define and #include
accessible definition of C, was created in 1978 by Brian
Kernighan and Dennis Ritchie.
 Learn about Printf() and scanf()

The C programming language was used to create the UNIX


operating system, the C compiler, and basically all UNIX application
applications.

For a number of reasons, C is now a


popular professional language:
Simple to learn

Structured language

It creates effective programmes

It is capable of handling simple tasks

It can be built on a number of different computer platforms

Why use C?

C was initially utilised for system development tasks, especially for


the operating system's programmes. Because C produces code that
executes almost as quickly as code written in assembly language,
it was accepted as a system development compiler is called by the cc command, hence the
language. name of the command also serves as the name
of the compiler.
Here are a few instances where C is used:
As a result, the terms C compiler and cc
compiler are used synonymously. A compiler,
roughly speaking, converts source code into
executable object code. This compiled code
is automatically created in a file called a.out
on UND(systems. This compiled code is
Operating Systems Network Drivers
automatically generated on MS-DOS computers
Language Compilers Modern Programs in a file with the same name as the.c file, but with

Assemblers Databases the.exe extension in place of the.c extension.

Text Editors Language Interpreters


Variables, Expressions, and Assignment
PrintSpoolers Utilities
Let's create a program that translate the
kilometers from miles and yards that make up a
marathon. The length of a marathon is 26 miles
Programming and Preparation
and 385 yards in English units. Integers make up
The operating system, a collection of unique these numbers. We multiply by the conversion
applications, is installed on the device. Operating factor, 1.609, a real integer, to change miles to
systems like MS-DOS, OS/2, and UNIX are kilometers. Computers store integers differently
frequently accessible. An operating system than reals in memory. We divide by 1760.0 to
controls the resources of the computer, offers convert yards to miles, and as we will see, it is
user software, and serves as a conduit between important to represent this value as a real rather
the hardware and the user. The C compiler and
than an integer.
several text editors are only a couple of the
numerous software packages that the operating Our conversion program will include variables
system offers. Vi is the name of the default text that can store both real and integer data, In C,
editor on UNIX systems. the first line of code must declare (or name)

The text editor and compiler are integrated the aU variables. An identifier, also known as a

in certain systems, such Borland C++. We variable name, is made up of a string of letters,
presume that the reader is able to produce C digits, and underscores but cannot begin with a
code files using a text editor. These files are digit. The selection of identifiers should take into
known as source files, and on the majority of account the program's intended use. They act as
UNIX systems, they are compiled using the cc documentation in this way, improving software
command, which launches the C compiler. The readability.

An Overview of C - Unit 1 2
In file marathon.c of operators with variables and constants is also
an expression, as is the name of a variable by
/*' The distance of a marathon in kilometers. */
itself.

#include <stdio.h>
Conversion rules may be incorporated into the

int main(void) evolution of expressions. This is a crucial idea.


Any remainder is removed when two integers
{ are divided, yielding an integer value. As an
illustration, the phrase 7/2 has an int value of
int miles, yards;
3. On the other hand, 7.0/2 is a double divided
float kilometers; by an int. The value of the equation 2.1S was
immediately changed to a double when the
miles 26; expression 7.0/2 was evaluated, giving 7.0/2 the
value 3.5.
yards 385; ,
kilometers 1.609 * (miles + yards / 1760.0);
kilometers = 1.609 R * (miles + yards I 1760.0);
is converted to
printf("\nA marathon is %f kilometers.\n\n",
kilometers); kilometer = 1.609 * (miles + yards / 1760);

return 0; This results in a software bug. Due to the fact


that the variable yards is an int and has a value,
}
yard/1760
Output:
results in the integer value O when using
A marathon is 42.185970 kilometers .
integer division. Not what is desired is this. The
When a number has a decimal point, it is a error is fixed by using the double-type constant
floating-point constant as opposed to an integer 1760.0.
constant. Therefore, a program would handle the
#define and #include
integers 37 and 37.0 in various ways. Despite the
fact that there are three forms of floating—float, The instructions for the preprocessor are
double, and long double Floating constants are #include and #define. The header files are
always of type double, while variables can be included in a source code file using the #include
declared to be of any of these kinds. command. Programs can declare macros or
constants using the #define statement.
Expressions are typically found as parameters
to functions and on the right side of assignment Introduction to Define and Include in C
operators. Simplest expressions include
solely of constants, like 385 d 1760.0 from the Before the source code is built, the
preceding program. A meaningful combination preprocessor in C processes commands known

An Overview of C - Unit 1 3
as preprocessor directives. They do not end constant values or expressions with names
with a semicolon and start with the symbol "#." that can be reused frequently. The defined
Preprocessor directives used frequently in C macros name replaces each time a #define C
include : pre processor directive is encountered with a
specific constant value or expression.
To include header files in a source
code file, use this directive. The Syntax of #define in C
#include header file's location can be
The following is the syntax for the C #define
specified using either double
quotes ("") or angle brackets (<>). preprocessor directive:

With this pre-processor directive, #define CNAME expression


a constant or macro can be OR
defined in Cis. You can use it to
#define
give a constant value a name or #define CNAME value
to make a macro that can be used
CNAME: It is the expression's or constant
repeatedly throughout the code.
value's name. Programmers frequently define it
Conditions are compiled using in capital letters.
these directives. Depending on
#ifdef,
whether a particular symbol is expression: Any mathematical equation or
#ifndef,
declared or not, they are used to piece of code is acceptable.
#endif
include or omit specific sections
of the code.
value: It can be an int, char, float, or other data
type constant.
To give the compiler
#pragma implementation-specific choices, Example of #define keyword in C
use this directive.
#include <stdio.h>
By using this directive, a compile-
// defines the PI value to be 3.14 in the whole
#error time error with a specific error
program
message can be produced.
#define PI 3.14
There are other preprocessor directives in int main() {
C besides these, which are some of the most
float radius, circumference;
used ones. Preprocessor directives are handled
before the actual compilation, thus it is vital to radius = 56.0;
remember that they are not a component of the C // PI will be replaced by 3.14 in the below
language itself but rather a preprocessor feature. statement

define in C circumference = 2 * PI * radius;

printf("Circumference of Circle : %0.2f",


C macros are defined using the preprocessor
circumference);
command #define in a C program. Also known
as the macros directive, #define The #define return 0;
directive in a C program is used to declare }

An Overview of C - Unit 1 4
Output: • Creating platform-specific code: The
programmer can write platform-specific
Circumference of Circle : 351.68
code for several operating systems or

Explanation: We used #define in the code architectures with #define c.

above to give "PI" the value 3.14. This will


• Creating custom debug statements:
substitute the value 3.14 for "PI" in the program.
A single line of code can be changed

Uses of #define keyword in C to activate or disable specific debug


statements that the programmer has
Uses of "#define" that are frequent include:
created using the #define function.

• Defining constants: A preprocessor macro


include in C
can be given a constant value using the
#define define C directive, and that constant The "include" command is used in C

value can subsequently be used in place programming to include header files in a source

of the value throughout the program. For code file. Function and variable declarations that

instance, one could use a macro called PI, can be utilised in the source code file are found

defined as #define PI 3.14159, instead of in the header file. With the preprocessor directive

using the value 3.14159 throughout the "#include" and the header file's name enclosed in

program. double quotes or angle brackets, the header file


is included.
• Creating custom macros: The #define c
directive allows the programmer to build Syntax of #include in C

unique macros that can be used to simplify


The following is the syntax for the C #include
difficult expressions or give values more
preprocessor directive:
meaningful names.
#include
• Conditional compilation: If a macro is
present, preprocessor directives like #ifdef, OR
#ifndef, #if, #else, and #endif can be used
#include "file_name"
to influence the compilation of specific
code sections. File_name: You wish to add the name of a
header file. The term "header file" refers to a C file
• Creating shorthands for keywords: With
with the common ".h" file extension that contains
#define, a programmer can construct
declarations and macro definitions that may be
shorthands for terms or expressions that
shared by several source files.
are often used in the code.

An Overview of C - Unit 1 5
Example of #include in C • Including standard library headers:
Headers like "stdio.h" and "stdlib.h" include
#include <stdio.h>
declarations for several of the standard C
int main() { library functions, including "printf,""scanf,"
and "malloc." To make the functions they
int a, b, product; contain available to the remainder of the

// we can use printf() and scanf() function program, these headers are normally

because inserted at the start of a C source file.

// these functions are pre-defined in the • Including user-defined header files: The
stdio.h header file declarations of functions, variables, and
other constructs that a programmer uses
printf("Enter two numbers to find their sum across numerous source files can be found
: ");
in their own header files. Programmers

scanf("%d %d", &a, &b); can reuse declarations that are common
across several source files and lessen
product = a*b; code duplication by including these header
files.
printf("Sum of %d and %d is : %d", a, b,
product); • Including third-party headers: In order to
use the functionality offered by third-party
return 0;
libraries or frameworks in a C program,
} it is frequently essential to include the
appropriate header files.
Output:
• Conditional inclusion of headers: In order
Enter two numbers to find their sum : Sum of
to include or exclude header files depending
3 and 4 is : 12
on specific criteria, preprocessor directives
Explanation: like #ifdef, #ifndef, #if, #else, and #endif
might be used.
The header file "stdio.h," which includes
definitions of functions for taking input and • Creating custom macros: Custom macros
creating output, has been included in the code can be built by the programmer using the
above. Because we included the header file using #define directive and then added to source
the #include keyword, we can utilise the scanf() files using the #include directive.
and printf() functions.
Printf() and scanf()
Uses of #include in C
Both the result and user input are displayed
Using "#include" frequently in C involves:
using the printf() and scanf() functions,

An Overview of C - Unit 1 6
respectively. In the C programming language, Simple Example of printf() Function
the printf() and scanf() methods are often used.
#include<stdio.h>
These functions are built-in library functions
found in C programming header files. int main()

printf() Function {

For output, the C programming language int num = 450;

uses the printf() function. The printf() method


// print number
can accept any number of parameters. Each
subsequent argument must be separated from printf("Number is %d \n", num);

the first by a comma (,) in double quotes. The first


return 0;
argument, "hello," must be enclosed in double
quotations. }

Important points about printf(): Output:

In the header file stdio.h, the printf() function Number is 450

is defined. This function allows us to print data scanf() Function


or a message that we define on the monitor (also
called the console). A variety of data formats can Data supplied from the console is read using
the scanf() method. The C library includes a
be printed using printf() on the output string.
built-in function called scanf(). The C language's
We use "\n" in the printf() command to print scanf() function can read character, string,
on a new line on the screen. numeric, and other data from the keyboard.
When given additional arguments, scanf() will
C-based programming languages are case- receive formatted data from the user and assign
sensitive. For example, printf() and scanf() are it to the variables. Extra arguments must point to
treated differently from Printf() and Scanf (). All variables with the same datatype as the format
characters must be lowercase for the built-in of the user input.
methods printf() and scanf() to function properly.
Syntax

Syntax
scanf("format specifier",argument_list);

printf("format specifier",argument_list); Simple Example of scanf() Function

%d (integer), %c (character), %s (string), #include<stdio.h>


%f (float), %lf (double), and %x (hexadecimal)
int main()
variables can all be used in the format string for
output. {

An Overview of C - Unit 1 7
int x; a system development language because
it produces code that runs nearly as fast as
printf("enter the number =");
the code written in assembly language.

scanf("%d",&x);
• The evolution of expressions can involve

printf("The number is=%d",x); conversion rules. This is an important


point. The division of two integers results
return 0; in an integer value, and any remainder is
discarded.
}
• #include and #define are the preprocessor
Output:
directives. #include is used to include the
enter the number =180 header files in a source code file. #define
is used to define macros or constants in
The number is=180 programs.

Summary • In a C program, the preprocessor command


#define is used to define C macros. #define
• C is a general-purpose, high-level language
also known as macros directive. In a C
that was originally developed by Dennis
program, the #define directive is used to
M. Ritchie to develop the UNIX operating
declare constant values or expressions with
system at Bell Labs. C was originally first
names that may be used repeatedly. Every
implemented on the DEC PDP-11 computer
time a #define C preprocessor directive
in 1972.
is encountered, the defined macros name
• C was initially used for system development substitutes a specified constant value or
work, particularly the programs that make- expression in its place.
up the operating system. C was adopted as

An Overview of C - Unit 1 8
UNIT 2

Arrays, Strings, and Pointers

Learning Objectives Introduction


At the end of this unit, you will
An array name alone in C is a pointer, while a string is an array of
be able to:
characters. The ideas of arrays, strings, and pointers are hence closely
 Recognize arrays and string related. A pointer is nothing more than an object's memory address.
handling Unlike to most other languages, C supports pointer arithmetic. Pointer
arithmetic is one of the language's strong features since it allows for
 Define pointers
the creation of extremely useful pointer expressions.
 Discuss about operating
system considerations
Arrays

When several variables of the same type are required, arrays are
utilized.

For instance, the assertion

int a[3];

gives the three-element array a space to be used. The array's


elements, which are of type int, are accessed using the symbols [0],
[1], and [2]. An array's index, or subscript, always begins at O. The
use of an array is demonstrated in the following application. Five
scores are read into the computer, sorted, and then printed out in
chronological sequence.

For Example: In C

#include<stdio.h>

#define CLASS_SIZE 5

int main (void)


{ Ordered score:

int i, j, score[CLASS_SIZE]. sum = 0, tmp; Score[0] = 97

for (i = 0; i < CLASS_SIZE; ++i) { Score[1] = 88

scanf("%d", &score[i]); Score[2] = 77

sum += scorer;]; Score[3] = 63

} Score[4] = 53

for (i 0; i < CLASS_SIZE - 1; ++i) /* bubble sort 378 is the sum of all scores
*/
75.6 is the class average
for (j = CLASS_SIZE - 1; j > i;--j)
The application sorts the scores using a
if (score[j-1J < score[j]) { /* check the order */ bubble sort. This design is commonly carried out
using nested for loops, with a test being made
tmp = score[j-l];
in the inner loop's body to determine whether a

score[j-1] = score[jJ; score[j] = tmp; pair of elements are in the correct order. When
elements are compared that are not in the proper
} sequence, their values are switched. Here, the
code carries out this transaction.
printf("\nOrdered scores:\n\n");
mp = score[j-1];
for (; = 0; i < CLASS_SIZE; ++i)
score[j-1] = score[j];
printf(" score[%d] =%5d\n", i, score[i]);
score[j] =: tmp;
printf("\n%18d%s\n%18.lf%s\n\n",
The variable tmp in the first sentence holds
sum, " the sum of all the scores",
the value of score [j-l]. In the next sentence, the
(double) sum / CLASS_SIZE, " the class value of score [j] is used in place of the value of
average"); score [j-1] that was previously stored in memory.
The final sentence substitutes the value of score
return 0; [j] for the original value of score I, which is now
stored in tmp.
}
By manually executing the program with
The results will appear on the screen if we run
the given data, the reader will be able to see
the application and enter the scores 63, 88, 97,
why this bubble sort construct of two nested
53, and 77 when prompted.
far loops results in an array containing sorted
Input 5 Scores: 63 88 97 53 77 elements. With each iteration of the outer loop,

Arrays, Strings, and Pointers - Unit 2 10


the necessary value among those that need to be The declaration and initialization that follow
processed is bubbled into position, giving bubble produce a string containing the word "Hello". The
sort its name. character array holding the string must be one
character larger than the word "Hello" in order to
While bubble sorts are easy to program,
accommodate the null character at the end of
they are not very efficient. Certain sorting
the array.
techniques operate much more fast. Efficiency
is not important when sorting a small number of
items seldom, but it becomes important when
The following sentence can be used to express
the number of items is large or the code is used
the above statement if you adhere to the rule of
frequently. This word
array initialization:
(double) sum / CLASS_SIZE

which employs a cast operator and appears as


The above-described string's memory
an argument in the final printf() statement. The
presentation in C is seen below;
(double) sum function has the effect of casting
the sum's int value to a double. The cast is
completed before division takes place since a cast Index 0 1 2 3 4 5

Variable
operator's precedence is higher than a division H e l l o \0

Address 0x23451 0x23452 0x23453 0x23454 0x23455 0x23456


operator's. A mixed expression is created when
a double is divided by an int. Now, conversion
happens automatically. The operation results in
The null character is not actually added to
a double once the int is upgraded to a double.
the end of a string constant. After initialising the
In the absence of a cast, integer division would
array, the C compiler automatically appends the
have taken place and any fractional parts would
'\0' to the end of the string. Let's try printing the
have been thrown away. Also, since the outcome
string described above:
would have been an int, the printf() statement's
format would have been incorrect. #include <stdio.h>

String Handling int main ()

A character array is what C refers to as a string. {

In addition to demonstrating how to utilise strings char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
in this part, we also want to demonstrate the use
of getchar() and putchar (). These are macros printf("Output message: %s\n", greeting );

from the stdio.h file. A macro is used similarly to return 0;


a function, despite some technical distinctions.
}
To read characters from the keyboard and print
characters on the screen, respectively, use the When the aforementioned code is compiled
macros getchar() and putchar(). and run, the following outcome is obtained:

Arrays, Strings, and Pointers - Unit 2 11


Output message: Hello printf("strcat( str1, str2): %s\n", str1 );

Several functions that work with null- /* total lenghth of str1 after concatenation */
terminated strings are available in C:
len = strlen(str1);
strcpys1, s2 Copies string s2 into string s1.
printf("strlen(str1) : %d\n", len );
Concatenates string s2 onto
strcats1, s2;
the end of string s1. return 0;

strlens1 Returns the length of string s1.


}
Returns 0 if s1 and s2 are the
strcmps1, s2 Output
same; less than 0 if s1s2.

Returns a pointer to the first strcpy( str3, str1) : Hello


strstrs1, s2 occurrence of string s2 in
string s1. strcat( str1, str2): HelloWorld

strlen(str1) : 10
The example below uses a few of the
aforementioned features: Pointers
#include <stdio.h> You must have a solid working understanding
of pointers if you wish to be effective at
#include <string.h>
developing code in the C programming language.
int main () One of those concepts that C beginners find
challenging is the idea of pointers. This unit's
{ goal is to introduce pointers and demonstrate
how to use them effectively in C programming.
char str1[12] = "Hello";
Ironically, the terminology used for pointers in C
char str2[12] = "World"; is more of a challenge than the actual idea itself.
There are three primary uses for pointers in C.
char str3[12];
They are initially employed to create dynamic
int len ; data structures, which are composed of run-
time heap-allocated memory chunks. Second, C
/* copy str1 into str3 */
handles pointers used as variable parameters in
strcpy(str3, str1); functions. Finally, dealing with strings makes use
of pointers in C, which provides an alternative
printf("strcpy( str3, str1) : %s\n", str3 ); method of accessing data kept in arrays. A
typical variable is a location in memory that can
/* concatenates str1 and str2 */
be used to store a value.
strcat( str1, str2);
For instance, four bytes of memory are

Arrays, Strings, and Pointers - Unit 2 12


reserved for the variable I when you declare it type of machine. Running the code given below
to be an integer. You use the term I to designate will provide you with information on the size of
that memory region in your program. The four the different data kinds on your system.
bytes at that place have a memory address at
# include <stdio.h>
the machine level, where they can each carry an
integer value. main()

A variable that points to another variable {


is called a pointer. This indicates that it stores
the memory location of a different variable. In printf(“n Size of a int = %d bytes”, sizeof(int));
other words, the pointer contains the address
printf(“\n Size of a float = %d bytes”,
of another variable rather than a value in the
sizeof(float));
conventional sense. By storing its address, it
serves as a pointer to the other variable. A pointer printf(“\n Size of a char = %d bytes”,
contains two components because it stores an sizeof(char));
address rather than a value.
}
The address is stored in the pointer itself. Its
After running the program we will below output:
address denotes a worth. Both the value pointed
to and the pointer are present. Pointers can be Size of int = 2 bytes
helpful, strong, and generally trouble-free tools
as long as you take care to make sure they Size of float = 4 bytes
always point to appropriate memory regions in
Size of char = 1 byte
your programmes.
A memory region that may store a value is
Characteristics
referred to as an ordinary variable. For instance,
The memory of a computer is composed of the compiler reserves 2 bytes of RAM (depending
a series of storage units known as bytes. An on the PC) to keep the value of the integer when
address is a number that is connected to each you declare a variable as an integer. You use the
byte. The compiler immediately allots a certain name num to refer to that memory region in your
block of memory to keep the value of a variable program. There is a memory address for that
when we define it in our program. This block of region at the machine level.
memory will have a distinct starting address
int num = 100;
because every cell has a distinct address. The
permitted range for the variable determines how Either the memory address or the name num
big this block should be. For instance, an integer can be used to access the value 100. Addresses
variable on a 32-bit computer is 4 bytes in size. In can be kept in any other variable because they are
earlier 16-bit computers, an integer was 2 bytes. just digits. Pointers are those variables that store
In C, a variable type like an integer does not the addresses of other variables. In other terms,
necessarily need to have the same size on every a pointer is just a variable that holds an address,

Arrays, Strings, and Pointers - Unit 2 13


or a location in memory where another variable is Guidelines for designing and running a C
located. By storing its address, a pointer variable application
"points to" another variable. A pointer has two
• Create a text file with a C program in it,
components because it stores an address rather
like pgm.c, using an editor. The file must
than a value. The address is stored in the pointer
have a name that ends in .c to indicate that
itself. Its address denotes a worth. A pointer and
it includes C source code. For instance,
the value it points to are present.
on a UNIX system, we would issue the
Characteristic features of Pointers: command to use the vi editor.

Pointers are used in programming to: vi pgm.c

• When addresses are used to alter the The programmer must be familiar with the
data directly, the application will run more proper commands for adding and editing text in
quickly. order to use an editor.

• Memory space will be saved. • Compile the program. The command will
enable you to achieve this.
• Memory access will be quick and effective.

cc pgm.c
• Allotted memory is dynamic.

The cc command calls the preprocessor,


Operating System Considerations
compiler, and loader individually. By modifying
Writing and Running a C Program a copy of the source code in compliance with
the preprocessing directives, the preprocessor
Operating system, text editor, and compiler
produces a translation unit. The compiler
are the three variables that determine the precise
transforms the translation unit into object code.
actions that must be taken to generate a file
The programmer must return to step 1 and
containing C code, compile it, and execute it. The
change the source file if mistakes are discovered.
general process is the same in every situation,
Errors that occur at this stage are referred to as
though. First, we give a thorough explanation
syntax errors and compile-time errors. If there
of how it is carried out in a UNIX system. The
are no errors, the loader creates the executable
process is then discussed in an MS-DOS context.
file a.out using both the object code produced
The C compiler will be called using the cc by the compiler and object code taken from a
command in the explanation that follows. number of the system's libraries. The application
Nevertheless, in practice, the command is can now be run since it is ready.
dependent on the compiler being used. For
• Execute the program. To accomplish this,
instance, we would use the command tee rather
use the command.
than cc if we were using the Turbo C compiler
from Borland's command line interface. a.out

Arrays, Strings, and Pointers - Unit 2 14


Usually, when the program has finished the compiler. An attempt to divide by zero, for
running, a system prompt will reappear on the instance, could be encoded into a program, which
screen. Run-time errors are any errors that could result in a run-time error when the program
happen while a program is being executed. The is run. Typically, a run-time error's error message
programmer must start over at step 1 if the isn't very helpful in identifying the problem.
program needs to be altered for any reason.
So let's think about an MS-DOS environment.
The file a.out will be replaced and its prior Most likely, another text editor would be utilised
contents lost if we compile a different application.
in this situation. Certain C systems, like Turbo
The executable file a.out needs to be moved or
C, offer both an integrated environment and
renamed if the contents are to be stored. Let's
a command line environment. The text editor
say we issue the command.
and compiler are both a part of the integrated

cc sea.c environment. (For specifics, consult the Turbo


C manuals.) The command that starts the C
This results in the automatic writing of
compiler differs depending on whether MS-DOS
executable code into a.out. We can issue the
or UNIX is being used.
command to save this file.
On MS-DOS, a C compiler's executable output
mv a.out sea
is written to a file with the same name as the
As a result, a.out is shifted out to sea. Now, source file but an.exe extension rather than a.c
the command can be used to run the program. extension. Think about the situation when we are
using the command-line environment for Turbo
sea
C. If we provide the instruction
In UNIX, it's customary to omit the.c suffix
tcc sea.c
and give the executable file the same name as
the related source file. The cc command's output then sea.exe will receive the executable code.
can be directed if we so choose by using the -0 We issue the command to run the application.
parameter. For instance, the instruction
sea.exe or equivalently sea
cc -0 sea sea.c
There is no need to type the.exe extension in
causes whatever is in a.out to remain intact
order to run the software. The rename command
while writing the executable output from cc
can be used to change the name of this file.
directly into sea.
Summary
A software may contain a variety of errors.
Run-time errors only appear while a program • In C, a string is an array of characters, and

is being run; syntax problems are captured by an array name by itself is a pointer. Because

Arrays, Strings, and Pointers - Unit 2 15


of this, the concepts of arrays, strings, and • The pointer in C language is a variable which
pointers are intimately related. A pointer is stores the address of another variable.
just an address of an object in memory. C, This variable can be of type int, char, array,
unlike most languages, provides for pointer function, or any other pointer. The size of
arithmetic. Because pointer expressions of the pointer depends on the architecture.
great utility are possible, pointer arithmetic However, in 32-bit architecture the size of
is one of the strong points of the language. a pointer is 2 byte.

Arrays, Strings, and Pointers - Unit 2 16


UNIT 3

Lexical Elements and


Operators
Learning Objectives Introduction
At the end of this unit, you will
A language is C. It features an alphabet and rules for how to combine
be able to:
words and punctuation to create proper, or legal, programmes, just
 Infer characters and lexical like other languages. The syntax of the language is defined by these
Elements
principles. The compiler is the program that verifies the validity of

 Discuss the concept of


C code. If there is a mistake, the compiler will stop and produce an
keywords and identifiers error message. If the source code is valid and free of mistakes, the
compiler converts it into object code, which the loader then uses
 Learn about operators and
to create an executable file. The preprocessor completes its work
punctuators
before the compiler is called. Because of this, we can consider the
preprocessor to be a component of the compiler.

This is actually the case on some platforms, but the preprocessor is


separate on others. We are not concerned with this in this chapter. But,
we must be aware that in addition to the compiler, the preprocessor
is another source of error messages. A C program is a series of
characters that a C compiler will translate into object code, which is
then translated onto a specific machine into a target language.

The target language will typically be a runnable or interpretable


kind of machine language. The program must be syntactically sound
for this to occur. Tokens, which might be considered the language's
core vocabulary, are initially created by the compiler by grouping
the characters in the program. There are six different categories of
tokens in ANSI C: operators, punctuation, constants, string constants,
and keywords. The compiler verifies that the tokens can be combined
into valid strings using the language's syntax.
The majority of compilers have highly specific {
specifications. A C compiler will not offer a
int a, b, sum;
translation of a syntactically wrong program,
regardless of how little the fault may be, in contrast printf("Input two integers: ");
to human readers of English who are capable of
understanding the meaning of a sentence with scanfC"%d%d", &a, &b);

an extra punctuation mark or a misspelt word. As


sum = a + b;
a result, the programmer needs to develop their
accuracy in developing code. printfC"%d + %d = %d\n", a, b, sum);

Characters and lexical Elements return 0;

The programmer creates a C program first as }


a string of characters. The following are some
Lexical Dissection of the addition Program
examples of characters that can be used in a
program: /* Read in two integers and pri nt thei r sum. */

Characters that can be used in a program A /* and */ character delimits a comment.


Each comment is first replaced by a single blank
Lowercase letters a b c . . . z
by the compiler. After that, the compiler either

Uppercase letters A B C . . . Z ignores white space or makes use of it to divide


tokens.
digits 0 1 2 3 4 5 6 7 8 9
#include <stdio.h>
other characters +-*/=(){}[]<>‘“!#%
This preprocessing instruction triggers the
&_|^~\.,;:?
inclusion of the stdio.h standard header file.
white space characters blank, newline, tab, etc It is included because it contains the printf()
and scanf function prototypes (). An example
The compiler gathers these characters into
of a declaration is a function prototype.
tokens, which are syntactic units. Before we Functionprototypes are necessary for the
move on to a strict description of C syntax, compiler to function.
let's take a quick look at a basic program and
arbitrarily highlight some of its tokens. int main(void)

In file sum.c {

1* Read in two integers and print their sum. *1 int a, b, sum;

#include <stdio.h> These characters are divided into four different


token types by the compiler. The parenthesis ()
int main(void) that come right after main are an operator, and

Lexical Elements and Operators - Unit 3 18


the function name n is the main identifier. At first, "Input two integers: "
this concept seems contradictory because what
A string constant is a group of characters that
you see after main is (void), but it's actually only
are contained in double quotes. This is viewed
the parentheses () that make up the operator.
as a single token by the compiler. Moreover, the
The compiler is informed that main is a function compiler supplies RAM for storing the string.
by this operator. The punctuation marks "{", ",",
"," and ";" are identifiers; "a,""b," and "sum" are &a, &b

keywords. The address operator is the letter &. It


is handled as a token by the compiler. The
int a, b, sum;
compiler treats each of the characters & and an

The compiler uses the white space between as a separate token even if they are close to one
another. We had the option to write
int and a to distinguish between the two tokens.
Nobody is a writer. & a, &b, or &a,&b

int a, b, sum; /* wrong: white space is but not


necessary */
&a &b /* the comma punctuator is
On the other hand, there is no need for any missing */

white space after a comma. We had the option


a&, &b /* & requires its operand to be on the
to write right */

int a,b,sum; but not int absum; sum = a + b;

Absum would be regarded as an identifier by Operators are the letters = and +. White space
the compiler. will not be used in this area, thus we may have

printfC"Input two integers: "); Sum a + b; or sum a + b ;

But not s u m a+b;


scanfC"%d%d" , &a, &b);

The comas would treat each letter on this


The parenthesis that follow the identifiers
line as a unique identifier if the latter had been
printf and scanf tell the compiler that they are
written. The compiler would complain that not all
functions. After the compiler has translated
of these identifiers have been declared.
the C code, the loader will attempt to create
an executable file. If the programmer hasn't The programmer makes advantage of white
space to make the code easier to read. A human
provided the code for printf() and scanf(), it will
reader sees program text as a two-dimensional
be taken from the standard library. Normally, a
tableau, whereas the compiler sees it as a single
coder wouldn't change these identifiers.
stream of characters.

Lexical Elements and Operators - Unit 3 19


Keywords and Identifiers select identifiers with mnemonic significance so
they can improve the program's readability and
Words that are explicitly reserved and have a
documentation.
precise meaning as separate tokens are known
as keywords. They cannot be modified or applied Identifier : : = {letter | underscore}1 {letter |
to other situations.
underscore | digit}0+
Keywords
Underscore : : - _
auto do goto signed unsigned
break double if sizeof void

case else int static volatile Some examples of identifiers are


char enum long struct while
const extern register switch
K
continue float return typedef

default for short union


_id

Iamamidentifier2
Figure: Keywords in C

There might be additional keywords in some So_am_i

implementations. These will change depending


But not
on the implementation or system. Here are a few
other Turbo C keywords as an illustration. Not#me /*special character # not allowed*/

Additional keywords for Borland C


101_south /*must not start with a digit*/
asm cdecl far huge interrupt near pascal

-plus /*do not mistake – for _*/

Figure: Additional Keywords in C


In order to provide software objects distinctive
In comparison to other popular languages, C names, identifiers are made. One way to think of
contains fewer keywords. For instance, Ada has keywords is as reserved identifiers with a certain
62 keywords. C is unique in that it can accomplish meaning. The C system is already aware of
a lot with only a small number of special symbols identifiers like scanf and printf as input/output
and keywords.
functions in the standard library. Normally,

Identifiers these names wouldn't be changed. The reason


the identifier ma; n is unique is because C
An identifying token consists of a string of
programmes always start their execution at the
characters, numbers, and the unique underscore
main function.
( ). A letter or an underscore must be the first
character of an identifier. Most C implementations
The length of discriminated identifiers is one of
treat the lowercase and uppercase letters
the main differences between operating systems
differently. It's best programming practice to
and C compilers. Just the first 8 characters of an

Lexical Elements and Operators - Unit 3 20


identification that has more than 8 characters will expression yields the value of a modulus b. For
be used on some older systems. Just ignoring instance, 5% 3 has a value of 2, whereas 7% 2 has
the remaining characters. For instance, on such a value of 1.
a system, the variable names
Operators in a program can be used to divide
I_am_an_identifier and I_am_an_elephant identifiers. Although it is customary to surround
binary operators with white space to improve
would be seen as being the same.
readability, this is not necessary.

An identifier's first 31 characters must be


a+b
distinguishable in ANSIC. Many C systems are
more discriminating. a–b

An important component of good programming Context can affect the interpretation of


is making meaningful name selections. some symbols. Consider the % sign in the two
statements as an illustration of this.
If you were to create a program to calculate
different taxes, you may include identifiers like printf("%d", a); and a = b % 7;
tax rate, price, and tax so that the assertion
The modulus operator is represented by the
Tax = price * tax_rate; second% symbol, whereas the first% symbol
marks the beginning of a conversion specification
would be clear in its meaning. The underscore
or format. The brackets, commas, semicolons,
is used to combine a string of words that are often
and parentheses are some examples of
separated by spaces into a single identification.
punctuation. Take into account this code:
The main rule for good programming style is
readability, followed by meaningfulness and int main(void)
avoiding confusion.
{
Operators and Punctuators
int a, b = 2, c
There are numerous special characters in
a = 17 * (b + c);
C that have specific meanings. The arithmetic
operators are a couple of examples. Following mai n, the parenthesis are regarded
as an operator. They inform the compiler that the
+-*/%
function's name is main. The punctuation marks
They stand for addition, subtraction, "{", ",", ";", U(", and ")" come next.
multiplication, division, and modulus—the
Operators and punctuation are used to
standard mathematical operations—respectively.
demarcate language elements and are both
Recall that in mathematics, the remainder
gathered by the compiler as tokens. The intended
produced when dividing an expression by an

Lexical Elements and Operators - Unit 3 21


usage of some special characters can be inferred The value will be 9.
from the context in which they are employed. For
The precedence and associativity rules for
instance, parentheses are sometimes used as
some of the C operators are provided in the table
punctuation and other times to denote a function
below.
name. The expressions provide yet another
illustration. Operator precedence and associativity
Operator Associativity
a+b ++a a += b
() ++ (postfix) -- (postfix) left to right

They all employ the character +, although ++ + (unary) - (unary) ++ (prefix) -- (prefix) right to left

and += are only single operators. A tiny symbol * / % left to right

set and a terse language result from making a + - left to right

symbol's meaning dependent on context. = += -= *= /= etc. right to left

Precedence and Associativity of Figure: Operator precedence and associativity


Operators
Any operator on a line, including '~, I, and%,
Expressions are evaluated according to the
has equal precedence to all other operators
precedence and associativity rules for operators.
on that line but has higher precedence than all
Due of the complier's flexibility to alter the the operators on lines below it. The right side
evaluation to suit its needs, these rules do not of the table displays the associativity rule for
completely dictate evaluation. Parentheses can each operator on a particular line. Every time
be used to clarify or alter the order in which we introduce a new operator, we will state its
operations are carried out because they are precedence and associativity rules. Frequently,
evaluated before any expressions outside of we will also add to this table to condense the
them. Think about the phrase information.

1+2*3 Every C programmer needs to be aware of


these guidelines. There is a unary plus in addition
Because the operator * in C has higher
to the binary plus, which stands for addition.
precedence than the operator +, multiplication
Both of these operators are denoted by a plus
takes place before addition in the program.
sign. Moreover, the negative symbol has unary
Hence, the expression's value is 7. A comparable
and binary interpretations.
expression is
Keep in mind that ANSI C marked the
1 + (2 * 3)
introduction of the unary plus. Traditional C
only has unary minus; there is no unary plus.
Yet, because parentheses-enclosed phrases
We can observe from the above table that unary
are evaluated first, the
operators take precedence over binary plus and
(1 + 2) * 3 minus. Within the phrase

Lexical Elements and Operators - Unit 3 22


-a & b – c separate tokens. For this reason, white
space, operators, and punctuators are
The first and second minus signs are binary
collectively called separators. White space,
and unary, respectively. Using the rules of other than serving to separate tokens, is
precedence, we can determine that the following ignored by the compiler.
expression is an equal one:
• A keyword, also called a reserved word, has
((-a) * b) – c a strict meaning. There are 32 keywords in
C. They cannot be redefined.
Summary
• Some identifiers are already known to the
• Tokens are the basic syntactic units of
system because they are the names of
C. They include keywords, identifiers, functions in the standard library. These
constants, string constants, operators, include the input/output functions scanf()
and punctuators. White space, along with and printf() and mathematical functions
operators and punctuators, can serve to such as sqrt(), sin(), cos(), and tan().

Lexical Elements and Operators - Unit 3 23


UNIT 4

The Fundamental Data Types

Learning Objectives Introduction


At the end of this unit, you will
Declarations, Expressions, and Assignment
be able to:

Fundamental data types are the data types which are predefined
 Define the concepts
declarations, expressions, and in the language and can be directly used to declare a variable in C.
assignment Fundamental data types are the basic data types and all other data
types are made from these basic data types.
 Recognize the use of getchar()
and putchar() A program works with things called variables and constants. All
variables in C must be declared before use. This could be how a
 Infer mathematical functions
program's introduction would appear.

#include <stdio.h>

int main(void)

int

float

a, b, c;

x, y = 3.3, z -7.7;

printf("Input two integers: ");

scanf("%d%d", &b, &c);

a = b + c;

x = y + z;
Each variable that is declared has a type operator in C. An example of an assignment
associated with it, which instructs the compiler expression is as follows:
to reserve the necessary amount of memory
space to retain the values for the variables. It i =7
also enables the compiler to precisely instruct
The expression as a whole is given the
the machine to do the specified tasks. At the
value 7, and the variable i is given the value 7.
machine level, using the operator + to two
An expression becomes a statement, or more
variables of type int in the expression b + c is
specifically, an expression statement, when
different from doing it to variables of type float in
it is followed by a semicolon. These are a few
the equation y + z.
instances of statements:

The technical distinctions between the two +


i = 7;
operations need not bother the programmer, but
the C compiler must be able to do so and produce printfC"The plot thickens!\n");

the appropriate machine instructions.


The next two assertions are perfectly legal,

A block of declarations and statements is but they have no purpose. In contrast to others,
certain compilers will alert users to these
enclosed by the braces { and}. The statements
assertions.
must come before any declarations.

3.777;
Operators, function calls, constants, and
variables are logically combined to form a + b;
expressions. A constant, variable, or function
Let's take a look at a sentence that starts with
call by itself can also constitute an expression.
a basic assignment expression and ends with a
Several examples of phrases are given below:
semicolon. The form will be as follows:
a+b
Variable = expr;
sqrt(7.333)
The right-hand side of the equal sign of the
5.0 * x - tan(9.0 / x) expression's value is computed first. The value is
subsequently assigned to the variable to the left
Phrases frequently contain a value. For
of the equal sign, which acts as the value of the
instance, the expression "a + b" has a clear value assignment expression as a whole. (Statements
dependent on the values of the variables a and b. have no intrinsic value.) The value of the
If a and b both have values of 1, then a + b has a assignment phrase as a whole is not employed
value of 3. in this case, as is to be noted. That is entirely OK.
The value that an expression generates is not
The equal symbol = is the basic assignment
necessary to be used by the programmer.

The Fundamental Data Types - Unit 4 25


The Fundamental Data Types The fundamental types can be divided into
functional categories. The types that can carry
Several of the basic data types that C offers integer values are known as integral types,
have already been seen. The restrictions on what whereas the kinds that can hold real values
can be kept in each kind must be discussed. are known as floating types. They are all

Fundamental data types: long form mathematically inclined.

char signed char unsigned char Fundamental types grouped by functionality


char signed chat unsigned char
signed short int signed int signed long
Integral types short int long
unsigned short int unsigned int unsigned long unsigned short unsigned unsigned long
float double long double Floating types float double long double
Arithmetic
Intergral types + Floating types
types
Figure: Fundamental data type: long form
Figure: Fundamental types grouped by
These are all keywords. They are ineffective as
functionality
variable names. Only char and int are permitted
to be used as keywords, despite the fact that they These group names are provided for
stand for "character" and "integer," respectively. convenience.
Further data types like arrays, pointers, and
structures are derived from the fundamental The Use of getchar() and putchar()
types.
For character 1/0, the standard C library offers
The word "signed" is not frequently used. For a number of functions and macros. We will now
instance, signed int is similar to ; int, and int is take a look at the getchar and putchar macros.
frequently used since shorter names are simpler These macros often work in a loop to read/write
to type. Nonetheless, the type char is unique in a series of characters because they only read or
this sense. Moreover, the terms "short int,""long write a single character.
int," and "unsigned int" can all be abbreviated to
A function call and a macro call are comparable.
just "short,""long," and "unsigned," respectively.
As a result, it consists of a macro name followed
Although the keyword signed by itself is
by a list of arguments separated by commas
comparable to int in this situation, it is rarely
and wrapped in two parenthesis. Even though a
used. With each of these conventions, a new list
is produced. macro doesn't require any parameters, the pair
of parentheses still has to be utilised.
Assume for the moment that the category type
is any of the basic types listed in the previous The getchar macro reads a single character

table. We can offer the basic declaration syntax from the keyboard's standard input stream. The

using this category: format of a call to getchar is as follows: getchar


(). Prior to providing its value, this macro waits
declaration :: = type identifIer { , identifier }0+ ; for the key to be depressed. The returned value

The Fundamental Data Types - Unit 4 26


can be put into a char variable. Interestingly, this entered character is displayed on the screen
macro actually gets information from the input using the getche function rather than the getch
buffer, which is processed only when the Enter function. The only difference between these two
key is hit by the application. Hence, getchar does functions is this.
not return a value before the user presses the
Example:
Enter key. Interactive programmes cannot use
it as a result. An alternative are the getch and #include<stdio.h>

getche procedures, which read data directly from void main() {


the keyboard.
char ch;

The putchar macro allows a single character int count =0, i =0;
to be written to the standard output stream
char Str [33] ;
(i.e., display). Putchar (c), where c is an integer
clrscr();
expression denoting the character to be written,
is the syntax for calling this macro. We generally printf("Write a short sentence:\n");
pass a character to this macro even though it //The following code counts number of
needs an argument of type int. The input value characters in string.
(c) is converted to an unsigned char and written
while ( (ch = getchar ()) != '.') {
to the standard output stream.
Str[i] = ch;
The getch and getche Functions
count++;
The getchar macro's use of line buffering i++;
makes it inappropriate for interactive settings.
}
There isn't a facility in the C standard library
that promises to deliver an interactive character Str[i] = '\0';

input. Because of this, the majority of C compilers // append null character at end of string
include substitute functions for usage in these
printf("The number of characters read are=
interactive settings. They consist of the getch
%d\n", count);
and getche functions offered in the console I/O
header file, <conio.h>. Calls to these functions printf("You have written the following

take the following forms, just like the getchar sentence.\n");

function: getch () and getche (). Both Dev-C++ puts(Str); //display the string on std <a
and Turbo C/C++ include these functions. These href="https://Test.com" data-internallinksma
functions have the names _getch and _getche in nager029f6b8e52c="6" rel="nofollow">output
Visual C++. device</a>.

The getch and getche procedures foresee a }


key press and immediately return the value. The

The Fundamental Data Types - Unit 4 27


Output: pow(base, returns the power of given
4)
exponent) number.
returns the absolute value of
5) abs(number)
given number.

C Math Example

Let's look at a straightforward example of a


math function from the header file math.h.

#include<stdio.h>
According to the while expression, when the
character '.' is encountered, the system stops #include <math.h>

reading the code. The string doesn't even contain


int main(){
the character ".". Reading is character-by-
character, therefore this offers a chance to get to printf("\n%f",ceil(3.6));
know a certain character. Counting characters is
printf("\n%f",ceil(3.3));
thus feasible.

printf("\n%f",floor(3.6));
Mathematical Functions
printf("\n%f",floor(3.2));
Via the functions defined in the <math.
h> header file, we can execute mathematical printf("\n%f",sqrt(16));
operations using the C programming language.
Many methods for carrying out mathematical printf("\n%f",sqrt(7));
operations, including sqrt(), pow(), ceil(), and
printf("\n%f",pow(2,4));
floor(), are included in the header file <math.h>.
printf("\n%f",pow(3,3));
C Math Functions
printf("\n%d",abs(-12));
The header file math.h contains a number of
methods. Here are listed some of the math.h return 0;
header file's frequently used functions.
}
No . Function Description
rounds up the given number. It Output:
returns the integer value which
1) ceil(number)
is greater than or equal to given
number.
rounds down the given number.
It returns the integer value which
2) floor(number)
is less than or equal to given
number.
returns the square root of given
3) sqrt(number)
number.

The Fundamental Data Types - Unit 4 28


Summary along double in 16 bytes. The type double,
not float, is the "wording" type.
• The fundamental data types are char,
short, int, long, unsigned versions of these, • Automatic conversions occur in mixed
and three floating types. The type char expressions and across an equal sign.

is a I-byte integral type mostly used for Casts can be used to force explicit

representing characters. conversions.

• Three floating types, float, double, and • Suffixes can be used to explicitly specify
the type of a constant. For example, 3U of
long double, are provided to represent real
type unsigned, and 7. 0F is of type float.
numbers. Typically, a float is stored in 4
bytes and a doub1 e in 8 bytes, the number • A character constant such as 1 A I is of
of bytes used to store along double varies type int in C, but it is of type char in C++.
from one compiler to another. However, as This is one of the few places where c++
compilers get updated, the trend is to store differs from C.

The Fundamental Data Types - Unit 4 29


UNIT 5

Operator In C

Learning Objectives Introduction


At the end of this unit, you will
Any programming language's core is its set of operators. Operators
be able to:
are symbols that enable us to carry out particular logical and
 Define the various operator mathematical operations on operands. The operands are operated
used in C
by an operator, in other words. In an illustration, the addition operator
"+" is employed as follows:

In this formula, "c" is equal to "a + b," where "a" and "b" are the
operands and "+" is the addition operator. The compiler is instructed
to add both operands, "a" and "b," by the addition operator.

Without the usage of operators, the C programming language


cannot work fully.

C can be divided into six kinds and has a large number of built-in
operators:

• Arithmetic Operators

• Relational Operators

• Logical Operators

• Bitwise Operators

• Assignment Operators

• Misc Operators
C Language code for arithmetic operator

#include <stdio.h>

main()

int a = 21;
Arithmetic Operators
int b = 10;
This operator is used to calculate numbers.
They are one of the binary or unary arithmetic int c ;
operators. where the unary arithmetic operator,
such as +,-, ++, --,!, tiled, only required one operand. c = a + b;
Addition, subtraction, multiplication, and division
are among these operators. In contrast, the printf("Line 1 - Value of c is %d\n", c );
binary arithmetic operator has two operands
and has the following operators: + (addition), - c = a - b;
(subtraction), * (multiplication), / (division), and
% (modulus). Yet because there is no exponent printf("Line 2 - Value of c is %d\n", c );
operator in C, modulus cannot be applied with a
c = a * b;
floating point operand.

Addition and subtraction are similar, but unary printf("Line 3 - Value of c is %d\n", c );
(+) and unary (-) are distinct. Integer arithmetic is
used when both operands are integers, and the c = a / b;
outcome is always an integer. Floating arithmetic
printf("Line 4 - Value of c is %d\n", c );
is known when both operands are floating point,
and mixed type or mixed mode arithmetic is
c = a % b;
known when the operands are both integer and
floating point. The outcome is of the float type. printf("Line 5 - Value of c is %d\n", c );
Operator Description Example

+ Adds two operands


A+B c = a++;
will give 30
Subtracts second operand from A-B
-
the first will give -10 printf("Line 6 - Value of c is %d\n", c );
A *B
* Multiplies both operands
will give 200
/ Divides numerator by de-numerator B /A will give 2 c = a--;
Modulus Operator and remainder
% B % A will give 0
of after an interger devision
Increments operator increases printf("Line 7 - Value of c is %d\n", c );
++ A++ will give 11
integer value by one
Decrements operator decreases
-- A-- will give 9 }
integer value by one

Figure: Arithmetic Operator. Output:

Operator In C - Unit 5 31
The following outcome is produced by 3. Greater than operator: Represented
compiling and running the aforementioned as ‘>’, the greater than operator checks
program: whether the first operand is greater than
the second operand or not. If so, it returns
Line 1 - Value of c is 31
true. Otherwise, it returns false. For

Line 2 - Value of c is 11 example, 6>5 will return true.

Line 3 - Value of c is 210 4. Less than operator: Represented as ‘<‘, the


less than operator checks whether the first
Line 4 - Value of c is 2 operand is lesser than the second operand.
If so, it returns true. Otherwise, it returns
Line 5 - Value of c is 1
false. For example, 6<5 will return false.

Line 6 - Value of c is 21
5. Greater than or equal to

Line 7 - Value of c is 22 operator: Represented as ‘>=’, the greater


than or equal to operator checks whether
Relational Operators the first operand is greater than or equal
to the second operand. If so, it returns true
It is employed to compare two expressions'
else it returns false. For example, 5>=5 will
values based on their relationships. Relational
return true.
expression is an expression that contains a
relational operator. The value is assigned in this 6. Less than or equal to operator:
case based on whether it is true or false. Represented as ‘<=’, the less than or
equal to operator checks whether the first
Examples include less than, more than, equal
operand is less than or equal to the second
to, etc. Let's examine each one in turn.
operand. If so, it returns true else false. For
example, 5<=5 will also return true.
1. Equal to operator: Represented as ‘==’, the
equal to operator checks whether the two Example:
given operands are equal or not. If so, it
returns true. Otherwise, it returns false. For // C program to demonstrate working of
example, 5==5 will return true. relational operators

2. Not equal to operator: Represented as ‘!=’, #include <stdio.h>

the not equal to operator checks whether


int main()
the two given operands are equal or not.
If not, it returns true. Otherwise, it returns {
false. It is the exact boolean complement
int a = 10, b = 4;
of the ‘==’ operator. For example, 5!=5 will
return false. // greater than example

Operator In C - Unit 5 32
if (a > b) // not equal to

printf("a is greater than b\n"); if (a != b)

else printf("a is not equal to b\n");

printf("a is less than or equal to b\n"); else

// greater than equal to printf("a is equal b\n");

if (a >= b) return 0;

printf("a is greater than or equal to b\n"); }

else Output:

printf("a is lesser than b\n"); a is greater than b

// less than example a is greater than or equal to b

if (a < b) a is greater than or equal to b

printf("a is less than b\n"); a is greater than b

else a and b are not equal

printf("a is greater than or equal to b\n"); a is not equal to b

// lesser than equal to


Logical Operators
if (a <= b)
Logical operators can be used to integrate

printf("a is lesser than or equal to b\n"); two or more conditions or constraints, as well
as to improve the analysis of the initial condition
else being looked at. The result of a logical operation

printf("a is greater than b\n"); is a Boolean value that can be either true or false.

// equal to For instance, when both of the conditions are


satisfied, the logical AND operator, represented
if (a == b) by the && operator in C, returns true. False is

printf("a is equal to b\n"); returned if not. As a result, a && b yields true


when both a and b are true (i.e. non-zero).
else
They can be used to combine two or more
printf("a and b are not equal\n"); restrictions or conditions, or they can be used to

Operator In C - Unit 5 33
improve the analysis of the initial condition being printf("a is greater than b AND c is equal
taken into account. These are described below: to d\n");

1. Logical AND operator: The ‘&&’ operator else


returns true when both the conditions under
printf("AND condition not satisfied\n");
consideration are satisfied. Otherwise, it
returns false. For example, a && b returns // logical OR example
true when both a and b are true (i.e. non-
if (a > b || c == d)
zero).
printf("a is greater than b OR c is equal to
2. Logical OR operator: The ‘||’ operator
d\n");
returns true even if one (or both) of the
conditions under consideration is satisfied. else
Otherwise, it returns false. For example, a ||
printf("Neither a is greater than b nor c is
b returns true if one of a or b, or both are
equal "
true (i.e. non-zero). Of course, it returns
true when both a and b are true. " to d\n");

3. Logical NOT operator: The ‘!’ operator // logical NOT example


returns true the condition in consideration
if (!a)
is not satisfied. Otherwise, it returns false.
For example, !a returns true if a is false, i.e. printf("a is zero\n");
when a=0.
else
Example:
printf("a is not zero");
// C program to demonstrate working of
return 0;
logical operators
}
#include <stdio.h>
Output:
int main()
AND condition not satisfied
{
a is greater than b OR c is equal to d
int a = 10, b = 4, c = 10, d = 20;
a is not zero
// logical operators
Short-Circuiting in Logical Operators:
// logical AND example
• In the case of logical AND, the second
if (a > b && c == d) operand is not evaluated if the first operand

Operator In C - Unit 5 34
is false. For example, because the first Output: Logical operator
operand of a logical AND is false, Program
• In the case of logical OR, the second
1 below does not output "Logical operator."
operand is not considered if the first
operand is true. For instance, program 1
#include <stdbool.h>
below doesn't print "Operator" because the
#include <stdio.h> first operand of the logical OR is true by
itself.
int main()
#include <stdbool.h>
{
#include <stdio.h>

int a = 10, b = 4; int main()

bool res = ((a == b) && printf("Logical {


operator"));
int a = 10, b = 4;
return 0;
bool res = ((a != b) || printf("Operator"));

} return 0;

Output: No Output }

• However, because the first operand of a Output: No Output

logical AND is true, the program below But, because the first operand of the logical
prints "Logical Operator." OR is false, the following program produces
"GeeksQuiz."
#include <stdbool.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdio.h>
int main()
int main()
{
{

int a = 10, b = 4; int a = 10, b = 4;

bool res = ((a != b) && printf("Logical bool res = ((a == b) || printf("Operator"));


Operator"));
return 0;

return 0; }

} Output: Operator

Operator In C - Unit 5 35
Bitwise Operators Operator Description Example
Binary AND Operator copies a (A & B) will give
& bit to the result if it exists in both 12, which is
Bit-level operations on the operands are operands. 0000 1100
(A | B) will give
carried out using the Bitwise operators. Prior to |
Binary OR Operator copies a bit if it
61, which is
exists in eigher operand.
performing the calculation on the operands, the 0011 1101
Binary XOR Operator copies the bit (A ^ B) will give
operators are translated to bit-level. For quicker ^ if it is set in one operand but not 49, which is
both. 0011 0001
processing, mathematical operations like Binary Ones Complement Operator (~A) will give
~ is unary and has the effect of -60, which is
addition, subtraction, multiplication, etc. can be
'flipping' bits. 1100 0011
carried out at the bit level. Binary left shift Operator. The left
A << 2 will give
operands value is moved left by
<< 240, which is
the number of bits specified by the
1111 0000
The following are the truth tables for &, |, and right operand.
Binary Right Shift Operator. The left
^: operands value is moved right by
A >> 2 will give
>> 15, which is
the number of bits specified by the
p q p&q p|q p^q 0000 1111
right operand.
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0 Example:
1 0 0 1 1

#include <stdio.h>
Assume if A = 60; and B = 13; now in binary
format they will be as follows: main()

Assume if A = 60; and B = 13; now in binary {

format they will be as follows:


unsigned int a = 60; /* 60 = 0011 1100 */

A = 0011 1100
unsigned int b = 13; /* 13 = 0000 1101 */

B = 0000 1101
int c = 0;

-----------------
c = a & b; /* 12 = 0000 1100 */

A&B = 0000 1100


printf("Line 1 - Value of c is %d\n", c );

A|B = 0011 1101


c = a | b; /* 61 = 0011 1101 */

A^B = 0011 0001


printf("Line 2 - Value of c is %d\n", c );

~A = 1100 0011
c = a ^ b; /* 49 = 0011 0001 */

The following table is a list of the bitwise


printf("Line 3 - Value of c is %d\n", c );
operators that the C language supports. If
variable A has a value of 60 and variable B has a c = ~a; /*-61 = 1100 0011 */
value of 13, then
printf("Line 4 - Value of c is %d\n", c );

c = a << 2; /* 240 = 1111 0000 */

Operator In C - Unit 5 36
printf("Line 5 - Value of c is %d\n", c ); The simplest assignment operator is this one.
The variable on the left is given the value on the
c = a >> 2; /* 15 = 0000 1111 */
right using this operator.

printf("Line 6 - Value of c is %d\n", c );


Example:

}
a = 10;

Output:
b = 20;

Line 1 - Value of c is 12
ch = 'y';

Line 2 - Value of c is 61
b) “+=”

Line 3 - Value of c is 49
This operator is created by combining the

Line 4 - Value of c is -61 "+" and "=" operators. This operator assigns the
outcome to the left variable after first adding the
Line 5 - Value of c is 240 left variable's present value to the right variable's
value.
Line 6 - Value of c is 15
Example:
Assignment Operators
(a += b) can be written as (a = a + b)
A variable's value is assigned using assignment
operators. A variable serves as the assignment If initially value stored in a is 5. Then (a += 6)
operator's left side operand, and a value serves = 11.
as its right side operand. The variable on the left
must have the same data type as the value on c) “-=”

the right side in order for the compiler to avoid


The '-' and '=' operators are combined to form
raising an error.
this operator. This operator assigns the result to

A variable's value is assigned using assignment the variable on the left after first subtracting the

operators. A variable serves as the assignment value on the right from the left's current value.

operator's left side operand, and a value serves


Example:
as its right side operand. The variable on the left
must have the same data type as the value on (a -= b) can be written as (a = a - b)
the right side in order for the compiler to avoid
If initially value stored in a is 8. Then (a -= 6)
raising an error.
= 2.
Below are examples of various assignment
d) “*=”
operators:

This operator is made up of the '*' and '='


a). “=”
operators. Prior to assigning the outcome to the

Operator In C - Unit 5 37
left variable, this operator multiplies the value of • Basically, the sizeof the operator is used to
the left variable by the value of the right variable. compute the size of the variable.

Example: b. Comma Operator

(a *= b) can be written as (a = a * b) • The comma operator (represented by the


token) is a binary operator that evaluates
If initially, the value stored in a is 5. Then (a *=
its first operand and discards the result,
6) = 30.
it then evaluates the second operand and

e) “/=” returns this value (and type).

This operator is created by combining the '/' • The comma operator has the lowest

and '=' operators. This operator divides the value precedence of any C operator.

of the variable on the left by the value of the


• Comma acts as both operator and
variable on the right before assigning the result
separator.
to the variable on the left.
c. Conditional Operator
Example:
The conditional operator is of the form
(a /= b) can be written as (a = a / b)
Expression 1? Expression 2 : Expression 3

If initially, the value stored in a is 6. Then (a /=


• Here, Expression1 is the condition to be
2) = 3.
evaluated. If the condition(Expression1)

Misc Operators is True then we will execute and return


the result of Expression2 otherwise if
Apart from the above operators, there are the condition(Expression1) is false then
some other operators available in C used to we will execute and return the result of
perform some specific tasks. Some of them are Expression3.
discussed here:
• We may replace the use of if..else
a. sizeof operator statements with conditional operators.

• sizeof is much used in the C programming d. dot (.) and arrow (->) Operators
language.
• Member operators are used to reference
• It is a compile-time unary operator which individual members of classes, structures,
can be used to compute the size of its and unions.
operand.
• The dot operator is applied to the actual
• The result of sizeof is of the unsigned object.
integral type which is usually denoted by
size_t. • The arrow operator is used with a pointer
to an object.

Operator In C - Unit 5 38
e. Cast Operator printf("The value of a - b is %d\n", a - b);

• Casting operators convert one data type printf("The value of a * b is %d\n", a * b);
to another. For example, int(2.2000) would
printf("The value of a / b is %d\n", a / b);
return 2.

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


• A cast is a special operator that forces one
data type to be converted into another. printf("The value of a++ is %d\n",

• The most general cast supported by most a++); // First print (a) and then increment
of the C compilers is as follows − [ (type) it
expression ].
// by 1
f. &,* Operator
printf("The value of a-- is %d\n",
• Pointer operator & returns the address of
a variable. For example &a; will give the a--); // First print (a+1) and then decrease
actual address of the variable. it

• Pointer operator * is a pointer to a variable. // by 1


For example *var; will pointer to a variable
printf("The value of ++a is %d\n",
var.
++a); // Increment (a) by (a+1) and then
Example:
print
// C Program to Demonstrate the working
printf("The value of --a is %d\n",
concept of
--a); // Decrement (a+1) by (a) and then
// Operators
print
#include <stdio.h>
// Assignment Operators --> used to
int main() assign values to

{ // variables int a =3, b=9; char d='d';

int a = 10, b = 5; // Comparison operators

// Arithmetic operators // Output of all these comparison


operators will be (1)
printf("Following are the Arithmetic
operators in C\n"); // if it is true and (0) if it is false

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

Operator In C - Unit 5 39
"\nFollowing are the comparison operators in The value of a + b is 15
C\n");
The value of a - b is 5
printf("The value of a == b is %d\n", (a == b));
The value of a * b is 50
printf("The value of a != b is %d\n", (a != b));
The value of a / b is 2
printf("The value of a >= b is %d\n", (a >= b));
The value of a % b is 0
printf("The value of a <= b is %d\n", (a <= b));
The value of a++ is 10
printf("The value of a > b is %d\n", (a > b));
The value of a-- is 11
printf("The value of a < b is %d\n", (a < b));
The value of ++a is 11
// Logical operators
The value of --a is 10
printf("\nFollowing are the logical operators in
The comparison operators in C are listed
C\n");
below.
printf("The value of this logical and operator
The value of a == b is 0
((a==b) "

The value of a != b is 1
"&& (a<b)) is:%d\n",

The value of a >= b is 1


((a == b) && (a < b)));

The value of a <= b is 0


printf("The value of this logical or operator
((a==b) " The value of a > b is 1

"|| (a<b)) is:%d\n", The value of a < b is 0

((a == b) || (a < b))); The logical operators in C are listed below.

printf("The value of this logical not operator " The value of this logical and operator ((a==b)
&& (a<b)) is:0
"(!(a==b)) is:%d\n",

The value of this logical or operator ((a==b) ||


(!(a == b)));
(a<b)) is:0
return 0;
The value of this logical not operator (!(a==b))
} is:1

Output: Summary

The C's arithmetic operators are listed here. • Operators are the foundation of any

Operator In C - Unit 5 40
programming language. We can define +(addition), -(subtraction), *(multiplication),
operators as symbols that help us to /(division), %(modulus).
perform specific mathematical and logical
• Logical Operators are used to combine
computations on operands. In other words,
two or more conditions/constraints or to
we can say that an operator operates the
complement the evaluation of the original
operands.
condition in consideration. The result of
• This operator used for numeric calculation. the operation of a logical operator is a
These are of either Unary arithmetic Boolean value either true or false.
operator, Binary arithmetic operator.
• The Bitwise operators are used to perform

• Where Unary arithmetic operator required bit-level operations on the operands. The

only one operand such as +,-, ++, --,!, operators are first converted to bit-level and

tiled. And these operators are addition, then the calculation is performed on the
operands. Mathematical operations such
subtraction, multiplication, division.
as addition, subtraction, multiplication, etc.
Binary arithmetic operator on other hand
can be performed at the bit level for faster
required two operand and its operators are
processing.

Operator In C - Unit 5 41
UNIT 6

Decision Making in C

Learning Objectives Introduction


At the end of this unit, you will
be able to:
if statement

Decision making structures require that the programmer specifies


 Discuss various conditional
statement in c one or more conditions to be evaluated or tested by the program,
along with a statement or statements to be executed if the condition
 Infer about switch statement is determined to be true, and optionally, other statements to be
executed if the condition is determined to be false.
 Define nested switch
statements
In an if statement, a boolean expression is followed by one or more
sentences.

Syntax

In the C programming language, an if statement has the following


syntax:

if(boolean_expression)

/* statement(s) will execute if the boolean expression is true */

The code block in the if statement will be executed if the boolean


expression returns true. If the boolean expression returns false, the
first block of code after the closing curly brace (the conclusion of the
if statement) will be executed.

All non-zero and non-null values are taken as true in the C


programming language, but zero or null values Output:
are taken as false values.
a is less than 20;

value of a is : 10

if...else statement

An optional else sentence that runs when the


boolean expression is false can be placed after
an if statement.

Syntax

In the C programming language, an if...else


Figure: Flow diagram statement has the following syntax:

Example:
if(boolean_expression)
#include <stdio.h>
{
int main ()
/* statement(s) will execute if the boolean
{
expression is true */
/* local variable definition */
}
int a = 110;
else
/* check the boolean condition using if
statement */ {

if( a < 220 )


/* statement(s) will execute if the boolean
{ expression is false */

/* if condition is true then print the following


}
*/
The if block of code is run if the boolean
printf("a is less than 20\n" );
statement evaluates to true; else, the else block
}
of code is executed.
printf("value of a is : %d\n", a);
All non-zero and non-null values are taken as
return 0; true in the C programming language, but zero or

} null values are taken as false values.

Decision Making in C - Unit 6 43


printf("a is not less than 20\n" );

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

return 0;

Output:

a is not less than 20;


Figure: Flow diagram.
value of a is : 100
Example:
The if...else if...else Statement
#include <stdio.h>
A single if...else if statement is particularly
int main () helpful for testing several conditions. It can be
followed by an optional else if...else statement.
{
There are a few things to bear in mind while
/* local variable definition */
employing if, otherwise, if, else statements:
int a = 100;
• An if must come after any other ifs and can
/* check the boolean condition */ have zero or one else's.

if( a < 20 ) • Any number of other ifs can follow an if,


but they must appear before the else.
{
• None of the remaining else if's or else's will
/* if condition is true then print the following be tried after an else if succeeds.
*/
Syntax
printf("a is less than 20\n" );
In the C programming language, an if...else
} if...else statement has the following syntax:

else if(boolean_expression 1)

{ {

/* if condition is false then print the following /* Executes when the boolean expression 1
*/ is true */

Decision Making in C - Unit 6 44


} /* if condition is true then print the following
*/
else if( boolean_expression 2)
printf("Value of a is 10\n" );
{
}
/* Executes when the boolean expression 2
is true */ else if( a == 20 )

{
}

/* if else if condition is true */


else if( boolean_expression 3)
printf("Value of a is 20\n" );
{
}
/* Executes when the boolean expression 3
is true */ else if( a == 30 )

} {

else /* if else if condition is true */

{ printf("Value of a is 30\n" );

}
/* executes when the none of the above
condition is true */ else

} {

Example: /* if none of the conditions is true */

#include <stdio.h> printf("None of the values is matching\n" );

int main () }

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

/* local variable definition */ return 0;

}
int a = 100;

The following is the outcome of compiling


/* check the boolean condition */
and running the aforementioned code:
if( a == 10 )
None of the values is matching
{
Exact value of a is: 100

Decision Making in C - Unit 6 45


Nested if statements /* check the boolean condition */

Using one if or else if statement inside another if( a == 100 )


if or else if statement is always acceptable in the
{
C programming language (s).
/* if condition is true then check the following
Syntax
*/
A nested if statement has the following syntax:
if( b == 200 )
if( boolean_expression 1)
{
{
/* if condition is true then print the following
/* Executes when the boolean expression 1 is */
true */
printf("Value of a is 100 and b is 200\n" );
if(boolean_expression 2)
}
{
}
/* Executes when the boolean expression 2 is
printf("Exact value of a is : %d\n", a );
true */
printf("Exact value of b is : %d\n", b );
}
return 0;
}
}
Similar to how you nested an if statement, you
can nest an else if...else statement. The following is the outcome of compiling
and running the aforementioned code:
Example
Value of a is 100 and b is 200
#include <stdio.h>
Exact value of a is : 100
int main ()
Exact value of b is : 200
{
Switch statement
/* local variable definition */
A switch statement enables the comparison
int a = 100;
of a variable's value to a list of possible values.
int b = 200; Each value is referred to as a case, and each
switch case checks the variable being turned on.

Decision Making in C - Unit 6 46


Syntax the switch, and it must be a constant or a
literal.
The following is the syntax for a switch
statement in the C computer language: • When the variable being switched on is
equal to a case, the statements following
switch(expression){
that case will execute until a break
case constant-expression : statement is reached.

statement(s); • When a break statement is reached, the


switch terminates, and the flow of control
break; /* optional */
jumps to the next line following the switch
case constant-expression : statement.

statement(s); • Not every case needs to contain a break.


If no break appears, the flow of control will
break; /* optional */
fall through to subsequent cases until a
/* you can have any number of case break is reached.
statements */
• A switch statement can have an optional
default : /* Optional */
default case, which must appear at the

statement(s); end of the switch. The default case can be


used for performing a task when none of
}
the cases is true. No break is needed in the

A switch statement must adhere to the default case.

following guidelines:

• The expression used in a switch statement


must have an integral or enumerated type,
or be of a class type in which the class has
a single conversion function to an integral
or enumerated type

• You can have any number of case


statements within a switch. Each case is
followed by the value to be compared to
and a colon.

• The constant-expression for a case must


be the same data type as the variable in
Figure: Flow diagram.

Decision Making in C - Unit 6 47


Example: printf("Your grade is %c\n", grade );

#include <stdio.h> return 0;

int main () }

{ The following is the outcome of compiling


and running the aforementioned code:
/* local variable definition */
Well done
char grade = 'B';
Your grade is B
switch(grade)
Nested switch statements
{
A switch could be included in the statement
case 'A' : chain of an outside switch. No conflicts will
develop even if the case constants of the inner
printf("Excellent!\n" );
and outer switches have similar values.
break;
Syntax
case 'B' :
A nested switch statement has the following
case 'C' : syntax:

printf("Well done Keep up\n" ); switch(ch1) {

case 'A':
break;

printf("This A is part of outer switch" );


case 'D' :
switch(ch2) {
printf("You passed\n" );
case 'A':
break;
printf("This A is part of inner switch" );
case 'F' :
break;
printf("Better try again\n" );
case 'B': /* case code */
break;
}
default :
break;
printf("Invalid grade\n" );
case 'B': /* case code */
}
}

Decision Making in C - Unit 6 48


Example The following is the outcome of compiling
and running the aforementioned code:
#include <stdio.h>
This is part of outer switch
int main ()
This is part of inner switch
{
Exact value of a is : 100
/* local variable definition */
Exact value of b is : 200
int a = 100;
Summary
int b = 200;
• Relational, equality, and logical expressions
switch(a) {
have the int value 0 or 1.

case 100:
• Automatic type conversions can occur

printf("This is part of outer switch\n", a ); when two expressions are compared that
the operands of a relational, equality, or
switch(b) { logical operator.

case 200: • An if statement provides a way of choosing


whether or not to execute a statement.
printf("This is part of inner switch\n", a );
• The else part of an if-else statement
}
associates with the nearest available if
} This resolves the "dangling else" problem.

printf("Exact value of a is : %d\n", a ); • The programmer often has to choose


between the use of a while or a far
printf("Exact value of b is : %d\n", b ); statement. In situations where clarity
dictates that both the control and the
return 0;
indexing be kept visible at the top of the
} loop, the for statement is the natural
choice.

Decision Making in C - Unit 6 49


UNIT 7

C Loops

Learning Objectives Introduction


At the end of this unit, you will
continue statement in C
be able to:

C Loop is used to execute the block of code several times


 Learn about while loop in C, for
loop in C and do...while loop in
according to the condition given in the loop. It means it executes the
C same code multiple times so it saves code and also helps to traverse
the elements of an array.
 Define the concepts of nested
loops in C There may be times when you need to execute a code block
repeatedly. A function's first statement is executed first, followed by
 Discuss about the break
its second and so on. Most of the time, statements are carried out
statement in C
in order. Programming languages' various control structures allow
for more complex execution paths. In the majority of programming
languages, a loop statement often takes the following form. We can
execute a statement or group of statements repeatedly by using a
loop statement.

while loop in C

We have learned from studying the for loop that the number of
iterations is known in advance, i.e., how many times the body of
the loop must be executed. While loops are employed when we are
unsure of the precise number of loop iterations in advance. Based on
the results of the test, the loop is stopped.

The initialization expression, test expression, and update


expression are the three statements that make up a loop, as we've
just mentioned. The arrangement of these three statements varies
between the three looping constructs—For, while, and do while—in
terms of syntax.
initialization expression; printf( "Hello India\n");

while (test_expression) // update expression

{ i++;

// statements }

update_expression; return 0;

} }

Output:

Hello India

Hello India

Hello India

Hello India

Hello India

for loop in C
With the use of a for loop, which is a repetition
control structure, we can create a loop that runs
a predetermined number of times. The loop
Figure: Flow Diagram.
permits us to carry out n stages simultaneously
Example: in a single line.

// C program to illustrate while loop Syntax:

#include <stdio.h> for (initialization expr; test expr; update expr)

int main() {

{ // body of the loop

// initialization expression // statements we want to execute

int i = 1; }

// test expression A for loop manages the loop by using a loop


variable. Set a value for the loop variable's initial
while (i < 6)
value before determining whether it exceeds or
{ falls short of the counter value. If the assertion

C Loops - Unit 7 51
is accurate, the loop's body is executed, and the Example:
loop variable is changed. Continue until the exit
condition is met. // C program to illustrate for loop

• Initialization Expression: The loop counter #include <stdio.h>


must be initialized to a certain value in this
int main()
expression. for instance, int i=1;

{
• Test Expression: We must verify the
condition in this expression. If the condition
int i=0;
is true, we will carry out the for loop's body
and move on to the update expression; for (i = 1; i <= 10; i++)
otherwise, we will stop. For instance: i <=
10; {

• Update Expression: This expression printf( "Hello India\n");

increases or decreases the loop variable by


}
a certain amount after the loop body has
run. for instance: i++; return 0;

Equivalent flow diagram for loop: }

Output:

Hello India

Hello India

Hello India

Hello India

Hello India

Hello India

Hello India

Hello India

Hello India

Figure: diagram for loop. Hello India

C Loops - Unit 7 52
do...while loop in C Example:

The execution of the loop is stopped in do // C program to illustrate do-while loop


while loops as well based on the results of the
#include <stdio.h>
test. While loops are entry controlled, do while
loops are exit controlled since the condition is int main()
verified at the end of the loop body. This is the
{
major distinction between do while loops and
while loops. int i = 2; // Initialization expression

Syntax: do

initialization expression; {

do // loop body

{ printf( "Hello India\n");

// statements // update expression

update_expression; i++;

}while (test_expression); } while (i < 1); // test expression

Note: Take note of the semicolon (";") at the return 0;


loop's end.
}

Output:

Hello India

In the program above, the test condition


(i1) evaluates to false. The loop's body will
only execute once, though, because the exit is
controlled.

nested loops in C

Loop nesting is supported in C. The C


language's nesting of loops feature enables the
looping of statements inside of other loops. Let's
look at a C nesting loop example.
Figure: Flow diagram do while.

C Loops - Unit 7 53
There is no constraint on the number of loops // outer loop statements.
that can be formed, therefore any number of
}
loops can be defined inside another loop. It is
possible to define the nesting level n times. Any Example to showcase functionality of nested for
type of loop can be defined within of another loop
loop; for instance, a "while" loop can be defined
inside of a "for" loop. #include <stdio.h>

int main()
Syntax of Nested loop
{
Outer_loop
int n;// variable declaration
{
printf("Enter the value of n :");
Inner_loop
// Displaying the n tables.
{
for(int i=1;i<=n;i++) // outer loop
// inner loop statements.
{
}
for(int j=1;j<=10;j++) // inner loop
// outer loop statements.
{
}
printf("%d\t",(i*j)); // printing the value.
The legitimate loops that can be used as
}
"for" loops, "while" loops, or "do-while" loops are
outer_loop and inner_loop. printf("\n");

Nested for loop }

Every form of loop that is defined inside the Explanation of the above code
"for" loop is referred to as a "nested for loop."
• First, the 'i' variable is initialized to 1 and
for (initialization; condition; update) then program control passes to the i<=n.

{ • The program control checks whether the


condition 'i<=n' is true or not.
for(initialization; condition; update)
• If the condition is true, then the program
{
control passes to the inner loop.
// inner loop statements.
• The inner loop will get executed until the
} condition is true.

C Loops - Unit 7 54
• After the execution of the inner loop, the {
control moves back to the update of the
int rows; // variable declaration
outer loop, i.e., i++.

int columns; // variable declaration


• After incrementing the value of the loop
counter, the condition is checked again, int k=1; // variable initialization
i.e., i<=n.
printf("Enter the number of rows :"); // input
• If the condition is true, then the inner loop the number of rows.
will be executed again.
scanf("%d",&rows);
• This process will continue until the
condition of the outer loop is true. printf("\nEnter the number of columns :"); //
input the number of columns.
Output:
scanf("%d",&columns);

int a[rows][columns]; //2d array declaration

int i=1;

while(i<=rows) // outer loop


Nested while loop

Every form of loop that is defined inside the {


"while" loop is referred to as a "nested while loop."
int j=1;
while(condition)
while(j<=columns) // inner loop
{
{
while(condition)
printf("%d\t",k); // printing the value of k.
{
k++; // increment counter
// inner loop statements.
j++;
}
}
// outer loop statements.
i++;
}

A nested while loop example printf("\n");

#include <stdio.h> }

int main() }

C Loops - Unit 7 55
Explanation of the above code. {

• We have created the 2d array, i.e., int do


a[rows][columns].
{
• The program initializes the 'i' variable by 1.
// inner loop statements.
• Now, control moves to the while loop, and
}while(condition);
this loop checks whether the condition is
true, then the program control moves to // outer loop statements.
the inner loop.
}while(condition);
• After the execution of the inner loop, the
control moves to the update of the outer Nested do..while loop illustration.
loop, i.e., i++.
#include <stdio.h>
• After incrementing the value of 'i', the
int main()
condition (i<=rows) is checked.
{
• If the condition is true, the control then
again moves to the inner loop. /*printing the pattern

• This process continues until the condition ********


of the outer loop is true.
********
Output:
********

******** */

int i=1;

do // outer loop

int j=1;

Nested do..while loop do // inner loop

Every form of loop that is defined inside the {


"do..while" loop is referred to as a "nested do..
printf("*");
while loop."
j++;
do

C Loops - Unit 7 56
}while(j<=8); 1. When a loop encounters the break
statement, the loop is instantly broken, and
printf("\n");
program control moves on to the statement

i++; that follows the loop.

}while(i<=4); 2. In the switch statement, it can be used to


end a case.
}
If you are using nested loops, which are loops
Output:
inside loops, the break statement will stop the
innermost loop from running and start the line of
code that follows the block.

Syntax

In C, a break statement has the following


syntax:

Explanation of the above code: break;

• First, we initialize the outer loop counter Flow diagram:


variable, i.e., 'i' by 1.

• As we know that the do..while loop executes


once without checking the condition, so the
inner loop is executed without checking the
condition in the outer loop.

• After the execution of the inner loop, the


control moves to the update of the i++.

• When the loop counter value is incremented,


the condition is checked. If the condition in
the outer loop is true, then the inner loop is
executed.

• This process will continue until the


condition in the outer loop is true.

break statement in C

There are two applications for the break


statement in the C programming language:

C Loops - Unit 7 57
Example value of a: 13

#include <stdio.h> value of a: 14

int main () value of a: 15

{ continue statement in C

/* local variable definition */ The continue statement and the break


statement both serve comparable purposes in
int a = 10;
the C programming language. However, instead

/* while loop execution */ of forcing termination, continue compels the


next iteration of the loop to start, skipping any
while( a < 20 ) code in between.

{ The continue statement causes the for loop's


conditional test and increment portions to run.
printf("value of a: %d\n", a);
The continue statement directs the program
a++; control to the while and do...while loops'
conditional tests.
if( a > 15)
Syntax
{
continue;
/* terminate the loop using break statement
*/ Flow diagram:

break;

return 0;

The following is the outcome of compiling


and running the aforementioned code:

value of a: 10

value of a: 11 Example:

value of a: 12 #include <stdio.h>

C Loops - Unit 7 58
int main () value of a: 18

{ value of a: 19

/* local variable definition */


Summary
int a = 10;
• The looping simplifies the complex
/* do loop execution */ problems into the easy ones. It enables
us to alter the flow of the program so that
do
instead of writing the same code again and
{ again, we can repeat the same code for a

if( a == 15) finite number of times. For example, if we


need to print the first 10 natural numbers
{
then, instead of using the printf statement
/* skip the iteration */ 10 times, we can print inside a loop which
runs up to 10 iterations.
a = a + 1;
• The while loop in c is to be used in the
continue;
scenario where we don't know the number
} of iterations in advance. The block of

printf("value of a: %d\n", a); statements is executed in the while loop


until the condition specified in the while
a++;
loop is satisfied. It is also called a pre-
}while( a < 20 ); tested loop.

return 0; • In do while loops also the loop execution is


terminated on the basis of test condition.
}
The main difference between do while
The following is the outcome of compiling loop and while loop is in do while loop the
and running the aforementioned code: condition is tested at the end of loop body,
value of a: 10 i.e do while loop is exit controlled whereas
the other two loops are entry controlled
value of a: 11
loops.
value of a: 12
• The for loop is used in the case where we
value of a: 13 need to execute some part of the code
until the given condition is satisfied. The
value of a: 14
for loop is also called as a per-tested loop.
value of a: 16 It is better to use for loop if the number of
iteration is known in advance.
value of a: 17

C Loops - Unit 7 59
UNIT 8

Functions

Learning Objectives Introduction


At the end of this unit, you will
Problem deconstruction is the key to solving problems effectively.
be able to:
Writing huge programmes requires the ability to take an issue and
 Define functions and functions divide it into discrete, manageable parts. This "top-down" approach
prototypes
of programming is implemented in C using the function construct.
 Discuss the return statement A program is composed of one or more files, each of which has a
main() function and zero or more other functions. The definition of a
 Infer how to declare function
from the compiler's viewpoint function is an independent object that cannot be nested. The main()
function initiates program execution and may invoke other procedures,
 Explain the storage classes
including library functions like printf() and sqrt (). Program variables
and recursion
are used for functions to operate, and scope restrictions govern which
of these variables are available where in a function.

Function Definition

The C code that specifies what a function does is referred to as


the function definition. It should not be confused with a function's
declaration. The following is the general form of a function definition:

type function_name( parameter list) { declarations statements }

The function definition's header is made up of everything before


the first brace, and its body is made up of everything in between. The
declarations are listed in the parameter list, separated by commas. A
function definition illustration is

int factorial (int n)


{ any arguments. This phrase

int i, product = 1; wrt_adresses()

for (i = 2; i <= n; ++i) initiates the call to the function. For instance,
we can write to call the method three times.
product *= i;
for (i = 0; i < 3; ++i) wrt_address 0 ;
return product;
In a function definition, the type of the function
}
is listed first. If there is no value returned, the type
The first int instructs the compiler to convert is void. If the type is something other than void,
the function's return value to an int if necessary. the function will transform the value it returns,
The declaration int n is included in the argument if necessary, to this type. A list of parameter
list. This informs the compiler that the function declarations in parentheses is placed after the
only accepts a single int parameter. The function function's name. When the function is called,
is called when an expression like factorial (7) is the parameters serve as placeholders for the
used. The result is that the function definition's values that are supplied. In order to emphasise
code is executed, using the value 7 for n. that these arguments are placeholders, they
Functions thus serve as effective abbreviation are occasionally referred to as the formal
systems. Another illustration of a function parameters of the function. Declarations may
definition is as follows: also be found in the function's body, which is a
block or compound statement. These are some
Void wrt_address(void) illustrations of function definitions:

{ void nothing(void) { }

Printf(“%s\n%s\n%s\n%s\n%s\n\n” double twice(double x)

“ ************************** {

“ ** SANTA CLAUS *” return (2.0 * x);

“ ** NORTH POLE *”” }

“ ** EARTH *”” int all_add(int a, int b)

“ **************************) {

) int c;

The first void indicates to the compiler that return (a + b + c);


the function returns nothing, while the second
void indicates that the function does not accept }

Functions - Unit 8 61
A function's default type is int if the function It doesn't matter what order the parameters
type is not specified in the definition. The final are declared in. A pair of empty parenthesis
function definition, for instance, might be is used if there are no parameters. Both this
provided by conventional syntax and the more recent syntax
are supported by ANSI C compilers. As a result,
all_add(int a, int b) {
an ANSI C compiler can still build conventional
To clearly state the function type is acceptable code.
programming practice, nevertheless.
Writing programmes as collections of
A variable is said to be "local" to a function if it numerous functions is advantageous for a
is defined in the function's body. Other variables number of reasons. Writing a precise tiny
outside of the function can be defined. They are function that only performs one task is easier.
referred to as "global" variables. One of them is The authoring and debugging processes are
simplified. Also, such a grammar is simpler to
#include <stdio.h>
update or maintain. Just changing the necessary
int a = 33; /* a is external and initialized to 33 set of functions and assuming the rest of the
*/ code will function properly is possible. Little
functions are also frequently highly readable
int main(void)
and self-documenting. A smart programming

{ heuristic is to write each function's code so that


it can fit on a single page.
int b = 77;
The return Statement
printf("a = %d\n", a);
An expression might or might not be present
printf("b = %d\n", b);
in the return statement.

return 0;
return_statement ::= return; return expression;
}
Many instances are
In traditional C, the function definition has a
return;
different syntax. The variables in the parameter
list are declared immediately following the return ++a;
parameter list itself and just before the first
brace. One of them is return (a ,/, b);

void f(a, b, c, x, y) Although it's optional, parentheses can be


used to encapsulate the returned expression.
int a, b, c;
When a return statement is discovered, the
double x, y;
function's execution is completed, and control is

{ sent back to the calling environment. The caller

Functions - Unit 8 62
environment additionally receives the value of getchar(); /* get a char, but do nothing with it
any expressions provided in the return statement. */
Also, based on the function's specification, this
c = getchar 0 ; /* c will be processed */
value will be modified as necessary to reflect the
function's type. ........

float f(char a, char b, char c) }

{ Function Prototypes
int i; Functions should be declared before use. The
function prototype, a new syntax for function
.........
definition, is provided by ANSI C. A function
return i; /*value returned will be converted to prototype tells the compiler how many and what
a float*/ kind of inputs to pass to the function, as well as
what kind of 0 result the function should return.
}
One of them is

A function may contain zero or more return


double sqrt(double);
statements. When the closing brace of the body
is encountered, if there is no return statement, This instructs the compiler that the sqrt()
control is returned to the caller environment. method accepts a single double-type argument
"Falling off the end" is the term used for this. The and returns a double. An abstract representation
use of two return statements is demonstrated by of a function prototype is
the function definition that follows:
type function_name ( parameter type list) ;
double absolute_value(double x)
A comma-separated list of kinds normally
{ makes up the parameter type list. Identifiers are
not required and have no impact on the prototype.
if (x >= 0.0)
As an illustration, the function prototype

return x;
void f(char c, int i); is equivalent to

else void f(char, int);

return -x; Identifiers like c and I that exist in parameter


type lists for function prototypes are not used by
} the compiler. They provide documentation for
the programmer and other code readers. The
A function may return a value, but a program
keyword void is utilised whenever a function
is not required to use it.
does not take any arguments. The keyword
while ( ..... ) { void is also used if the function has no output.

Functions - Unit 8 63
When a function takes more than one argument, About the function's parameter list, nothing is
the ellipses (...) are utilised. Have a look at the assumed. Now imagine that the definition of the
printf() function prototype in the standard header following function comes first:
file stdio.h, for instance.
int f(x) /* traditional C style */
The compiler is able to undertake a more
thorough code inspection thanks to function double x;

prototypes. Moreover, whenever possible, correct


{
coercion is used to force values supplied to
functions. For instance, if the function prototype The compiler receives both a declaration and
for sqrt() has been defined, the function call a definition from this. However, the parameter
sqrt(4) will result in the desired outcome. Because list is not presumed again. It is the obligation of
the compiler is aware that sqrt() needs a double, the programmer to only send a single double-
the int value 4 will be upgraded to a double and
type argument. Given that 1 is of type I nt, not
the appropriate value will be returned.
double, it is assumed that a function call like f (1)

Argument type lists are not supported in will fail. Now imagine that we use an ANSI C style

function declarations in traditional C. For declaration instead:


instance, the sqrt() function declaration is as
int f(double x) /* ANSI C style */
follows:
{
double sqrt(); /* traditional C style */

The argument list is also now known to the


Function prototypes are preferable even if
compiler. A function call like f(l) should perform
ANSI C compilers will support this coding style.
The function call sqrt (4) won't produce the right correctly in this situation. A double will be created

result with this declaration. when an int is supplied as an argument.

Function Declarations from the A function declaration's special case is a


Compiler's Viewpoint function prototype. Giving either the function
definition (ANSI C style) or the function prototype,
Function declarations are produced in a
or perhaps both, before a function is utilised,
variety of methods for the compiler, including
is a good programming practice. The fact that
function definition, function invocation, explicit
standard header files contain function prototypes
function declarations, and function prototypes.
The compiler assumes a default declaration of is a key justification for their inclusion.

the form if a function call, such as f(x), occurs


Storage Classes
before any of its declarations, definitions, or
prototypes. Storage The features of a variable or function
are described using classes. We can trace the
Int f();
existence of a particular variable during the

Functions - Unit 8 64
lifetime of a program thanks to these properties, that is initialised with a valid value where
which mainly include scope, visibility, and life- it is defined in order to be used elsewhere.
time. It is reachable from any block or function.
A normal global variable can also be
The four storage classes used by the C
made extern by prefixing its declaration
programming language are:
or definition with the term "extern" in any
Storage classes in C function or block. This simply means that
Storage we are only using/accessing the global
Storage Initial value Scope LIfe

Within End of variable and not initialising a new variable.


auto stack Garbage
block block
global
Using extern variables enables them to be
Data Till end of
extern Zero Multiple
segment program accessed from two separate files that are
Data Within Till end of
static
segment
Zero
block program
a part of a huge application, which is their
CPU Within End of
register
Register
Garbage
block block
primary use.

3. static: Static variables, which are frequently


used while building C programmes, can be
1. auto: This is the default storage class for
declared using this storage type. As soon
all variables specified inside a function or
as they leave their scope, static variables
a block. As a result, when developing C
continue to hold their value. Static
language applications, the keyword auto is
variables therefore maintain the value of
rarely utilised. Only the block or function in
their most recent use within their scope.
which they were declared can access auto
So, we can conclude that they receive a
variables (which defines their scope). In
single initialization and remain valid till the
the parent block or function where the auto
program is finished. Because they are not
variable was declared, they can, of course,
re-declared, no new memory is allocated
be accessed within nested blocks. But,
as a result. The function to which they
using the idea of pointers presented here,
were specified is the only area of their
the variables can also be accessed outside
application. Anything in the program can
of their intended scope by referring to the
access global static variables. They are
particular memory location where they are
given the value 0 by the compiler by default.
stored. They always have a garbage value
when they are declared. 4. register: Register variables with the same
capability as auto variables are declared by
2. extern: The phrase "external storage class"
this storage class. The main difference is
simply means that the definition of the
that the compiler only tries to store these
variable is found outside of the block in
variables in the microprocessor's register if
which it is used. In essence, the value can
a free registration is available. As a result,
be changed or rewritten in another block
using register variables during program
after being assigned to it in the first block.
execution is substantially quicker than
An extern variable is just a global variable
using variables that are kept in memory. In

Functions - Unit 8 65
the absence of a free registration, they are // printing the auto variable 'a'
just stored in memory. The register keyword
printf("Value of the variable 'a'"
is often used to declare a few variables
that a program will utilise repeatedly, which
" declared as auto: %d\n",
reduces the amount of time the program
will take to run. The fact that we cannot a);
use pointers to get the address of a register
printf("--------------------------------");
variable is both significant and intriguing in
this context.
}

The following syntax must be used to specify


void registerStorageClass()
a variable's storage class:
{
Syntax:
printf("\nDemonstrating register class\n\n");
storage_class var_data_type var_name;
// declaring a register variable
The syntax for functions is the same as that
for variables above. For more information, check register char b = 'G';
at the following C example:
// printing the register variable 'b'
// A C program to demonstrate different
storage printf("Value of the variable 'b'"

// classes " declared as register: %d\n",

#include <stdio.h> b);

// declaring the variable which is to be made printf("--------------------------------");


extern
}
// an initial value can also be initialized to x
void externStorageClass()
int x;
{
void autoStorageClass()
printf("\nDemonstrating extern class\
{ n\n");

printf("\nDemonstrating auto class\n\n"); // telling the compiler that the variable

// declaring an auto variable (simply // x is an extern variable and has been

// writing "int a=32;" works as well) // defined elsewhere (above the main

auto int a = 32; // function)

Functions - Unit 8 66
extern int x; " as in the case of variable 'p'\n");

// printing the extern variables 'x' printf("\nLoop started:\n");

printf("Value of the variable 'x'" for (i = 1; i < 5; i++) {

" declared as extern: %d\n", // Declaring the static variable 'y'

x); static int y = 5;

// value of extern variable x modified // Declare a non-static variable 'p'

x= 2; int p = 10;

// printing the modified values of // Incrementing the value of y and p by 1

// extern variables 'x' y++;

printf("Modified value of the variable 'x'" p++;

" declared as extern: %d\n", // printing value of y at each iteration

x); printf("\nThe value of 'y', "

printf("--------------------------------"); "declared as static, in %d "

} "iteration is %d\n",

void staticStorageClass() y, i);

{ // printing value of p at each iteration

int i = 0; printf("The value of non-static variable 'p', "

printf("\nDemonstrating static class\ "in %d iteration is %d\n",


n\n");
p, i);
// using a static variable 'y'
}
printf("Declaring 'y' as static inside the loop.\n"
printf("\nLoop ended:\n");
"But this declaration will occur only"
printf("--------------------------------");
" once as 'y' is static.\n"
}
"If not, then every time the value of 'y'"
int main()
"will be the declared value 5"

Functions - Unit 8 67
{ Declaring 'y' as static inside the loop.

printf("A program to demonstrate" But this declaration will occur only once as 'y'
is static.
" Storage Classes in C\n\n");
If not, then every time the value of 'y' will be
// To demonstrate auto Storage Class
the declared value 5 as in the case of variable 'p'

autoStorageClass();
Loop started:

// To demonstrate register Storage Class


The value of 'y', declared as static, in 6

registerStorageClass(); iteration is 1

// To demonstrate extern Storage Class The value of non-static variable 'p', in 11


iteration is 1
externStorageClass();
The value of 'y', declared as static, in 7
// To demonstrate static Storage Class iteration is 2

staticStorageClass(); The value of non-static variable 'p', in 11


iteration is 2
// exiting
The value of 'y', declared as static, in 8
printf("\n\nStorage Classes
iteration is 3
demonstrated");
The value of non-static variable 'p', in 11
return 0;
iteration is 3
}
The value of 'y', declared as static, in 9
Output: iteration is 4

...ster: 71 The value of non-static variable 'p', in 11


iteration is 4
--------------------------------
Loop ended:
Demonstrating extern class
--------------------------------
Value of the variable 'x' declared as extern: 0
Storage Classes demonstrated
Modified value of the variable 'x' declared as
extern: 2 Recursion

-------------------------------- Recursion happens when a function calls


a copy of itself to work on a smaller issue. A
Demonstrating static class recursive function is any function that calls

Functions - Unit 8 68
itself, and recursive calls are calls performed int fact(int n)
by recursive functions. Recursion involves a
{
large number of recursive calls. It is essential
to enforce a recursion termination condition as if (n==0)
a result. Recursive code is more cryptic than
{
iterative code, although being shorter.
return 0;
Recursion cannot be used for every problem,
but it is more beneficial for jobs that can be }
broken down into related subtasks. Recursion
else if ( n == 1)
can be used to solve sorting, searching, and
traversal issues, for instance. {

As function calls always incur cost, iterative return 1;


solutions are typically more efficient than
recursive ones. Each issue that may be resolved }

recursively also lends itself to iterative resolution. else


Yet, some issues, like the Tower of Hanoi, the
Fibonacci sequence, factorial finding, etc., are {
better handled via recursion.
return n*fact(n-1);

In the example that follows, recursion is used }


to get a number's factorial.
}
#include <stdio.h>
Output:
int fact (int);

int main()

{ The following diagram helps us understand


the recursive method call in the program we just
int n,f;
looked at:
printf("Enter the number whose factorial you
want to calculate?");

scanf("%d",&n);

f = fact(n);

printf("factorial = %d",f);

} Figure: Recursion.

Functions - Unit 8 69
Recursive Function int fibonacci(int);

Recursive functions carry out tasks by breaking void main ()


them down into smaller ones. The function has a
{
defined termination condition, which is met by a
certain subtask. The recursion ends at this point, int n,f;
and the function returns the ultimate outcome.
printf("Enter the value of n?");
The base case is the circumstance in which
scanf("%d",&n);
the function does not recur; in contrast, the
recursive case is the circumstance in which the f = fibonacci(n);
function repeatedly invokes itself to carry out
printf("%d",f);
a subtask. It is possible to write all recursive
functions in this style. }

The following pseudocode can be used to int fibonacci (int n)


write any recursive function.
{
if (test_for_base)
if (n==0)
{
{
return some_value;
return 0;
}
}
else if (test_for_another_base)
else if (n == 1)
{
{
return some_another_value;
return 1;
}
}
else
else
{
{
// Statements;
return fibonacci(n-1)+fibonacci(n-2);
recursive call;
}
}
}
Example of recursion in C

Here is an illustration of how to determine the Output:

nth term in the Fibonacci series.

#include<stdio.h>

Functions - Unit 8 70
Memory allocation of Recursive method return 0; // terminating condition

That method is duplicated in memory with else


each recursive call. The copy is erased from
{
memory after the procedure returns some data.
A distinct stack is kept for each recursive call printf("%d",n);
since all variables and other items defined inside
functions are saved in the stack. The stack is return display(n-1); // recursive call
deleted after the associated function returns its
}
value. Resolving and tracking the values at each
recursive call requires a great deal of complexity }
in recursion. As a result, we must keep the stack
up to date and monitor the values of the variables Explanation:
it contains.
With n set to 4, let's examine this recursive
To comprehend how recursive functions function. First, all stacks are maintained active
allocate memory, let's look at the example below. and show the appropriate value of n until n =
0. Each stack is destroyed one at a time upon
int display (int n) attaining the termination condition by returning
0 to the caller stack. Consider the illustration
{
below for further information on the recursive
if(n == 0) functions' stack traces.

Functions - Unit 8 71
Summary tells the compiler the number and type of
arguments that are to be passed to the
• In C, the function construct is used to function and the type 0 the value that is to
implement this "top-down" method of
be returned by the function.
programming. A program consists of one
or more files, with each file containing zero • Storage Classes are used to describe the
or more functions, one of them being a features of a variable/function. These
main() function. Functions are defined as features basically include the scope,
individual objects that cannot be nested. visibility and life-time which help us to
Program execution begins with main(), trace the existence of a particular variable
which can call other functions, including during the runtime of a program.
library functions such as printf() and sqrt().
• Recursion is the process which comes into
• Functions operate with program variables, existence when a function calls a copy
and which of these variables is available of itself to work on a smaller problem.
at a particular place in a function is Any function which calls itself is called
determined by scope rules. recursive function, and such function
calls are called recursive calls. Recursion
• Functions should be declared before
involves several numbers of recursive
they are used. ANSI C provides for a new
function declaration syntax called the calls. However, it is important to impose a

function prototype. A function prototype termination condition of recursion.

Functions - Unit 8 72
UNIT 9

Structures and Unions

Learning Objectives Introduction


At the end of this unit, you will
C is a language that is simple to expand. It can be improved by
be able to:
adding functions that are kept in libraries and macros that are kept in
functions and functions prototypes header files. It can also be expanded by specifying data types that are
constructed from the fundamental types. As an example, the array
 Define the concept of
Structures type is a derived type that is used to represent homogeneous data. On
the other hand, the structural type is used to represent heterogeneous
 Discuss how to use structures
data. A structure's members are its individual parts, and they each
with functions
have a distinct name. Because the parts of a structure could be of
 Describe about unions various types, a programmer might create data aggregates that are
suitable for a particular application.

Structures

A group of member elements and the accompanying data types


make up a structure in the C programming language. As a result, the
definition of a variable of a structural type is the name of a group of
one or more members, who may or may not be of the same data type.
In programming, a structural data type is referred to as a record data
type, and its components are called fields.

Declaring and Accessing Structure Data

Like with any other data type, we must be able to declare variables
of that data type. Particularly for structures, we must specify the
names and types of all the structure's fields. As a result, we must
define variables of that type and specify the quantity and type of fields
in the form of a template in order to construct a structure.
We provide the following example: a program printf(“Temp in degree F =%3. If\n”,tenp.
that maintains temperatures in both fahrenheit ftemp);”
and celsius. The variable temp, which will be
used to maintain the same temperatures in both printf(“Temp in degree F =%3. If\n”,tenp.

celsius and fahrenheit, requires two fields that ftemp);”


are both integers.
}
The temperature of one field will be denoted by
/* This converts degree F to degree c*/
the letters "ftemp" for fahrenheit and "ctemp" for
celsius. The program, which is shown in Figure double f_to_c(doublef)
(Code for simple structure program), reads a
temperature from the temp variable's ftemp field, {
converts it to celsius using the f to c() function,
Return((f -32.0)*5.0/9.0);
and then stores the result in the ctemp field.
}
/* File: fctemp.c
Looking at this program, we can observe that
Program read temperature is Fahrenheit,
the declaration statement for the variable temp's
converts to Celsius, and maintain the equivalen
structure type is as follows:
values in a variable of structure type*/

struct trecd {
#include <stdio.h>

float ftemp;
Main()

float ctemp;
{ struct trecd{

} temp;
float ftemp;

floatctemp; This phrase starts with the word "struct," then


goes on to describe the structure's template
} temp; before ending with the variable name. In our
example, a tag (or name), trecd, identifies
double f_to_c(double f)
the template and is followed by a set of field
char c; declarations that are wrapped in brackets. The
tag is optional. Without having to once more
printf(“***Temprature – Degree F and C***\
precisely explain the fields, the tag can be used
n\n”);
to refer to this structural template within its
printf(“Enter temperature in degree F : ”) scope. The bracketed list specifies the type and
identification of each field in the structure. Our
scanf(“%f”,&temp.ftemp); example shows that this structure has two fields,
ftemp and ctemp, both of type float.
temp.ctemp = f_to_c(temp.ftemp);

Structures and Unions - Unit 9 74


The memory cells designated for the variable • Sample Session:***Temperatures -
temp are displayed in Figure (Structure variable Degrees F and C***
temp in memory).
• ***Temperatures - Degrees F and C***

• Enter temperature in degrees F : 78

• Temp in degrees F = 78.0


Figure: Structure variable temp in memory.
Temp is degrees C = 25.6
The field and ctemp are the names of two
As we've already mentioned, a structural
float cells that have been assigned. The variable
variable's members can be of several sorts. For
name temp refers to the full block of memory.
instance:
Structure declarations otherwise have the same
scope as any other variable declaration, such as struct {
an int declaration, and are treated the same way.
char name[26];
The variable name (in this case, temp) is
qualified with the "dot" operator (.) and the field int id_number;
name to access the data in a structure:
} student;

which generates the structure variable student


with the two fields name, a character string,
In general, the syntax for accessing a member and id, an integer. There is enough contiguous
of a structure is: memory allocated to the variable student to
store both fields. To find out how much storage a
_identifier>.<member_identifier>
structure has been given, use the sizeof operator.
The same way that other variables are used (Be careful that the overall size of a structure
in programmes, members of structural variables variable may not be the same as the sum of the
can also be used. The float cell's address, temp. sizes for the fields due to restrictions affecting
ftemp, is provided as a parameter to scanf() in memory alignment that may vary from computer
the aforementioned procedure main() as &temp. to computer.
ftemp. Since the dot operator takes precedence
For instance, the start of a memory allocation
over the address operator in this case, parenthesis
for an integer could need to be at a machine
are not required. The argument will be preserved
word boundary, such an even byte address. Due
in the temp.ftemp cell, which will also save the
to these alignment requirements, the size of a
numerical value obtained by scanf(). The rest of
structural variable may be slightly bigger than the
the program is straightforward. We assigned the
sum of the field sizes.
double value that was produced by the function
f to c to the variable temp.ctemp and printed the The identifiers for the field names are specific
results on it. to variables of that structure type. Different

Structures and Unions - Unit 9 75


structure types can have fields specified with independent storage cells in this instance since
the same identifier, but these fields are separate there are two separate instances of the template
cells that can only be accessed by using the that are allocated. We have also defined a part
correct structure variable name followed by the variable, whose template contains the name
field name. Moreover, only the field names that of the id no field. However part.id_no can also
are listed in the structure template can qualify a access this other storage location. Nevertheless,
variable name. it is NOT allowed to refer to the person's cost
field (person.cost) or the _day (part.b_day)
A field name cannot be used alone; it
when using these declarations. Similar to this,
always needs to be followed by the name of
referencing f_name or price is prohibited in the
an appropriate structure variable. Consider the
absence of a variable name of the proper type.
following structural variable declarations:
Here are a few legitimate uses of structures:

struct {
part.id_no = 99;

char f_name[10];
part.cost = .2239;

char m_inits[3];
if (strcmp(person.f_name, "Helen") == 0)

char l_name[20];
printf("Last name is %s\n", person.l_name);

int id_no;
printf("This is the cost %d\n",part.cost);

int b_month;
part.price = part.cost * 2.0;

int b_day;
As long as the variables are of the same

int b_year; structure type, the only permissible operations


that can be performed on a structure variable are
} person, manager; accessing its members, copying, or assigning it
as a unit, for example:
struct {
manager = person;
int id_no;
Using Structure Tags
float cost;
In order to declare a structure variable, you
float price;
must first describe the structure's template and
} part; then declare variables of that structure type.
These two actions could alternatively be carried
In this case, the two variables person and out in a program as independent statements. That
manager are structures with seven fields, some is, simply define a structure template with a tag,
of which are numbers and others of which are but without declaring any variables. Afterwards,
strings. Person.id_no and Manager.id_no are declare variables for the structure type that the

Structures and Unions - Unit 9 76


tag indicated. Say, for illustration, the following: char name[30];

struct stdtype { char class_id[3];

char name[26]; int test[3];

int id_number; int project;

}; int grade;

provides a template with the tag "stdtype" for a } student;


particular structure type. (Note the semicolon for
struct stu_rec ee_stu, me_stu;
the declaration that follows the statement.) As
no variables are declared in such a declaration, struct date today, birth_day;
RAM is NOT allocated; instead, a template for
variables to be declared later is defined. We may The key benefit of separating the definition of

then declare stdtype structure variables like: the template from the declaration of variables

within the scope of the tag declaration. is that the template only needs to be declared
once and can then be used to declare variables
struct stdtype x, y, z; in several locations. When we pass structures to
function in the paragraphs below, we will realise
The three variables x, y, and z, all of which are
how useful this is.
of type structure stdtype and so fit the earlier
stated template, are allotted memory by this Hence, a structure declaration typically
declaration. Here are some more instances of includes the form shown below:
structure tags and variable declarations:
item struct [<tag_identifier>] {
/* named structure template, no variables
item struct [<tag_identifier>] {
declared */

<type_specifier> <identifier>;
struct date {
<type_specifier> <identifier>;
int month;
} [<identifier>[, <identifier>
int day;
where <tag identifiers> and the variable are both
int year;
optional. Further variables of the structure type
}; may be declared after the definition of a template
by:
/* named structure template and a variable
declared */ <tag_identifier> <identifier>[, <identifier>

struct stu_rec { Any legal C type, including scalar data types


(int, float, etc.), arrays, and structures, may be

Structures and Unions - Unit 9 77


used for the structure's fields. Since nested It is common to refer to both structure tags and
structure types can also be defined, it follows structure type variables as structures. As a result,
that: we may argue that the variable today is a structure
and that date is a structure. Usually, the context
struct inventory {
makes it clear if a structure tag or a variable of a

int item_no; structure type is intended. Nonetheless, we shall


refer to the templates themselves—i.e. tags—as
float cost; "structures" for the most part, and we will declare
that certain variables have a structure type. So,
float price;
the term "date" refers to a structure, and the term
struct date buy_date; "today" refers to a variable of the structure type,
namely the type "struct date."
};
Structures can be initialised in declarations
struct car_type{ just like other data types by stating constant
values for each member of the structure inside
struct inventory part;
of brackets. Similar to an array, the initializers for
struct date ship_date; structure members are separated by commas.
A struct inventory item might be declared as
int shipment;
follows:

} car;
struct inventory part = { 123, 10.00, 13.50 };

Here, the ship date field of the car type structure


which sets member's part no to 123, cost to 10.00,
is a date structure unto itself, and the part field is
and price to 13.50 dollars. Another illustration of
an inventory structure containing item no, cost,
a label item declaration is:
etc. fields, as well as another date structure
inside (from above). The members of nested struct name {
structures can be accessed using dot operators,
char f_name[10];
which should be used sequentially from left to
right (the grouping for the dot operator is from char m_inits[3];
left to right). Thus:
char l_name[20];
car.ship_date.month = 5; /* Lvalue is (car.
ship_date).month */ };

car.part.buy_date.month = 12; struct address {

The month field of the variable car's ship date char street[30];
field and the month field of the variable car's
char city[15];
buy_date field, respectively, are the subjects of
these assignments. char state[15];

Structures and Unions - Unit 9 78


int zip}; struct inventory read_part(void);

}; void print_part(struct inventort part);

struct label { main( )

struct name name; { struct inventory item;

struct address address; printf(“***Part Inventory Data***\n\n”);

}; item = read_part( )

struct label person = { {"Jones", "John", "Paul"}, };

{"23 Dole Street", "Honolulu", "Hawaii", 96822} {


};
printf(“Part no. =%d, Cost = %5.2f, Reatil price
Each of the two parts of the structure, label =%5.2f\n, part.part_no, part.cost, part.price);
is a structure. Name, the first member, has three
struct inventory read_part(void)
members, and address, the second member, has
four. Each member structure's initialization is { int n;
properly nested.
float x;
Using Structures with Functions
struct inventory part;
Like scalar variables, structure variables can
be supplied as arguments and returned from printf(“Part Number: ”)
functions. Let's look at an illustration that reads
scanf(“%d”, &x);
and publishes a part's data record. The part
number, cost, and retail price are included in part.part_no = n;
the record. Figure displays the code to read and
output a single part structure (Code for reading printf(“Cost: ”);
and printing a single part)
scanf(“%f”, &x);
#include <stdio.h>
part.cost = x;
Struct inventory{
printf(“Price: ”);
int part_no;
scanf(“%f”, &x);
float cost;
part.price = x;
float price;
return part;
};
}

Structures and Unions - Unit 9 79


• You'll see that we've declared the inventory accessible with the dot operator, receives each
structure template at the top of the source data item as it is read and places it there. After
file. The scope of an external declaration is being returned to main(), the value of part is
the whole file that follows the declaration. subsequently allocated to the variable item. The
As this structural tag is used by every return expression's value is transferred back to
function in the file, every function must be the calling function, just like it would for a scalar
able to see the template. In order to read data type. This is a structure, thus every field
data into a structure and return it to be within the structure is replicated. This isn't too
assigned to the variable item, the driver bad for our inventory structure since it only uses
executes read part(). Then, it executes print two floats and one integer. More values would
part() with the argument item, printing each need to be transferred if the structure were
field's value as it is called. The program is substantially larger, possibly containing nested
simple to follow. Below is an illustration of structures and arrays.
a session:***Part Inventory Data***
The call to print part has the same effect ().
• Part Number: 2341 The function in this instance is given a structure
for an inventory. As you may remember, in
• Cost: 12.5 C, the value of each argument expression is
transferred from the calling function into the cell
• Price: 15
corresponding to the parameter of the called
• Part no. = 2341, Cost = 15.00 function. Once more, this may not be the most
effective method of passing data to functions for
The consistent use of tags and functions is huge structures. We see a solution to this issue
facilitated by external declarations of structure in the next section.
prototypes and templates. As a rule, we shall
externally declare structure templates, typically Initialization of Structures
at the top of the source file. External structure
Members of structures cannot be initialized
tag declarations may occasionally be contained
by declaration. The compilation of the following
in a separate header file that is subsequently
C program, for instance, fails.
included in the source file using the include
directive. struct Point

We can see from this example that utilising {


structures with functions is the same as using
int x = 0; // COMPILER ERROR: cannot initialize
any scalar data type, such as int. But let's think
members here
about what actually occurs when the application
runs. Memory is allocated for all of the function int y = 0; // COMPILER ERROR: cannot initialize
read_part(local )'s variables, including the struct members here
inventory variable part, when the function is
invoked. The appropriate field of the component, };

Structures and Unions - Unit 9 80


Simple lack of memory allocation when Let's use an example to better grasp this.
a datatype is declared is the cause of the
struct abc
aforementioned error. Only when variables are
created is memory allocated. {

Curly braces, or "{}" can be used to initialize int a;


structure members. The initialization that
char b;
follows, for instance, is acceptable.
}
struct Point
The user-defined structure in the
{
aforementioned code has two members, namely
"a" of type int and "b" of type character. The
int x, y;
addresses of "a" and "b" are different, as we
}; discovered when we checked them. As a result,
we draw the conclusion that the structure's
int main() members do not share the same memory
address.
{
After defining the union, we found that its
// A valid initialization. member x gets value
definition is essentially the same as that of
0 and y
a structure, with the exception that the union

// gets value 1. The order of declaration is keyword is used to specify the union data type
and the struct keyword to specify a structure.
followed.
The data elements "a" and "b" that make up
struct Point p1 = {0, 1}; the union are identical when we examined the
addresses of the two variables. It suggests that
} each individual in the union has access to the
same region of memory.
Unions
Deciding the size of the union
A user-defined data type called a union is a
grouping of various variables of various data The largest member of the union determines
types stored in the same memory address. The the size of the union as a whole.
union can also be thought of as having numerous
members, but at any given time, only one of those Let's use an illustration to clarify.
members can hold a value.
union abc{
The user-defined data type union shares
int a;
the same memory address with structures, in
contrast. char b;

Structures and Unions - Unit 9 81


float c; They initially chose to arrange the records in
the manner depicted below:
double d;
struct store
};
{
int main()
double price;
{
char *title;
printf("Size of union abc is %d", sizeof(union
abc)); char *author;

return 0; int number_pages;

} int color;

As is common knowledge, an int is 4 bytes, a int size;

char is 1 byte, a float is 4 bytes, and a double is 8


char *design;
bytes in size. A total of 8 bytes will be allocated
in the RAM because the double variable uses the };
most memory of the four variables. As a result, 8
All the products that the business owner
bytes would be the output of the aforementioned
wants to store are included in the structure
program.
above. The aforementioned structure is entirely
Why do we need C unions? functional, however only the price is shared by
both goods, while the rest are separate. Books
To comprehend the necessity of C unions, have attributes like price, *title, *author, and
consider one illustration. Consider a shop that number_pages, whereas shirts have properties
sells two things: like color, size, and *design.

Books Let's see how we can get to the structure's


members.
Shirts
int main()
Shop owners desire to keep a record of the two
items described above as well as the pertinent {
data. For instance, shirts feature colour, design,
struct store book;
size, and price whereas books have title, author,
number of pages, and price. In both items, the book.title = "C programming";
'price' property is present. How would the store
owner store the records after deciding to store book.author = "Paulo Cohelo";

the properties?
book.number_pages = 190;

Structures and Unions - Unit 9 82


book.price = 205; } shirt;

printf("Size is : %ld bytes", sizeof(book)); }item;

return 0; };

} int main()

We have established a variable of type store {


in the code above. Title, Author, Number_Pages,
and Price variables have values assigned to struct store s;
them, however the book variable lacks attributes
s.item.book.title = "C programming";
like size, colour, and design. Hence, it wastes
memory. The aforementioned structure would
s.item.book.author = "John";
be 44 bytes in size.
s.item.book.number_pages = 189;
Unions allow us to save a lot of space.
printf("Size is %ld", sizeof(s));
#include <stdio.h>
return 0;
struct store
}
{

We have established a variable of type store


double price;
in the code above. When unions were used in
union the code above, the variable's biggest memory
footprint would be taken into account while
{
allocating RAM. The program mentioned above
struct{ outputs 32 bytes. When it comes to structures,
we got a size of 44 bytes, whereas when it comes
char *title;
to unions, we got a size of 44 bytes. Hence, 44
char *author; bytes save a lot of memory space since they are
larger than 32 bytes.
int number_pages;
Summary
} book;
• In C, a structure is a derived data type
struct {
consisting of a collection of member
int color; elements and their data types. Thus, a
variable of a structure type is the name of
int size;
a group of one or more members which
char *design; may or may not be of the same data type.

Structures and Unions - Unit 9 83


In programming terminology, a structure just like scalar variables.
data type is referred to as a record data
• Union can be defined as a user-defined
type and the members are called fields.
data type which is a collection of different
• In a program, members of a structure variables of different data types in the
variable may be used just like other same memory location. The union can also
variables. be defined as many members, but only one
member can contain a value at a particular
• Structure variables may be passed as point in time.
arguments and returned from functions

Structures and Unions - Unit 9 84


UNIT 10

Input/Output

Learning Objectives Introduction


At the end of this unit, you will
The Output Function printf()
be able to:

functions and functions prototypes When we say Input, it means to feed some data into a program. An
input can be given in the form of a file or from the command line. C
 Discuss the output function
programming provides a set of built-in functions to read the given
printf()
input and feed it to the program as per requirement.
 Describe the input function
scanf() When we say Output, it means to display some data on screen, printer,
or in any file. C programming provides a set of built-in functions to
 Explain the functions fprintf(),
output the data on the computer screen as well as to save it in text or
fscanf(), sprint(), and sscanf()
binary files.
 Recognize the functions
fopen() and fclose() When completing calculations, you typically wish to display your
findings (sometimes known as "the answer") on the screen. The printf
function, which enables you to display messages on the computer
screen, is part of the standard input and output library, which is
installed by default on all computers with a C compiler. The line below
must be the first line in your program to access the standard input
and output library:

#include <stdio.h>

The printf function's common format is

printf(control string, other arguments);

With two exceptions, the control string will be written exactly as


it appears in the program when it is executed. Each conversion
specification will initially be replaced by the value printf("My favorite numbers are %d and
supplied in the other arguments part of the printf %f.\n",i,x);
statement by the computer. Second, distinctive,
return 0;
difficult-to-print characters will be used in place
of escape sequences. It's crucial to keep in mind }
that the control string contains both conversion
In this illustration, we wish to print an int value
specifications and escape sequences.
that is contained in the variable i. As "d" is the
Fill-in-the-blank style placeholders in the control conversion character for decimal integers, we
string are the first sort of replacement, known should select the conversion specification%d.
as conversion specifications. A conversion As "f" is the conversion character for floating
specification has an a% at the start and a point values, we wish to utilise the conversion

conversion character at the end. Your choice specification%f since the second value is of type

of converting character will depend on the kind float. Here is an example of the code's output

of content you want to see on the screen. The after compilation and execution:

table below is a list of the various conversion


My favorite numbers are 97 and 3.140000.
characters. (This table can also be found on
page 494 of your work, A Book on C.) What happens if we swap out the printf statement
above with the one below? Characters are
Conversion How the corresponding argument is
"secretly" stored as integers.
Character printed
c as a character printf("My favorite numbers are %c and %f.\n",i,x);
d as a decimal integer
The conversion character c has been used in
as a floating point number; example
e place of the conversion character d, which shows
7.123000e+00
integers (which displays characters). Here is
as a floating point number; example
f what we observe after compiling and running the
7.123000
program:
in the e-format or f-format,
g
whichever is shorter My favorite numbers are a and 3.140000.
s as a string
Computers are obedient despite their lack
Consider the following code as an illustration: of intelligence (is the letter "a" your favourite

#include <stdio.h> number?). We instructed the computer to display


the character 97, and the ASCII table on page
int main(void)
703 of A Book on C confirms that the character
{ 'a' does indeed have the ASCII code 97. Printf
interprets the information supplied in the other
int i=97;
parameters in accordance with the conversion
float x=3.14; character.

Input/Output - Unit 10 86
Escape sequences, the second sort of letters \t and favourite), the result is the same
replacement, are used to display non-printing text with additional horizontal tabs and newlines:
and challenging-to-print characters. Certain
characters, like as newlines and tabs, generally My favorite
determine where text appears on the screen. The
numbers are 2 and 3.140000.
issue with some of these characters is that they
move the editor's cursor when you put them in The Input Function scanf()
your program when what you really want to do
is change how the text will be laid out after the Scan Formatted String is what the function
program is run. The following table lists a number scanf in the C programming language stands
of popular escape sequences together with the for. It receives information from the standard
corresponding special characters:
input stream (stdin), which is often the keyboard,

Special Character Escape Sequence and then writes the outcome into the specified
parameters.
alert (beep) \a

backslash \\ • It accepts user-provided character, string,


backspace \b and numeric data via standard input.
carriage return \r
• Like printf, Scanf also makes use of format
double quote \"
specifiers.
formfeed \f

horizontal tab \t Syntax:int scanf( const char *format, … );


newline \n
Here
null character \0

single quote \' • The return type is int.


vertical tab \v
• The type specifiers are contained in a
question mark \?
string called format (s).

A different outcome will occur if the escape


• The prefix "..." denotes that the function
sequences are added to the control string. Have a
takes an arbitrary number of parameters.
look at the original code with the printf statement
changed to a different control string: Example type specifiers recognized by scanf:

printf("My\tfavorite\nnumbers are \t%d and %d to accept input of integers.


\t%f.\n",i,x);
%ld to accept input of long integers
Even if the escape sequences and some of the
control string words are combined (such as the %lld to accept input of long long integers

Input/Output - Unit 10 87
%f to accept input of real number. Return Values:

%c to accept input of character types. >0: The number of correctly assigned and
converted values.
%s to accept input of a string.
0: No value was assigned.
Three conversion characters are of a unique kind,
and one of them, [...], isn't even a character but is <0: Read error or end-of-file (EOF) reached

still given character treatment. before any assignment was made.

Why &?
scanf() conversion characters
Conversion Scanf has to save the input data somewhere
Remarks
character
while it scans the input. The memory location of
No characters in the input stream a variable must be known for scanf to be able
are matched. The corresponding
to store this input data. And now the ampersand
n argument is a pointer to an integer,
into which gets stored the number steps in to save the day.
of characters read so far.
• The operator's address is also referred to as &.
A single % character in the input
% stream is matched. There is no
• For instance, the address of var is &var.
corresponding argument.

The set of characters inside the Example:


brackets [ ], us cakked the scan set.
It determines what gets matched. // C program to implement
(See the following explanation.)
The corresponding argument is a // scanf
[ ... ] pointer to the base of an array of
characters that is large enough #include <stdio.h>
to hold the characters that are
matched, including a terminating // Driver code
null character that is appended
automatically. int main()

Example: {

int var; int a, b;

scanf(“%d”, &var);
printf("Enter first number: ");

The user-inputted value will be written by the


scanf("%d", &a);
scanf into the integer variable var.
printf("Enter second number: ");

Input/Output - Unit 10 88
scanf("%d", &b); The function prototypes for file handling functions
are given in stdio.h. Here are the prototypes for
printf("A : %d \t B : %d" , fprintf() and fscanf():

a , b); int fprintf(FILE *fp, canst char *format, ...


);
return 0;
int fscanf(FILE *fp, canst char *format, ...
} );

Output: A statement of the form

Enter first number: 10 fprintf(file_ptr, con troL string , other_


arguments);
Enter second number: 8
writes to the file pointed to by file_ptr. The
A : 10 B: 8 conventions for controLstring and other_
arguments conform to those of printf(). In
The Functions fprintf(), fscanf(),
particular,
sprint(), and sscanf()
fprintf(stdout, ... ); is equivalent to printf(
File equivalents of the functions printf() and
... );
scanf() are the functions fprintf() and fscanf(),
respectively. We need to understand how C In a similar fashion, a statement of the form
handles files before we can talk about how to
use them. fscanf (file_ptr, control string , other_
arguments);
A specific structure with components that
reads from the file pointed to by file_ptr. In
indicate the current state of a file is defined as
particular,
the identifier FILE in the file's header, or stdio.h.
A programmer does not need to be an expert on fscanf(stdi n, ... ); is equivalent to scanf(
this structure to use files. The three file pointers ... );
stdin, stdout, and stderr are also specified in
stdio.h. We occasionally refer to them as files The functions sprint() and sscanf() are string
even though they are actually pointers. versions of the functions printf() and scanf(),
respectively. Their function prototypes, found in
Written in C Name Remark stdio.h, are
connected to the
stdin standard input file int sprintf(char *s, const char *format, ...
keyboard
);
standard output connected to the
stdout
file screen
int sscanf(const char *s, const char *format, ... );
connected to the
stderr standard error file
screen Instead of writing to the screen, the sprint()

Input/Output - Unit 10 89
function writes to its first parameter, a reference input stream to read data from the keyboard and
to char (string). The rest of its arguments line up the standard output stream to display that data
with those for printf (). Instead of reading from on the screen. When a file is opened, a pointer
the keyboard, the function sscanf() reads from to a FILE structure (specified in) containing
its first parameter. The remainder of its inputs information about the file's size, type, current file
support scanf (). Think about the code. pointer location, and other specifics is returned.
This structure also includes a file descriptor, an
char str1[] :=: "1 2 3 go", str2[lee] , tmp[l00]; integer that acts as an index into the open file
table of the operating system. The operating
int a, b, c;
system employs a block in this table called a file
sscanf(str1, "%d%d%d%s", &a, &b, &c, control block (FCB) to handle each particular file.
tmp);
Standard input, standard output, and standard
sprintf(str2, "%s %s %d %d %d\n", tmp, error are controlled by the file pointers stdin,
tmp, a, b, c); stdout, and stderr. The group of operations that
we will now explain fall under the umbrella of the
printf ("%s", str2) buffered file system. Because the procedures
automatically maintain all the disc buffers
Strl is used as the function sscanf(input. )'s It
needed for reading and writing, this file system is
reads a string, three decimal integers, and puts
known as a buffered file system.
them in the appropriate places (a, b, c, and tmp).
The sprint() function writes to str2. To be more We must first declare a pointer to the FILE
explicit, it writes characters starting at address structure and then link it to the specific file in
str2 into memory. Two strings and three decimal order to access any file. The declaration of this
integers make up its output. We use printf() to pointer, which is known as a file pointer, is as
display the contents of str2. The screen displays follows:
the following text:
FILE *fp
go go 1 2 3
fopen()
The Functions fopen() and fclose()
The following action is to open a file after a file
A file is described as a sequence of consecutive pointer variable has been declared. The fopen()
bytes that has an end-of-file marker. When a file function creates a link between a file and a
is opened, the stream is connected to it. When stream and makes it available for use. A file
program execution begins, the standard input, pointer is returned by this function.
standard output, and standard error files and
The following is the syntax:
streams are automatically opened. Streams
provide a means of exchanging data between FILE *fopen(char *filename,*mode);
files and applications.
where mode is the intended open state as a string.
For instance, a program can use the standard The filename must be a string of characters that

Input/Output - Unit 10 90
gives the operating system a valid file name and A file pointer is the value that the fopen() function
may also include a path. The permissible values returns. This pointer's value is NULL, a constant
for the fopen() mode parameter are displayed in defined in, in the event that an error arises while
the table below. opening the file. Always keep an eye out for this
possibility, like in the case above.
Table: Legal values to the fopen() mode
parameter fclose()

MODE: MEANING The fclose() method, whose syntax is as follows,


"r" / "rt" opens a text file for read only access should be used to close the file after processing
"w" / "wt" creates a text file for write only access is complete.
"a" / "at" text file for appending to a file
int fclose(FILE *fptr);
"r+t" open a text file for read and write access

"w+t" creates a text file for read and write access, The stream is terminated, any automatically
"a+t" opens or creates a text file and read access allocated buffers are released, any unwritten
"rb" opens a binary file for read only access data for the stream is flushed, any input that
"wb" create a binary file for write only access has been buffered but not yet read is discarded.
"ab" binary file for appending to a file The return value is a constant EOF, a file end-
"r+b" opens a binary or read and write access of-file marker, if an error occurred; otherwise, it
"w+b" creates a binary or read and write access, is 0. Furthermore, specifies this constant in. If
"a+b" open or binary file and read access the function fclose() is not explicitly used, the
operating system will normally close the file
How to open a file for reading is described in the when the program execution is complete.
following bit of code.
How to close a file is demonstrated in the
Code Fragment 1 following section of code.
#include <stdio.h>
# include <stdio.h>
main()
main()
{
{
FILE *fp;
FILE *fp;
if ((fp=fopen(“file1.dat”, “r”))==NULL)
if ((fp=fopen(“file1.dat”, “r”))==NULL)
{
{
printf(“FILE DOES NOT EXIST\n”);

exit(0); printf(“FILE DOES NOT EXIST\n”);

} exit(0);

} }

Input/Output - Unit 10 91
…………….. • To open and close files, we use fopen() and
fclose(), respectively. After a file has been
……………..
opened, the file pointer is used to refer to

…………….. the file.

……………. • The system opens the three standard files


stdin, stdout, and stderr at the beginning of
/* close the file */ each program. The function printf() writes
to stdout. The function scanf() reads from
fclose(fp);
stdi n. The files stdout and stderr are
} usually connected to the screen. The file
stdin is usually connected to the keyboard.
The file cannot be used again once it has been Redirection causes the operating system
closed. It can be accessed in the same mode or to make other connections.
another if necessary.
• A set of functions that use file descriptors
Summary is available in most systems, even though
these functions are not part of ANSI C.
• The functions printf() and scanf(), and the
They require user-defined buffers. The file
related file and string versions of these
descriptors of stdin, stdout, and stderr are
functions, all use conversion specifications
0, 1, and 2, respectively.
in a control string to deal with a list of
arguments of variable length.

Input/Output - Unit 10 92
UNIT 11

The Operating System

Learning Objectives Introduction


At the end of this unit, you will
File Descriptor Input/Output
be able to:

C was invented to write an operating system called UNIX. C is a


 Explain how to execute
commands from within a C successor of B language which was introduced around the early
program 1970s. The language was formalized in 1988 by the American National
Standard Institute (ANSI). The UNIX OS was totally written in C.
 Infer about the environment
variables A nonnegative integer connected to a file is referred to as a file
descriptor. The library functions that are utilized with file descriptors
 Discuss the concept of the C
compiler are discussed in this section. Despite not being ANSI C-compliant,
these functions are present on the majority of C systems under MS-
 Define the concept of libraries DOS and UNIX. Care must be used while transferring code from UNIX
used in C
to MS-DOS or vice versa due to minor differences.

FD PURPOSE

0 Standard input

1 Standard output

3 Standard error

The majority of standard library functions that use a reference to FILE


are buffered. Contrarily, file descriptor-using functions might call for
programmer-specified buffers. Let's use a program that reads from
one file and writes to another while changing the case of each letter
to demonstrate how file descriptors are used.

In file change_case.c

/* Change the case of letters in a file. */


#include <ctype.h> Program analysis for change_case

#include <fcntl.h> #include <ctype.h>

#include <unistd.h> /* use io.h in MS_ #include <fcntl.h>


DOS */
#include <unistd.h>
#define BUFSIZE 1024
We'll make advantage of the fcntl.h header file's
int main(int argc, char **argv) symbolic constants. The header file unistd.h
contains prototypes for the open () and read ()
{
functions. Instead, we would add io.h to MS-DOS.

char mybuf[BUFSIZE], *p;


in_fd = open(argv[lJ, O_RDONLY);

int in_fd, out_fd, n; The first input to open() is a file name, and the
second one specifies how to open the. If there are
in_fd = open(argv[lJ, O_RDONLY);
no issues, the function returns a file descriptor;
out_fd = open(argv[2] , O_WRONLY I O_ otherwise, it returns the value -1. The mnemonic
EXCL | 0_CREAT, 0600; "in fd" stands for "in file descriptor." The cntl.h
file presents the symbolic constant O RDONL
while ((n = read(in_fd, mybuf, BUFSIZE))
Y, which works with both MS-DOS and UNIX
> 0) {
platforms. As a mnemonic, it denotes "available
for (p = mybuf; p mybuf < n; ++p) for reading only."

f (islower(*)) Out_fd = open(argv [2], 0_WRONLY | 0_


EXCL | 0_CREAT, 0600);
*p = toupper(*p);
The symbolic constants in fcntl.h that are used
else if (isupper(*p))
to open a file can be combined using the bitwise
*p = tolower(*p); OR operator. Here, we specify that the file
should only be opened for writing (i.e., if the file
write(out_fd, mybuf, n);
already exists, it is a mistake), that it should only

} be opened for writing, and that if the file does


not already exist, it should be created. O EXCL
close(in_fd); can only be obtained through O CREAT. If the
file is created, the third parameter sets the file
close(ouLfd);
permissions; otherwise, it has no effect. Further
return 0; information on file permissions will be provided
below.
}

The Operating System - Unit 11 94


while ((n = read(in_fd, mybuf, BUFSIZE)) > 0) {
Meaning of each octal digit in the file permissions

Mnemonic Bit representation Octal representation


A maximum of BUFSIZE characters from the
r-- 100 04
stream connected to in fd are read and then
-w- 010 02
written to mybuf. The total number of characters
--x 001 01
read is returned. The body of the while loop rw- 110 06
is executed so long as read 0 is able to read r-x 101 05

characters from the stream. Throughout the -wx 011 03

body of the loop, the letters in mybuf are changed rwx 111 07

to the reverse case.


Now, we can calculate the file access permissions
write(out_fd, mybuf, n); by combining three octal digits into a single
integer. The most straightforward to remember
n characters in mybuf are written to the stream
is the mnemonic representation. The user, the
indicated by out_fd. group, and others are denoted, respectively, by
the first, second, and third groups of three letters.
close(in_fd);
Examples of file access permissions
close(out_fd);
Mnemonic Octal representation

rw------- 0600
The two files are then closed. The system
rw----r-- 0604
will close the files upon program exit if the
rwxr-xr-x 0755
programmer has not expressly instructed it to do rwxrwxrwx 0777
so.
The rights rwxr-xr-x signify that the owner, the
File Access Permissions
group, and others may all read and execute the
In UNIX, a file is created with the appropriate file. They also signify that the owner can read,
access permissions. The permissions govern write, and execute the file. The Is -1 command
who has access to a file, including the owner, the in UNIX displays the mnemonic file access
group, and other users. It is possible to combine permissions. File permissions are available in
read, write, execute, or none of these access MS-DOS, but only for everyone.
capabilities. When a file is created by calling
Executing Commands from Within a C
open 0, the third parameter can be a three-
Program
digit octal integer to set the permissions. Each
octal digit controls the read, write, and execute Access to operating system commands is
permissions. A user's permissions are controlled provided via the library function system(). The
by the first octal digit, a group's permissions are command date causes the current date to be
controlled by the second octal digit, and others' printed on the screen in both MS-DOS and UNIX.
permissions are controlled by the third octal From within a program, we can write code to
digit. (Everyone is included in "others"). print this information on the screen.

The Operating System - Unit 11 95


system(“date”); char command [MAXSTRING], *tmp_
filename;
System() treats the string as an operating system
command. Control is transferred to the operating int c;
system when the statement is executed, where it
is used to carry out the instruction before being FILE *ifp;

returned to the program.


tmp_filename = tmpnam(NULL);
In UNIX, Vi is a well-liked text editor. Let's imagine
sprintf(command , "dir > %s", tmp_
that from within a program, we want to utilise vi to
filename);
edit a file that has been supplied as a command
line argument. Our ability to write system(command)j

char command[MAXSTRING]; ifp = fopen(tmp_fil ename, n r");

sprintf(command, "vi %S", argv[l])' while ((c = getc(ifp)) != EOF)

printf("vi on the file %5 is coming up ... \n", putchar(tolower(c));


argv[l]);
remove(tmp_filename);
system(command);
return 0;
If we use an editor that is available on that system
in place of vi, a similar example will function in }
MS-DOS.
Then, we use the library function tmpname to
As a last illustration, imagine that we have create a temporary file name (). The system()
had enough of the capital letters that the dir function is then used to pass the output of the dir
command on our MS-DOS system produces. A command into the temporary file. After that, the
software that uses this command and only prints file's contents are displayed on the screen with
lowercase letters on the screen can be created. all uppercase letters changed to lowercase. After
we have finished using the temporary file, we call
In file lower_case.c
the library method remove() to delete it..
/* Write only lowercase on the screen. */
Environment Variables
#include <ctype.h>
Both UNIX and MS-DOS support environment
#include <stdio.h> variables. To print them on the screen, run the
next program:
#include <stdlib.h>
#include <stdio.h>
#define MAXSTRING 100
int main(int argc, char *argv[], char *env[])
int main(void)
{
{

The Operating System - Unit 11 96


int i; getenv() can be used in a C program to get the
value of an environment variable that has been
for (i 0; env[i] ! NULL; ++i)
supplied as an argument. Here is an illustration
printfC"%s\n" , env[i]); of how to use getenv():

return 0; printf("%s%s\n%s%s\n%s%s\n%s%s\n",

} " Name: ", getenv("NAME"),

The third argument to the main() method is a “ User: ", getenv("USER"),


pointer to a pointer to char, often known as an
“ Shell: ", getenv("SHELL"),
array of strings or pointers to char. The system
provides the strings and the storage space for " Home directory t:
them. Env, the last element of the array, is a ,”getenv("HOME"));
NULL pointer. Our UNIX system prints using this
In stdlib.h, the function prototype is available. The
program.
NULL pointer is returned if the string supplied as
HOME=/c/c/blufox/center_manifold an input is not an environment variable.

SHELL=/bin/csh
The C Compiler
TERM=vt102
There are numerous C compilers, and any number
USER=blufox of them may be offered by an operating system.
Just a few of the options are listed below:
The environment variable is to the left of the
equal sign, and its value, which should be viewed Command The C compiler that gets invoked

as a string, is to the right of the equal sign. This cc The system supplied native C compiler

software prints on our MS-DOS machine. An early version of an ANSI C compiler from Sun
acc
Microsystems
COMSPEC=C:\COMMAND.COM bc Borland C/C++ compiler, integrated environment

bcc Borland C/C++ compiler, command line version


BASE=d:\base
GNU C compiler from the Free Software
gcc
Foundation
INCLUDE=d:\msc\include
hc High C compiler from Metaware
The command to display the environment occ Oregon C compiler from Oregon Software

variables is provided by the UNIX system, qc Quick C compiler from Microsoft

however it depends on the shell you are currently tc


Turbo C compiler, integrated environment, from
Borland
using. The command is set in MS-DOS and the
Turbo C compiler, command line version, from
Bourne shell while printenv is used in the C shell. tcc
Borland
The command's output and our program's output
are identical. In this part, we go over a few of the UNIX systems'
Environment variables are typically capitalised cc command's available options. Similar options
as a matter of convention. The library function are offered by other compilers. If an entire

The Operating System - Unit 11 97


program, such as pgm.c, is stored in a single file, Some useful options to the compiler
then the command v Compile only, generate corresponding .o files.

-g Generate code suitable for the debugger.


Cc pgm.c
-o name Put executable output code in name.

-p Generate code suitable for the profiler.


creates executable object code from the C code
-v Verbose option, generates a lot of information.
in pgm.c and writes it to the file a.out. (Pgm.
-D name -def Place at the top of each .c file the line.
exe is the executable file's name on MS-DOS.) #define name def.
The program is run with the command a.out. -E Invoke the preprocessor but not the compiler.

Whatever is in a.out will be overwritten by the -I dir Look for #include files in the directory dir.

next cc command. If we issue the order -M Make a make file.

-O Attempt code optimization.


cc -0 pgm pgm.c Generate assembler code in corresponding .s
-S
files.
A.out won't be affected, and the executable code
will instead be written directly into the file pgm. There's a chance your compiler will offer
additional options in addition to those listed
In reality, the cc command completes its task
below. Alternatively it might employ various
in three steps: The preprocessor is called first,
flag characters. Several memory models are
followed by the compiler and then the loader.
often supported by MS-DOS compilers. For
The final executable file is created by the loader,
a comprehensive list of options, consult the
also known as the linker. You can only invoke the
documentation for your compiler.
preprocessor and compiler with the -c option;
you cannot call the loader. If we have a program Recommendation: If you've never used the -v
that is written in multiple files, this is helpful. option, give it a shot. When trying to understand
Considering the order every aspect of the compilation process, certain
compilers generate a tonne of information that
cc –c main.c file1.c file2.c can be quite helpful.

Corresponding object files with a .0 extension Libraries


will be created if there are no mistakes. We
can compile a combination of.C and.0 files to A utility for creating and managing libraries

produce an executable file. Imagine, for instance, is offered by several operating systems. The
program is known as the archiver in UNIX and
that main.c contains a mistake. After fixing the
is accessed using the ar command. This tool,
error in main.c, we may issue the command.
known as the librarian in the Ms-DOS universe,
cc -0 pgm main.c file 7.0 file2.0 is an add-on function. For instance, the Turbo C
librarian is tUb, whereas the Microsoft librarian is
Using .0 files instead of.e files speeds up
lib. By convention, files in a library end in.a in UNIX
compilation,
and.lib in MS-DOS. The topic will be discussed in

The Operating System - Unit 11 98


relation to UNIX, but the main concepts apply to #inc1ude <stdio.h>
any librarian.
#inc1ude <stdlib.h>
The standard C library for UNIX is often located
void *gca11oc(int n, unsigned sizeof_
in the file /lib/libc.a, but it can also exist in whole
something)
or in part in other files. Try the command if UNIX
is available to you. {

art /usr/lib/llbe.a void *p;

The title, or name, of each file in the library is if ((p = calloc(n, sizeof_something))
NULL) {
displayed using the key t. More than you care to
look at exist. You can use the command to count fprintf(stderr, "\nERROR: ca11ocO failed -
them. bye.\n\n");

art /usr/lib/libe.a I we exit(l);

By connecting the output of the ar command to }


the input of the we command, this counts the
return p;
number of lines, words, and characters. It is not
very remarkable that the standard library keeps }
growing over time. A DEC VAX 11/780 from
Before we can create our library, we must first
the 1980s has 311 object files in its standard
compile the.e files to create the corresponding.0
library. In 1990, a moderately new Sun computer
files. After that, we give the two directives.
contained 498 object files in its standard library.
The Sun machine we are using right now has 563 ar ruv fl_lib.a gfopen.o gfclose.o flealloc.o
object files. ...

Let's give an example of how programmers can ranlib fl_lib.a

build and utilise their own libraries. This will be


The keys ruv in the first command stand for
done as part of building a "graceful library." We
replace, update, and verbose, respectively. This
currently have 11 such gracious functions in a action generates the library g lib.a if it doesn't
directory called g lib, and we regularly add more. already exist. If so, the named.0 files replace any
They include procedures like gfclose(), gcalloc(), other identically named files that are currently
gmalloc(), and others. Although each is written present in the library. If the named.0 files don't
in a distinct file, they may all very well be in one already exist in the library, they are added.
file for the sake of establishing a library. We
The ranlib tool is used to randomise the library so
provide the gcalloc() code to further illustrate the
that the loader may use it. Imagine that main.c
concept of functions:
and two other.e files will make up the software

The Operating System - Unit 11 99


we are developing. If our software calls gfopen(), statement
we have to make our library available to the
System(“dir");
compiler. The following command makes this
happen: will cause a list of directories and files to
be listed on the screen.
CC -0 pgm main.e file I.e file2.c g_lib.a

• Many operating systems provide a utility


If a function is called by our application without
to create and manage libraries. In UNIX
providing the function definition, the standard
the utility is called, archiver, and it is
library will be searched before g_lib.a. The final
invoked with the arc command. In the
executable file will only contain the functions
MS-DOS world, this utility IS called the
that are actually required.
librarian, and it is an add-on feature.
Summary
• The make utility can be used to keep track
• An operating system command can of source files and to provide convenient
be executed from within a program access to libraries and associated header
by invoking system(). In MS-DOS, the files.

The Operating System - Unit 11 100


UNIT 12

Moving from C to C++

Learning Objectives Introduction


At the end of this unit, you will
Functions
be able to:

The new function prototype syntax used by standard C compilers was


 Define the concept of classes
and abstract data types inspired by the syntax of functions in C++. In essence, a list of the
various argument types is contained within the header parentheses.
 Discuss constructors and By explicitly declaring the type and number of arguments in C++,
destructors
strong type checking and conversions that are consistent with

 Infer the concept of object-


assignments are possible.
oriented programming,
inheritance, and polymorphism Function parameters may be called directly by reference in C++.
Declaring call-by-reference parameters requires the following syntax:

type& identifier

The default settings for C++ function arguments are also an option.
They are provided in the parameter list by the function declaration.

= expression

placed following the parameter.

The example below demonstrates these ideas:

In file add3.cpp

// Use of a default value

#include <iostream.h>

inline void add3(int& s, int a, int b, int c=0)


{ associated operators and functions are provided
by a c1 ass. Hence an ADT can be implemented
s = a + b + c;
with a c1 ass. To implement a limited form of
} string, let's create a C1 ass called string.

inline double average(int s) { return s / In file my _string.cpp


3.0; }
// An elementary implementation of type string.
int main()
#inc1ude <string.h>
{
#include <iostream.h>
int score_I, score_2, score_3, sum;
canst int max_len = 255;
count <<"\nEnter 3 scores: ";
class string {
Cln >> score_I >> score_2 >> score_3;
public: // universal access
add3(sum, score_I, score_2, score_3);
void assign(const char* st)
cout<< \nSum = "<< sum;
{ strcpy(s, st); len = strlen(st); }
cout << It\nAverage = "<<average(sum)
int 1ength() { return len; }
<< end1'
void printO { cout« s« "\nLength: //
add3(sum:. 2 * score_I, score_2); // use
<<le<<"\n"; }
of default value 0
private: // restricted access to member
cout<< \nWeighted Sum "<< sum << // If,
functions
cout <<"\nWeighted Average = It <<
char s[max_len]; // implementation by
average(sum) <<".\n";
character array
}
int 1en;
Here, invoking add 30 only requires three actual
};
parameters. The default value for the fourth
argument is zero. The typical C structure idea is expanded in this
example in two key ways: It has members that
Classes and Abstract Data Types
are functions like assign as well as members
The c1 ass aggregate type is what makes c++ that are both public and private. The term pub
new. A c1 ass is a development of the struct 1 I c designates the visibility of the following
concept in conventional C. The mechanism for members. Without this keyword, the members
implementing a user-defined data type and any are private to the class. Private members can only

Moving from C to C++ - Unit 12 102


be accessed by other member functions of the cout << three;
class. Public members can be accessed by any
method that is covered by the class declaration. cout <<"\nLength: // << strlen(three) <<

The implementation of a class type may be endl; // Print shorter of one and two.

"hidden" for privacy reasons. This restriction


if (one.length() <= two.length())
prevents unanticipated modifications to the
data structure. Object-oriented programming is one.print ();
characterised by data hiding or limited access.
else
The declaration of member functions enables
two.print();
the ADT to assign particular functions to execute
on its private representation. The length of the }
string is determined by the characters up to but
excluding the first character with a zero value, and The first and second variables are of the string
is returned by the member function 1ength as an type. The variable three is incompatible with
example. The member function print generates strings because it is of the pointer to char type.
both the string and its length (). By using the The dot operator, also known as the "structure
member function assign (), a character string is member operator," is used to call the member
saved in the hidden variable s, and its length is functions. It is clear from their definitions that
determined and saved in the hidden variable 1en. member functions work with the secret private
member fields of the designated variables. In
This data type string can now be used just like order to access this member, one cannot be
a language's fundamental types. It complies written within of main. The result of this example
with C's common block structure and scope program is
requirements. This class is also used by client
code. Only the public members can be used by My name is Charles Babbage.
the client to manipulate string variables.
Length: 27
// Test of the class string.
My name id Alan Turing.
int mainO
Length: 23
{
Constructors and Destructors
string one, two;
A constructor is one of a class's member
char three [40] {liMy name is Charles functions with the same name as the class itself.
Babbage."}; Initializing a class's object is helpful. It has the
option to accept or reject the arguments. It is
one.assign("My name ;s Alan Turing."); employed to allocate memory to a class object.
Every time a class instance is created, it is called.
two.ass;gn(three);
It can be manually defined both with and without

Moving from C to C++ - Unit 12 103


arguments. A class may include a large number using namespace std;
of constructors. It cannot be inherited or virtual,
class Z
but it can be overloaded. To initialise an item
from another object, one can utilise the copy {
constructor idea.
public:
Syntax:
// constructor
ClassName()
Z()
{
{
//Constructor's Body
cout<<"Constructor called"<<endl;
}
}
Destructor:
// destructor
Like a function Object() { [native code] }, a
destructor is a member function of a class ~Z()
whose name is the class name followed by
{
the tilde() operator. The memory of an object
can be dealt with. When the class's object is cout<<"Destructor called"<<endl;
released or deleted, it is called. A class always
has a single destructor that has no parameters, }
preventing overloading. It is always invoked in
};
the constructor's reverse order. If a class inherits
another class and both classes have a destructor, int main()
the destructor of the child class is called first,
{
followed by the destructor of the parent or base
class. Z z1; // Constructor Called

~ClassName() int a = 1;

{ if(a==1)

//Destructor's Body {

} Z z2; // Constructor Called

Example: } // Destructor Called for z2

#include <iostream> } // Destructor called for z1

Moving from C to C++ - Unit 12 104


Output: of students. We must create a base class that
captures the definition of "student." Graduate
Constructor called
and undergraduate students are the two main

Constructor called subgroups.

Destructor called The OOP design methodology is as follows:

Destructor called OOP Design Methodology

Object-oriented Programming and • Choose a suitable assortment of sorts.


Inheritance
• Design in their connection.
The inheritance system is an innovative OOP
• To share code, use inheritance.
concept. This is the process for deriving a new
class from a base class that already exists. This is an illustration of deriving a class:
The members of the inherited base class are
increased or changed by the derived class. This enum support { ta, ra, fellowship, other };

is used to establish a hierarchy of related kinds


enum year { fresh, soph, junior, senior,
and share code and interface.
grad };

The use of hierarchy helps people manage


class student {
complexity. It assigns items to different
categories. The periodic table of elements, public: student(char* nm, int id, double g,
for instance, has elements that are gases. year x);
They have characteristics that all items in that
voi d pri ntO ;
categorization share. An essential subclass of
gases are inert gases. Here, the hierarchy looks private: int student_id;
like this: A gas, like argon, is an element since
it is an inert gas. The behavior of inert gases double gpa;
can be easily understood using this hierarchy.
year y;
Since all elements match this characteristic,
we are aware that they are made up of protons char name[30];
and electrons. Since all gases behave in the
same way at ambient temperature, we can be };

certain they are in a gaseous state. While this is


class grad_student: public student {
a characteristic of all inert gases, we know they
do not combine with other elements in typical public: grad_student (char* nm, int id,
chemical processes. double g, year x, support t,

Think about creating a database for a college. char* d, char* th);


The registrar must keep tabs on various kinds

Moving from C to C++ - Unit 12 105


void printO; in C++. A function's signature, which is the list of
argument types in its parameter list, determines
private:
how it is called.

support s;
a/b // divide behavior determined by

char dept[10]; native coercions

char thesis[80]; cout<< a // overloading « the shift


operator for output
};
The outcome of the division statement depends
In this example above, the base class is student, on the arguments being forced by default to the
and the derived class is graduate student. widest type. Hence, the outcome is an integer
Because the word "public" is inserted after the division if both arguments are integers. The
colon in the derived class header, the public outcome is floating-paint if either one or both
members of student are to be inherited as public parameters are floating-point. The shift operator
members of graduate student. The private <<invokes a function that can output an object of
members of the base class are not accessible type an in the output statement.
to the derived class. Due to public inheritance,
the derived class grad student IS a subtype of Localizing behavioral responsibility through

student. polymorphism. When new functionality is added


to the system thanks to code advancements
An inheritance structure offers the overall from ADT, the client code frequently doesn't
system a design. For instance, from the base need to be revised.
class member, a database containing all of the
students at a college may be created. Extension A thorough structural description of any shape is

students could be included in the student-grad_ a prerequisite for the C method for constructing

student relation as an additional significant a set of routines to produce an ADT shape.

category of objects. Similar to how other


struct shape {
employment categories may use person as their
basis class, enum{CIRCLE, ..... } e_val;

Polymorphism double center, radius;

The forms of a polymorphic function are };


varied. The division operator is an illustration
would include an enumerator value to help
of Standard C. Integer division is used when the
identify it as well as all the members required
arguments to the division operator are integral.
for any shape that is currently drawable in our
But, floating-point division is used if either one or
system. Then, the area procedure would be
both parameters are.
expressed as
A function name or operator can be overloaded

Moving from C to C++ - Unit 12 106


double area(shape* s) class rectangle: public shape {

{ public:

switch(s -> e_val) { II pure virtual function

case CIRCLE: return (PI * s -> radius * s -> rectangle(double h, double w): height(h),
radius); width(w) {}

case RECTANGLE: return (s -> height*S -> double area() { return (height * width);} //
width); overridden

} private:

A form hierarchy is used by oop coding double height, width;


techniques in C++ to solve the same issue. The
};
hierarchy is the one where the shape of the
circle and rectangle comes first. A new derived class circle: public shape {
class is created throughout the revision process
to accommodate code updates, localising public:
additional description. The meaning of any
circle(double r): radius(r) {}
modified routines—in this case, the new area
calculation—is overridden by the programmer. double area() { return ( 3.14159 * radius
The new type is not used by client code, therefore * radius); }
it is unaffected. Client code that benefits from
the new type often undergoes minimal change. private:

This design employs shape as an abstract base double radius;


class in C++ programmes. A single or more
};
pure virtual functions can be found in this class.
There is no definition for a pure virtual function. The client code is polymorphic and computes
A derived class is where the definition is located. an arbitrary area. At runtime, the proper area()
function is chosen.
// shape is an abstract base class
shape'" ptr _shape;
class shape {
cout <<" area = "<< ptr _shape-> area();
public:
Imagine creating a square class to enhance our
virtual double area() = 0; // pure virtual
hierarchy of types.
function
class square: public rectangle {
};

Moving from C to C++ - Unit 12 107


public: type (ADT). are two important additions
to the structure concept: first, it includes
square(double h): rectangle(h,h) {}
members that are functions, and second,

double area() { return rectangle::area(); } it employs access keywords public,


private, and protected. These keywords
}; indicate the visibility of the members that
follow. Public members are available to
The client-side code is unaltered. With non-OOP
any function within the scope of the class
code, this would not have been the case.
declaration. Private members are available
Summary for use only by other member functions of
the class. Protected members are available
• c++ reduces C's traditional reliance on for use only by other member functions of
the preprocessor. Instead of using define, the class and by derived classes. Privacy
special constants are assigned to variables allows part of the implementation of a
specified as canst. The new keyword inline class type to be "hidden."
specifies that a function is to be compiled
inline to avoid function call overhead. As a • A polymorphic function has many forms.
rule, this should be done sparingly and only A virtual function allows run-time selection
on short functions. from a group of functions overridden
within a type hierarchy. An example in
• What is novel about C++ is the aggregate the text is the area calculation within the
type class. A class is an extension of the idea shape hierarchy. Client code for computing
of struct in traditional C. Its use is a way of an arbitrary area is polymorphic. The
implementing a data type and associated appropriate area() function is selected at
functions and operators. Therefore, a class run-time.
is an implementation of an abstract data

Moving from C to C++ - Unit 12 108

You might also like