Module 1 C Programing
Module 1 C Programing
The programming language C was developed in the early 1970s by Dennis Ritchie at Bell
Laboratories to be used by the UNIX operating system. It was named ‘C’ Because many of its features
were derived from an earlier language called ‘B’. Although C was designed for implementing system
software, it was later on widely used for developing portable application software. C is one of the
most popular programming languages. It is being used on several different software platforms. In a
nutshell, there are a few computer architectures for which a C compiler does not exist. It is a good
idea to learn C because few other programming languages such a C++ and Java are also based on C
which means you will be able to learn them more easily in the future.
Characteristics of C: It is a robust language whose rich set of built - in functions and operators can
be used to write complex programs. The C compiler combines the features of assembly languages
and high - level languages, which makes it best suited for writing system software as well as
business packages. Some basic characteristics of C language that define the language and have led to
its popularity as a programming language are listed below:
- C is a high level programming language, which enables the programmer to concentrate on
the problem at hand and not worry about the machine code on which the program would be
run.
- Small size - C has only 32 keywords. This makes it relatively easy to learn as compared to
other languages.
- C makes extensive use of function calls.
- C is well suited for structured programming. In this programmed approach, C enables users
to think of a problem in terms of function/modules where the collection of all the modules
makes up a complete program. This feature facilitates ease in program debugging, testing,
and maintenance.
- Core language. C is a core language as many other programming languages (like C++, Jave,
Perl, etc) are based on C. If you know C, learning other computer languages becomes much
easier.
- C is a portable language, i.e., a C program written for one computer can be run on another
computer with little or no modification.
Uses of C: C is a very simple language that is widely used by software professionals around the
globe. The uses of C language an summarized as follows:
- C language is primarily used for system programming. The portability, efficiency, the ability
to access specific hardware addresses, and low runtime demand on system resources make
it a good choice for implementing operating systems and embedded system applications.
- C has been so widely accepted by professionals that compilers, libraries, and interpreters of
other programming languages are often written in C.
- For portability and convenience reasons, C is sometimes used as an intermediate language
for implementation of other languages. Examples of compilers which use C this way are BitC,
Gambit, the Glasgow Haskell Compiler, Squeak, and Vala.
- Basically, C was designed as a programming language and was not meant to be used as a
compiler target language. Therefore, although C can be used as an intermediate language it
is not an ideal option. This led to the development of C based intermediate languages such
as C - -.
- C is widely used to implement end - user applications.
Structure of a C program
A C program is composed of preprocessor commands, a global declaration section, and one or more
functions. The preprocessor directives contain special instructions that indicate how to prepare the
program for compilation. One of the most important and commonly used preprocessor commands
is including which tells the compiler that to execute the program, some information is needed from
the specified header file.
A C program contains one or more functions, where a function is defined as a group of C statements
that are executed together. The statements in a C function are written in a logical sequence to
perform a specific task. The main () function is the most important function and is a part of every C
program. The execution of a C program begins at this function.
All functions (including main ()) are divided into two parts - the declaration section and the
statement section. The declaration section precedes the statement section and is used to describe
the data that will be used in the function. Note that data declared within a function are known as
local declaration as that data will be visible only within that function. Stated in other terms, the life -
time of the data will be only till the function ends. The statement section in a function contains the
code that manipulates the data to perform a specified task.
From the structure given above we can conclude that a C program can have any number of functions
depending on the tasks that have to be performed, and each function can have any number of
statements arranged according to specific meaningful sequence.
include <stdio.h>
int main ()
{
printf(“ n Welcome to the world of C “);
return 0;
}
Output
Welcome to the world of C
include <stdio.h>
This is a preprocessor command that comes as the first statement in our code. The include
statements tells the compiler to include the standard input/output library or header file (stdio.h)in
the program. This file has some in built functions. By simply including this file in our code we can
use these functions directly. The standard input/output header file contains functions for input and
output of data such as reading values from the keyboard and printing the results on the screen.
int main()
Every C program contains a main() function which is the starting point of the program. int is the
return value of the main() function. After all the statements in the program have been written, the
last statement of the program will return an integer value to the operating system.
Header files
When working with large projects, it is often desirable to separate out certain subroutines from the
main () function of the program. There also may be a case that the same subroutine has to be used
in different programs. In the latter case, one option is to copy the code of the desired subroutine
from one program to another. But copying the code is often tedious as well as error prone and
makes maintainability more difficult. So, another option is to make subroutines and store them in a
different file known as header file. The advantages of header files can be realized in the following
cases:
- The programmer wants to use the same subroutines in different programs. For this, he
simply has to compile the source code of the subroutines once, and then link to the resulting
object file in any other program in which the functionalities of these subroutines are
required.
- The programmer wants to change or add subroutines, and have those changes reflected in
all the other programs. In this case, he just needs to change the source file for the
subroutines, recompile its source code, and then link programs that use them. This way time
can be saved as compared to editing the subroutines in every individual program that uses
them.
Thus, we see that using a header file produces the same results as copying the header file into each
source file that needs it. Also when a header file is included, the related declarations appear in only
one place. If in future we need to modify the subroutines, we just need to make the changes in one
place, and programs that include the header file will automatically use the new version when
recompiled later. There is no need to find and change all the copies of the subroutine that has to be
changed.
Conventionally, header files end with a ‘.h’ extension and names can use only letters, digits, dashes,
and underscores. Although some standard header files are automatically available to C
programmers, in addition to those header files, the programmer may have his own user defined
header files.
Standard Header files: In the program that we have written till now, we used printf() function that
has not been written by us. We do not know the details of how this function works. Such functions
that are provided by all C compilers are included in standard header files. Examples of these
standard header files include:
- string.h : for string handling function
- stdlib.h : for some miscellaneous functions
- stdio.h : for standardized input and output functions
- math.h : for mathematical functions
- alloci.h : for dynamic memory allocation
- conio.h : for clearing the screen.
All the header files are referenced at the start of the source code file that uses one or more functions
from that file.
Object files: These are generated by the compiler as a result of processing the source code file.
Object files contain compact binary code of the function definitions. Linker uses these object files to
produce an executable file (.exe file) by combining the object files together. Object files have a ‘.o’
extension, although some operating systems including windows and MS - DOS have a ‘.obj’ extension
for the object file.
Binary Executable files: The binary executable file is generated by the linker. The linker links the
various object files to produce a binary file that can be directly executed. On the Windows operating
system, the executable files have a ‘.exe’ extension.
The compilation process shown in Fig is done in two steps. In the first step, the preprocessor
program reads the source file as text, and produces another text file as output. Source code lines
which begin with the ?? symbols are actually not written in C but in the preprocessor language. The
output of the preprocessor is a text file which does not contain any preprocessor statements. This
file is ready to be processed by the compiler. The linker combines the object file with library
routines (supplied with the compiler) to produce the final executable file.
In modular programming, the source code is divided into two or more source files. All these source
files are compiled separately there by producing multiple object files. These object files are
combined by the linker to produce an executable file.
Variables
A variable is defined as a meaningful name given to a data storage location in computer memory.
When using a variable, we actually refer to the address of the memory where the data is stored. C
language supports two basic kinds of variables - numeric and character.
Numeric Variables: Numeric Variables can be used to store either integer values or floating point
values. While an integer value is a whole number without a fraction part or decimal point, a floating
point value can have a decimal point. Numeric variables may also be associated with modifiers, such
as short, long, signed and unsigned. The difference between signed and unsigned numeric variables
is that signed variables can be either negative or positive but unsigned variables can only be
positive. Therefore, by using an unsigned variable we can increase the maximum positive range.
When we do not specify the signed/unsigned modifier. C language automatically takes it as a signed
variable. To declare an unsigned variable, the unsigned modifier must be explicitly added during the
declaration of the variable.
Character Variables:
Character variables are just single characters enclosed within single quotes. These characters could
be any character from the ASCII character set — letters (‘a’, ‘A’), numerals (‘2’), or special characters
(‘&’). In C, a number that is given in single quotes is not the same as a number without them. This is
because 2 is treated as an integer value by ‘2’ is a considered character not an integer.
Declaring variables;
Each variable to be used in the program must be declared. To declare a variable, specify the data
type of the variable followed by its name. The data type indicates the kind of values that the variable
will store. Variable names should always be meaningful and must reflect the purpose of their usage
in the program. The memory location of the variable is of importance to the compiler only and not
to the programmer. Programmers must only be concerned with accessing data through their
symbolic names. In C, variable declaration always ends with a semicolon, for example:
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short in acc_no;
In C variables can be declared at any place in the program but two things must be kept in mind.
First, variables should be declared before using them. Second, variables should be declared closest
to their first point of use to make the source code easier to maintain. C allows multiple variables of
the same type to be declared in one statement. So the following statement is legal in C. float
temp_in_celsius, temp_in_farenheit;
Initializing Variables
While declaring variable, we can also initialize them with some value, For example,
int emp_num = 7;
float salary = 2156.35;
The initializer applies only to the variable defined immediately before it. Therefore, the statement
int count, flag = 1;
initializes the variable flag and does not count. If you want both the variables to be declared in a
single statement then write, int count = 0, flag = 1.
Constants;
Constants are identifiers whose values do not change. While values of variables can be changed at
any time values of constants can never be changed. Constants are used to define fixed values like
mathematical constant pi or the charge on an electron so that their value does not get changed in
the program even by mistake.
A constant is an explicit data value specified by the programmer. The value of the constant is known
to the programmer. The value of the constant is known to the compiler at the compile time. C allows
the programmer to specify constants of integer type, floating point type, character type, and string
type
Integer constants: A constant of integer type consists of a sequence of digits. For example, 1, 34,
567, 8907 are valid integer constants. A literal integer like 1234 is of type int by default. For a long
integer constant the literal in succeeded with either ‘L’ or ‘l’ (like 1234567L0. Similarly, an unsigned
int literal is written with a ‘U’ or ‘u’ suffix (ex: 12U). Therefore, 1234L, 1234L, 1234U, 1234u, 124LU,
1234u) are all valid integer constants.
- Integer literals can be expressed in decimal, octal, or hexadecimal notation. By default an
integer is expressed in decimal notation. Decimal integers consist of a set of digits, 0 through
9, preceded by an optional - or + sign. Examples of decimal integer constants include: 123,
-123, +123, and 0.
- While writing integer constants, embedded spaces, commas, and non - digit characters are
not allowed. Therefore, integer constants given below are totally invalid in C.
123 456
12, 34, 567
$123
- An integer constant preceded by a zero (0) is an octal number. Octal integers consist of a set
of digits, 0 through examples 7. Examples of octal integers include
012 0 01234
- Similarly, an integer constant is expressed in hexadecimal notation if it is preceded with 0x
or 0x. hexadecimal numbers contain digits from 0-9 and letters A through F, which represent
numbers 10 through 15. For example, decimal 72 is equivalent to 0110 in octal notation and
0x48 in hexadecimal notation. Examples of hexadecimal integers are 0x12, 0x7F, 0xABCD,
0X1A3B.
Floating point constants: Integer numbers are inadequate to express numbers that have a fractional
part. A floating point constant consists of an integer part, a decimal point, a fractional part, and an
exponent field containing a e or E (e means exponent) followed by an integer where the fraction
part and integer part are a sequence of digits. However, it is not necessary that every floating point
constant must contain all these parts. Some floating point numbers may have certain parts missing.
Some valid examples of floating point numbers are: 0.02, -0.23, 123.456, +0.34 123, 0.9, -0.7, +0.8
etc. A literal like 0.07 is treated as of type double by default. To make it a float type literal, you must
specify it using the suffix F or f. Consider some valid floating point literals given below (Note that
suffix L is for long double).
0.02F 0.34f 3.141592654L 0.002146 2.146E-3
A floating point number may also be expressed in scientific notation. In this notation, the mantissa
is either a floating point number or an integer and an exponent is an integer with an optional plus
or minus sign. Therefore, the numbers given below are valid floating point numbers
0.5e2 14E-2 1.2e+3 2.1E-3 -5.6e-2
Thus, we see that scientific notation is used to express numbers that are either very small or very
large. For example: 120000000 = 1.2E7 and -0.000000025 = -2.5E-7
Character constants: A Character constant consists of a single character enclosed in single quotes.
For example, ‘a’ and ‘@’ are character constants. In computers, characters are stored using the
machine's character set using ASCII codes.
String constants: A string constant is a sequence of characters enclosed in double quotes. So ‘’a’’ is
not the same as ‘a’. The characters comprising the string constant are stored in successive memory
locations. When a string constant is encountered in a C program, the compiler records the address
of the first character and appends a null character (‘ ‘) to the string to mark the end of the string.
Thus, length of a string constant is equal to the number of characters in the string plus 1 (for the
null character). Therefore, the length of the string literal ‘’hello’’ is 6.
Declaring constants: To declare a constant, precede the normal variable declaration const keyword
and assign it a value. For example,
const float pi = 3.14;
The const keyword specifies that the value of pi cannot change. However, another way to designate a
constant is to use the preprocessor command define. Like other preprocessor commands, define is
preceded with a symbol. Although define statements can be placed anywhere in a C program, it is
always recommended that these statements be placed at the beginning of the program to make
them easy to find and modify at a later stage. Look at the example given below which defines the
value of pi using define.
define pi 3.14159
define service_tax 0.12
In these examples, the value of pi will never change but service tax may change. Whenever the value
of the service is altered, it needs to be corrected only in the defined statement. When the
preprocessor reformats the program to be compiled by the compiler, it replaces each defined name
(like pi, service_tax) in the source program with its corresponding value. Hence, it just works like
the Find and - Replace command available in a text editor.
Let us take a look at some rules that need to be applied to a defined statement which defines a
constant.
Rule 1: Constant names are usually written in capital letters to visually distinguish them from other
variable names which are normally written lower case characters Note that this is just a convention
and not a rule.
Rule 2: No blank space is permitted between the symbol and define keyword.
Rule 3: Blank space must be used between define and constant name and between constant name
and constant value.
Rule 4: define is a preprocessor compiler directive and not a statement. Therefore, it does not end
with a semi - colon.
Input/Output Statements in C
This section deals with the basic understanding of the streams involved in accepting input and
printing output in C programs
Streams: A stream is the source data as well as the destination of data. Streams are associated with
a physical device such as a monitor or a file stored on the secondary memory. C uses two forms of
streams - text and binary.
In a text stream, a sequence of characters is divided into lines with each line being terminated with
a new - line character ( n). On the other hand, a binary stream contains data values using their
memory representation. We can do input/output from the keyboard/monitor or from any file but in
this chapter we will assume that the source data is the keyboard and destination of the data is the
monitor.
Formatting Input/Output: C language supports two formatting functions printf and scanf. printf is
used to convert data stored in the program into a text stream for output to the monitor, and scanf is
used to convert the text stream coming from the keyboard to data values and stores them in
program variables.
printf(): The printf function (stands for print formatting) is used to display information required by
the user and also prints the values of the variables. For this, the printf function takes data values,
converts them to a text stream using formatting specification in the control string and passes the
resulting text stream to the standard output. The control string may contain zero or more
conversion specifications, textual data, and control characters to be displayed. Each data value to be
formatted into the text stream is described using a separate conversion specification in the control
string. The specification in the control string describes the data value’s type, size and specific format
information. The syntax of printf function can be given as
printf (“control string”, variable list);
The function accepts two parameters - control string and variable list. The control string may also
contain the text to be printed like instructions to the user, captions, identifiers, or any other text to
make the output readable. In some printf statements you may find only a text string that has to be
displayed on screen. The control characters can also be included in the printf statement. These
control characters include …………………..etc.
The parameter control string in the printf() function is nothing but a C string that contains the text
that has to be written on to the standard output device. After the control string, the function can
have as many additional arguments as specified in the control string. Note that there must be
enough arguments, otherwise the result will be completely unpredictable. However, if by mistake
you specify more number of arguments, the excess arguments will simply be ignored. The prototype
of the control string can be given as follows:
%[flags][width][.precision][length modifier] type specifier
Each control string must begin with a % sign. The % character specifies how the next variable in the
list of variables has to be printed. After % sign follows:
Flags is an optional argument which specifies output justification such as numerical sign, trailing
zeros or octal, decimal, or hexadecimal prefixes. Note that when data is shorter than the specified
width then by default the data is right justified. To justify the data use minus sign (-) in the flags
field.
When the data value to be printed is smaller than the width specified, then padding is used to fill the
unused spaces. By default, the data is padded with blank spaces. If zero is used in the flag field then
the data is padded with zeros. One thing to remember here is that the zero flag is ignored when
used with left justification because adding zeros after a number changes its value.
Width: is an optional argument which specifies the minimum number of positions in the output. If
data needs more space than specified, then printf overrides the width specified by the user.
However, if the number of output characters is smaller than the specified width, then the output
would be justified with blank spaces to the left. Width is a very important field especially when you
have to align output in columns. However, if the user does not mention any width then the output
will take just enough room for data.
Precision is an optional argument which specifies the maximum number of characters to print.
- For integer specifiers (d, i, o, u, x, X): precision flag specifies the minimum number of digits
to be written. However, if the value to be written is higher than this number, the result is
padded with leading zeros. Otherwise, if the value is longer, it is not truncated.
- For character strings, precision specifies the maximum number of characters to be printed.
- For floating point numbers, the precision flag specifies the number of decimal places to be
printed.
Its format can be given as .m, where m specifies the number of decimal digits. When no precision
modifier is specified, printf prints six decimal positions.
When both width and precision fields are used, width must be large enough to contain the integral
value of the number, the decimal point and the number of digits after the decimal point. Therefore, a
conversion specification %7.3f means print a floating point value of maximum 7 digits where 3
digits are alloted for the digits after the decimal point.
Scanf()
The scanf() function stands for scan formatting and is used to read formatted data from the
keyboard. The scanf function takes a text stream from the keyboard, extracts and formats data from
the stream according to a format control string and the stores the data in specified program
variables. The syntax of the scanf() function can be given as:
scanf(“control string”, arg1, arg2, arg3, …………., argn);
The control string specifies the type and format of the data that has to be obtained from the
keyboard and stored in the memory locations pointed by arguments arg1, arg2,....., argn, i.e. the
arguments are actually the variable addresses where are piece of data is to be stored.
The prototype of the control string can be given as:
%[*][width][modifier]type
Here * is an optional argument that suppresses assignment of the input field, ie, it indicates that
data should be read from the stream but ignored (not stored in the memory location).
Width is an optional argument that specifies the maximum number of characters to be read.
However, fewer characters will be read if the scanf function encounters a white space or an
inconvertible character because the moment scanf function encounters a white space character it
will stop processing further.
Modifier is an optional argument that can be h, l, or L for the data pointed by the corresponding
additional arguments. Modifier h is used for short int or unsigned short int, l is used for long int,
unsigned long int, or double values. Finally, L is used for long double data values.
Type specifies the type of data that has to be read. It also indicates how this data is expected to be
read from the user. The type specifiers for scanf function are the same as given for printf() function.
The scanf function ignores any blank spaces, tabs and newlines entered by the user. The function
simply returns the number of input fields successfully scanned and stored.
Rule 2: Every variable that has to be processed must have a conversion specification associated with
it . Therefore, the following scanf statement will generate an error as num3 has no conversion
specification associated with it.
scanf(“%d %d”, &num1, &num2, &num3);
Rule 3: There must be a variable address for each conversion specification. Therefore, the following
scanf statement will generate an error as no variable address is given for the third conversion
specification.
scanf (“%d %d %d”, &num1, &num2);
Remember that the ampersand operator (&) before each variable name specifies the address of that
variable name.
Rule4: An error will be generated if the format string is ended with a white space character.
Rule5: The data entered by the user must match the character specified in the control string (except
white space or a conversion specification), otherwise an error will be generated and scanf will stop
its processing. For Example, consider the following scanf statement.
sanf(“%d / %d”, &num1, &num2);
Here the slash in the control string is neither a white space character nor a part of the conversion
specification, so the users must enter data of the form 21/46.
Rule8: When the field width specifier is used, it should be large enough to contain the input data
size.