Module1 Chapter4
Module1 Chapter4
Introduction to C
4.1 Introduction
✓ C is a high-level programming language.
✓ 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 as C++ and Java are
also based on C which means you will be able to learn them more easily in the future.
4.2 Characteristics of C
C 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
4.3 Uses of C
C is a very simple language that is widely used by software professionals around the globe. The
uses of C language can be summarized as follows:
✓ C is a very simple language that is widely used by software professionals around the globe.
✓ C is primarily used for system programming. The portability, efficiency, the ability to access
specific hardware addresses and low runtime.
✓ The compiler, libraries and interpreters of other programming languages are often
implemented in C.
[Comments]
[Preprocessor Directives]
[Global Declarations]
[Function Declarations]
[Function Definitions]
main()
{
[Declaration Section]
[Executable Section]
}
1. Comments
✓ At the beginning of each program is a comment with a short description of the problem to
be solved.
✓ We can use the comments anywhere in the program.
✓ The comments section is optional.
Ex: 1. /* Program1: To find the sum of two numbers*/
2. // Program2: To calculate the area and perimeter of circle
✓ The symbol /* and ends with */ represents the multiline comment.
✓ The symbol // can also be used for representing single line comment.
2. Preprocessor directives
✓ The preprocessor statements start with # symbol.
✓ These statements instruct the compiler to include some of the files in the beginning of the
program.
Ex: #include<stdio.h>
#include<math.h>
are the files that the compiler includes in the beginning of the program.
✓ The line containing #include<stdio.h> tells the compiler to allow our program to perform
standard input and output ‘stdio’ operations.
3. Global Declarations
✓ The variables that are declared above (before) the main program are called global variables.
✓ The global variables can be accessed anywhere in the main program and in all the other
functions.
7. Declaration section
✓ The variables that are used inside the function should be declared in the declaration
section.
✓ For example, consider the declaration shown below:
int sum=0;
int a;
float b;
Here, the variable sum is declared as an integer variable and it is initialized to zero. The variable
a is declared as an integer variable whereas the variable b is declared as a floating point
variable.
8. Executable section
✓ They represent the instructions given to the computer to perform a specific task.
Mr. Balaraju G. Asst Professor, Dept of AI&ML, BMSIT&M 4
✓ The instructions can be input/output statements, expressions to be evaluated, simple
assignment statements, control statements such as if statement, for statement etc.
✓ Each executable statement ends with “;”.
2. Header Files
✓ They have an extension '.h'.
✓ They contain the C function declarations and macro definitions that are shared between
various source files.
2. At times the programmer may want to change or add the subroutines and reflect those
changes in all the programs. For doing this, he will have to only change the source file for the
subroutines, recompile the source code and then recompile and re-link the program.
This tells us that including a header file will make it easier at all levels of the program. If we need
to modify anything then changes are made only in the subroutines after which all the changes will
be reflected.
✓ The header files are added at the start of the source code so that they can be used by more than
one function of the same file.
3. Object files
✓ They are the files that are generated by the compiler as the source code file is processed.
✓ These files generally contain the binary code of the function definitions.
✓ The object file is used by the linker for producing an executable file for combining the object
files together. It has a '.o' extension.
4. Executable file
✓ This file is generated by the linker.
✓ Various object files are linked by the linker for producing a binary file which will be
executed directly.
✓ They have an '.exe' extension.
4.8 C Tokens
✓ Tokens are the basic building blocks in C language.
✓ A token is the smallest individual unit in a C program.
✓ This means that a program is constructed using a combination of these tokens.
✓ There are six main types of tokens in C as shown below:
1. Keywords:
✓ Keywords are the tokens which have predefined meaning in C language, whose meaning
cannot be changed by the user.
✓ All keywords are basically a sequence of characters that have a fixed meaning.
✓ They are also called reserved words.
✓ C Keywords are case sensitive. Therefore all C keywords must be written in small letters.
int, float, if, while, void etc are valid keywords.
Int, Float, IF, VOID etc are invalid keywords. (They are written using capital letters).
List of keywords:
✓ There are total 32 keywords in C language as shown below.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
3. Constants: A constant is a data item which will not change during the execution of a
program.
Ex: #define PI 3.142
4. Strings: String is an array of characters and terminated by NULL character which is denoted by
‘\0’.
Ex: char name[21];
5. Operators: Operator is a symbol (or token) that specifies the operation to be performed on
various types of data.
Ex: Arithmetic operators (+,-,*,/), Relational operators (&&,||,!), Logical operators ( >,>=,<,<=)
and Assignment operator (=) etc.
6. Special characters: [ ], { }, ( ) etc. used in the program to execute the code correctly and helps
to write a complex codes by special symbols.
4.10 Identifiers
✓ Identifiers help us to identify data and other objects in the program.
✓ Identifiers are basically the names given to program elements such as variables, arrays, and
functions.
✓ Identifiers may consist of sequence of letters, numerals, or underscores.
i. int:
✓ An int is a keyword which is used for defining integers in C language.
✓ Using int the programmer can inform the compiler that the data associated with this
should be treated as integer.
✓ Using ‘int’ compiler determines the size of the data (2 bytes) and reserve space in memory
to store the data.
✓ Integer data types namely:
1. short int 2. int 3.long int
Type Size
short int 2 bytes
int 2 bytes
long int 4 bytes
Ex: int a,b,c;
ii. float:
✓ A float is a keyword which is used to define floating point numbers in C language.
✓ The programmer can inform the compiler that the data associated with this keyword
should be treated as floating point number.
✓ The default precision of floating point number is 6 digits after dot(.).
Size of float
16-bit Machine 4 bytes
32-bit Machine 8 bytes
iii. double:
✓ It is a keyword which is used to define long floating point numbers in C language.
✓ The default precision of floating point number is 14 digits after dot(.).
Size of double
16-bit Machine 8 bytes
32-bit Machine 16 bytes
Ex: double p,q,r;
Ex: char ch; // ch variable stores a single character Ex: ch= ‘a’;
char s[20]; // s variable stores a string(group of characters) Ex: s= “jitdvg”;
v. void:
✓ It is an empty data type, since no value is associated with this data type.
✓ It does not occupy any space in the memory.
Size of void Range
16/32-bit Machine 0 No value
}
It is primarily used in three cases:
✓ To specify the return type of a function (when the function returns no value)
✓ To specify the parameters of the function (when the function accepts no arguments from the
caller)
✓ To create generic pointers.
4.12 Constants
✓ A constant is a data item which will not change during the execution of a program.
or
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.
✓ C allows the programmer to specify constants of integer type, floating point type, character
type, and string type.
✓ The constants cannot be modified in the program.
3. 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 machines character set using ASCII codes. All escape
sequences mentioned in Table 4.1 are also character constants.
4.13 Variable
✓ A variable is a name given to a memory location within the computer that can hold one
value at a time.
OR
A variable is a data item whose value changes during the execution of program.
✓ Every variable should be associated with type, size and value.
✓ Whenever a new value is placed into a variable, it replaces the previous value.
1. 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.
✓ 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.
2. 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 (‘&’).
✓ 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, but ‘2’ is considered character not an integer.
Mr. Balaraju G. Asst Professor, Dept of AI&ML, BMSIT&M 15
4.13.3 Declaring/Defining a Variable
✓ Each variable to be used in the program must be declared.
✓ ‘Declaration’ tells the computer which storage locations or variables to use in the program.
✓ It is a method of informing the compiler to reserve the memory space for the program
data based on the type of variables.
✓ 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.
Syntax: datatype v ,v ,…….,v ;
1 2 n
Where, datatype: is the type of the data to be stored in memory location. (int,float,char,double)
var_name: name of a variable
= is assignment operator
data: is the value to be stored in memory associated with variable var_name.
Ex: int a=10;
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.
Flags
✓ Flag is an optional argument which specifies output justifications such as numerical sign,
trailing zeros or octal, decimal or hexadecimal prefixes.
Types of flags:
- : Left justify
+ : Display data with numeric sign
# : Provide additional specifier o,O,X,0,0x
0 : Left-padding with zeros
Width
✓ It is an optional argument which specifies minimum number of positions in the output.
Precision
✓ Precision is an optional argument which specifies the maximum number of characters to print.
Length modifiers
Table 4.2 Length modifiers for printf()
Type specifiers
✓ Type specifiers are used to define the type and interpretation of the value of the corresponding
argument.
2. 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 the data
from the stream according to a format control string and then stores the data in a
specified program variables.
✓ Syntax of the scanf() function:
scanf ( “control string”, arg1, arg2, arg3,….. argn);
✓ 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 arg1, arg2, …, argn,i.e., arguments are
actually the variable addresses where each piece of data is to be stored.
✓ Prototype of the control string can be given as:
%[*][width][modifier] type
✓ Here the * is an optional argument which indicates that data should be read from the stream, but
ignored (not stored in memory location).
Width
✓ This is an optional argument that specifies the maximum number of characters to be read.
✓ Fewer characters are read if scanf() encounters a white space and will stop processing further.
Modifier
✓ It is an optional argument that can be h, l, or L for the data pointed by 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
✓ It specifies the type of data that has to be read.
✓ The type specifiers for scanf( ) function are same as that of printf ( ) function.
✓ The scanf function ignores any blank spaces, tabs and newlines entered by the user.
✓ The address of the variable is denoted by an ‘&’ sign followed by the name of the variable.
Rule 3: There must be a variable address for each conversion specification. Therefore following
scanf will generate an error as no variable address is given for the third conversion specification.
scanf(%d %d %d”, &num1, &num2);
Rule 4: An error will be generated if the format string is ended with the white space character.
Rule 5: The data entered by the user must match the character specified in the control string,
otherwise, an error will be generated and scanf will stop its processing.
For example, consider the following scanf of statement
scanf(“%d / %d”, &num1, &num2);
Here the slash in the constant 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.
Rule 7: Any unread data value will be considered as a part of data input in the next call to the
scanf.
Rule 8: When the field width specifier is used, it should be large enough to contain the input data
size.
Examples of printf/scanf:
1. Code to input values in variables of different data types:
▪ int num;
scanf(“%d”,&num);
▪ float salary;
scanf(“%f”, &salary);
▪ char ch;
scanf(“%c”,&ch);
▪ char str[10];
scanf(“%s”, str);
soprotection.com