Module 1 (PART 2) - Introduction To C Language

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

COMPUTER

FUNDAMENTALS AND
PROGRAMMING IN C

MODULE 1- INTRODUCTION TO C
Module 1- Introduction to C

INTRODUCTION TO C
 Introduction

 C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories.


 C was initially developed for writing system software.
 Today, C has become a popular language and various software programs are written using
this language.
 Many other commonly used programming languages such as C++ and Java are also based
on C .
 Characteristics of C
 C is a robust whose rich set of built-in functions and operators can be used to
write complex programs.
 Some of the characteristics of C are listed below:
 A high level programming language 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.
 Makes extensive use of function calls.
 C is well suited for structured programming.
- In this programming approach, C enables the user to think of the problem in
terms of functions or modules where the collection of all the modules makes up a
complete program.
 Unlike PASCAL it supports loose typing ( as a character can be treated as an integer
and vice versa).
 Stable language – ANSI C was created in 1983 and since then it has not been revised.
 Quick language –A well written C programming is likely to be quick or quicker than
a program written in any other language.
 Facilitates low level ( bit wise) programming .
 Supports pointers to refer computer memory, array, structures and functions.
 C is a core language as many other programming languages such as C++, Java or Perl
are based on C.
 C is a portable language - a C program written for one computer can be run on
another computer with little or no modification.
 C is an extensible language as it enables the user to add his/her functions to the C
library.

Dept of CSE, KSSEM Page 2


Module 1- Introduction to C

 Uses of C
 C language is primarily used for system programming.
 The portability, efficiency, the ability to access specific hardware addresses and
low run time demand on system resources makes 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 implemented in C.
 For portability and convenience reasons, C is sometimes used as an intermediate
language by implementations of other languages.
 Example of compilers which use C this way are BitC, Gambit, the Glasgow
Haskell Compiler, Squeak, and Vala.
 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 statements in a C program are written in a logical sequence to perform a
specific task.
 Execution of a C program begins at the main() function.

Figure 8.2 – Structure of a C Program

Dept of CSE, KSSEM Page 3


Module 1- Introduction to C

 The preprocessor directives contain special instructions that indicate how to prepare
the program for compilation.
 One of the most commonly used pre-processor commands is include which tells the
compiler that to execute the program, some information is needed from the specified
header file.
 All functions (including main()) are divided into two parts:
 Declaration section.
 Statement section .
 The declaration section precedes the statements and is used to describe the data that will
be used in the function.
 Note that the data declared within a function are known as local declaration as that
data will be visible only within that function.
 The statement section in a function contains the code that manipulates the data to
perform a specified task.
 A C program can have any number of functions depending on the tasks that have to be
performed.
 Each functions can have any number of statements arranged according to a specific
meaningful sequence.

 WRITING THE FIRST C PROGRAM


To write a C program, we need to write the code.
Steps to compile the C program:
1. Open a text editor.
2. If you are a windows user, you may use Notepad.
3. If you prefer working on UNIX/Linux, you can use emacs or vi editor.
4. Once the text editor is opened on your screen, type the following statements:

// This is my first program in C

#include<stdio.h>
int main()
{
printf(“Welcome to the world of C”);
return 0;
}

Output : Welcome to the world of C

Dept of CSE, KSSEM Page 4


Module 1- Introduction to C

 #include<stdio.h> - All pre-processor commands starts with the # symbol.


- The #include statement tells the compiler to include the standard input /
output(I/O) library or header file (stdio.h) in the program.
- The standard input/output header files contains functions for input and output
of data like reading values from the keyboard or printing the results on the
screen.
 int main() – is the return value of the main function.
- After all the statements in the program, the last statement of the program will
return an integer value to the operating system.
- The two curly braces {} are used to group all the related statements of the
main function.
- All the statements between the braces form the function body.
- The function body contains a set of instructions to perform the given task.
 printf(“\n Welcome to the world of C”);
- The printf function is defined in the stdio.h file.
- It is used to print text on the screen.
- The message that has to be displayed on the screen is enclosed within double
quotes.
- The „\n‟ is an escape sequence and represent a newline character.
- „\n‟ is used to print text on a new line on the screen.
 return 0;
- This is a return command that is used to return value 0 to the operating system
to give an indication that there were no errors during the execution of the
program.
 Commands to execute a C program
 Once you have written all the statements using a text editor, save the text
file as first.c
 If you are a Windows user, then open the command prompt by clicking
Start->Run, type „command‟ and click OK.
 Using the command prompt, change to the directory in which you have
saved your file and then type:
C:\>tc first.c
 If you are working on UNIX/Linux operating system, then exit the text editor
and type:
$cc first.c -ofirst

Dept of CSE, KSSEM Page 5


Module 1- Introduction to C

 Where -o is the output filename. If you leave out the -o, then the file name
a.out is used.
 Files Used in a C Program
- Every C program has four kinds of the files associated with it.

Figure 8.3- Files in a C program

 Source Code Files


 The source code file contains the source code of the program.
 The file extension of any C source code file is “.c”.
 This file contains C source code that defines the main function and may be other
functions.
 The main() is the starting point of execution when you successfully compile and
run the program.
 A C program in general may include even other source code files (with the file
extension .c).
 Header Files
 When working with large projects , it is often desirable to make sub-routines and store
them in a different file known as header file.
 The advantage of header files can be realized in the following cases:
1. The programmer wants to use the same subroutines in different programs.
2. The programmer wants to change, or add, subroutines, and have those changes be
reflected in all other programs.
 Conventionally, header files names ends with a “ .h” extension and its name can use only
letters, digits, dashes, and underscores.
 Standard header files
Examples of standard header files include the following:
 string.h – for string handling functions.
 stdlib.h – for some miscellaneous functions.
 stdio.h - for standardized input and output functions.
 math.h – for mathematical functions.
 alloc.h – for dynamic memory allocations.
 conio.h - for clearing the screen.

Dept of CSE, KSSEM Page 6


Module 1- Introduction to C

 Object Files
 Object files 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 this object file 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 File
 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 Windows operating system, the executable files have “.exe” extension.

 Compiling and Executing a C Program


 The compilation process is done in two steps:
 In the first step, the pre processor program reads the source file as text, and
produces another text file as output.
 Source code lines which begin with the hash symbol are actually not written in
C but in the pre processor language.
 The output of the pre processor is a text file which does not contain any pre
processor 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 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.

Figure 8.6- Modular Programming - the complete compilation and execution process

Dept of CSE, KSSEM Page 7


Module 1- Introduction to C

 Comments
● It is a good programming practice to place some comments in the code to help the reader
understand the code clearly.
● Comments are just a way of explaining what a program does.
● It is merely an internal program documentation.
● The compiler ignores the comments when forming the object file.
● This means that the comments are non-executable statements.
● C supports two types of commenting:
 // is used to comment a single statement.
 This is known as a line comment.
 A line comment can be placed anywhere on the line.
 It does not require to be specifically ended as the end of the line automatically
ends the line.
 /* is used to comment multiple statements.
 A /* is ended with */ and all statements that lie within these
characters are commented.
The following code shows the way in which we can make use of comments in our
first program.
/* Author : Reema Thareja
Description : To print „Welcome to the world of C‟ on the screen */
#include <stdio.h>
int main()
{
// prints message
printf (“\n Welcome to the world of C”);
return 0; //returns a value 0 to the
// operating system
}

Output : Welcome to the world of C

 Since comments are not executed by the compiler, they do not affect the
execution speed and the size of the compiled program.
 Therefore, use comments liberally in your programs so that other users can
understand the operations of the program and will serve as an aid to
debugging and testing.

Dept of CSE, KSSEM Page 8


Module 1- Introduction to C

 Keywords
 C has a set of 32 reserved words often known as keywords.
 All keywords are basically a sequence of characters that have a fixed meaning.
 By convention all keywords must be written in lower case (small) letters.

auto break case char const continue default


double else enum extern float for goto
int long register return short signed sizeof
struct switch typedef union unsigned void volatile
do if static while

Table 8.2 – Keywords in C language

 Identifiers
 Identifiers are names given to program elements such as variables, arrays and functions.
 Rules for forming identifier name are listed below:
- It cannot include any special characters or punctuation marks (like #, $, ^, ?, ., etc) except
the underscore"_".
- There cannot be two successive underscores.
- Keywords cannot be used as identifiers.
- The names are case sensitive. So, example, “FIRST” is different from “first” and “First”.
- It must begin with an alphabet or an underscore.
- It can be of any reasonable length.
- It should not contain more than 31 characters.
 Examples of valid identifiers include the following:
roll_number, marks, name, emp_number, basic_pay, HRA, DA, dept_code.
 Example for invalid identifiers include the following:
23_student, #marks, @name, #emp_number, basic.pay, -HRA, (DA), &dept_code,
auto.
 Basic Data Types in C
C language provides very few basic data types. The following table list the data
types used in C.

Dept of CSE, KSSEM Page 9


Module 1- Introduction to C

Table 8.4 – Detailed list of data types

 The void type holds 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.

 Variables
 A variable is defined as a meaningful name given to the data storage location
in computer memory.
 When using a variable, we actually refer to address of the memory where the
data is stored.
 C language supports two basic kinds of variables:
 Numeric variables can be used to store either integer values or floating point
values.
 While an integer value is a whole numbers without a fraction part or decimal
point, a floating point number, can have a decimal point in them.

Dept of CSE, KSSEM Page 10


Module 1- Introduction to C

 Numeric values may also be associated with modifiers like short, long, signed
and unsigned.
 By default, C automatically a numeric variable signed.
 Character variables can include any letter from the alphabet or from the ASCII
chart and numbers 0 – 9 that are put between single quotes.

Figure : Categories of Variables


 The difference between the signed and unsigned numeric variables is that signed
variables can be either negative or positive, but unsigned variables can only be
positive.
 Using the 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.

 Declaring Variables
 To declare a variable specify data type of the variable followed by its
name.
 Variable names should always be meaningful and must reflect the purpose
of their usage in the program.
 Variable declaration always ends with a semicolon.
 Example:
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short;
int acc_no;
 C allows multiple variables of the same type to be declared in one
statement.
 The following statement is absolutely legal in C:

Dept of CSE, KSSEM Page 11


Module 1- Introduction to C

float temp_in_celsius, temp_in_farenheit;


 In C , variables are declared at three basic places as follows:
 When a variable is declared inside a function it is known as a
local variable.
 When a variable is declared in the definition of function
parameters, it is known as formal parameters.
 When the variable is declared outside all functions, it is known as
a global variables.

 Initializing Variables
 While declaring the variables, we can also initialize with some value.
Example: int emp_num=7;
float salary=5000;
char grade=‟A‟;
double balance_amount=100000000;
 The initializer applies only to the variable defined immediately before it.
Therefore, the statement:
int count, flag=1; initializes the variable flag and not count.
 If you want both the variables to be declared in a single statement then
write,
int count=0, flag=1;
 When variables are declared but not initialized they usually contains a
garbage values.
 Constants
 Constants are identifiers whose value does not change.
 Constants are used to define fixed values like 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 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 set of digits.
 For Example-1, 34, 567, 8907 are valid integer constants.

Dept of CSE, KSSEM Page 12


Module 1- Introduction to C

 For a long integer constant, the literal is succeeded with either „L‟ or
„l‟(Example – 1234567L)
 Integer literals can be expressed in decimal, octal, hexadecimal notation.
 Decimal integers consists 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.
 Following integer constants are not valid in C:
123 456 12,34,567 $123
 An integer constant preceded by 0 is an octal number.
 Octal integer consists of set of digits 0 through 7.
 Examples of Octal integers include- 012, 0, 01234.
 An integer constant is expressed in hexadecimal notation if it is
preceded with 0x or 0X.
 Hexadecimal numbers contain digits from 0-9 and alphabets A through
F.
 The alphabets A through F represent numbers 10 through 15.
 Example – decimal 72 is equivalent to 0110 in octal notation and 0x48
in hexadecimal notation.
 Some examples of hexadecimal integers are 0X12 , 0x7F, 0xABCD.

 Floating Pointing Constant


 Integer numbers are inadequate to express the numbers that have a
fractional part.
 A floating point constant therefore consists of an integer part, a decimal
point, a fractional part, and an exponent field containing an e or E(e
means exponent) followed by an integer where the fraction part and
integer part are sequence of digits.
 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 such as 0.07 is treated as type double by default.
 To make it a float type literal, you must specify it using suffix „F‟ or „f‟.
 Some valid floating point literals are 0.02F, 0.34f, 3.141592654L, 0.002146
and 2.146E-3.
 A floating point number may also be expressed in scientific notation.

Dept of CSE, KSSEM Page 13


Module 1- Introduction to C

 In this notation, the mantissa is either a floating point number or an


integer and exponent is an integer with an optional plus or minus sign.
 The following are valid floating point numbers:
0.5e2 14E-2 1.2e+3 2.1E-3 -5.6e-2 .
 Thus, scientific notation is used to express numbers that are either very
small or very large.
 Example-120000007=1.2E8, and -0.00000025=-2.5E-8.
 Character Constant
 A character constant consists of a single character enclosed in single
quotes.
 For example-„a‟, „@‟ are character constants.
 In computers, characters are stored using the machine‟s character set
using ASCII codes.

 String Constants
 A string 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(„\0‟) to the string to mark the end of the string.
 Declaring Constants
 To declare a constant, precede the normal variable declaration with const
keyword and assign it a value.
 Example- const float pi=3.14;
 The const keyword specifies that the value of pi cannot change.
 Another way to designate a constant is to use the pre-processor command
define.
 Like other pre-processor commands, it 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.
 Let us look at the following example which defines values using define.
#define PI 3.14159
#define service_tax 0.12
 In these examples, the values of PI and service_tax may change.

Dept of CSE, KSSEM Page 14


Module 1- Introduction to C

 Whenever the values are altered, it needs to be corrected only in


the define statement.
 When the preprocessor reformats the program to be compiled by the
compiler, it replaces each defined name such as PI, service_tax in the
source program with its corresponding value.
 Let us take a look at some rules that need to be applied to a #define
statement which defines a constant.
 Rule 1 – Constant names are usually written in capital letters to
visually distinguish from other variable names which are normally
written in lower case characters.
 Rule 2 - No blank spaces are permitted in between # 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 pre-processor compiler directive and not a
statement. Therefore, it does not end with a semi-colon.

 Input / Output Statements

 A stream acts in two ways.


 It is the source of data as well as the destination of data.
 C programs input data and output data from a stream.
 Streams are associated with a physical device such as the monitor or with a file
stored on the secondary memory.
 In a text stream, 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.
 Although, we can do input/output from the keyboard / monitor or from any file.

Figure 8.9- Streams in C

Dept of CSE, KSSEM Page 15


Module 1- Introduction to C

Figure 8.10 – Input and Output Streams in C

 Formatting Input / Output


 C language supports two formatting functions:
 printf
 scanf
 printf is used to convert data stored in the program into a text stream for output
to the monitor.
 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 is used to display information required to the user and also prints the
values of the variables.
 Its syntax can be given as:
o printf (“conversion string”, variable list);
 The parameter control string is a C string that contains the text that has to be written on to
the standard output device.
 The function accepts two parameters- control string and variable list.
 The control string may also contain text to be printed such as instructions to the user,
captions, identifiers and 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- \n, \t, \r, \a.
 The prototype of the control string can be given as below:
%[flags][width][.precision][length]specifier
 Each control string must begin with a %sign .
 The % character specifies how the next variables in the list of variables has to be printed.

Dept of CSE, KSSEM Page 16


Module 1- Introduction to C

 After % sign, follows the following parameters:


 Flags- specify output justification such as decimal point, numerical sign, trailing zeros, or
octal, decimal or hexadecimal prefixes.
 Following table shows the different types of flags with their description:

Table 8.5- Flags in printf()

 Width- specifies the minimum number of characters to print after being padded with
zeros or blank spaces that is it specifies the minimum number of positions in the output.
 Precision- 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. If the value to be written is shorter 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.
 Specifiers- is used to define the type and the interpretations of the value of the
corresponding argument.

Figure 8.7-Specifier field in printf()

Dept of CSE, KSSEM Page 17


Module 1- Introduction to C

 Note that if the user specifiers a wrong specifier, then some strange things will
be seen on the screen and the error might propagate to other values in the printf
list.

A simple printf statement is:


printf(“Welcome to the world of C language”);
 Other examples are as follows:
printf(“\n Result : %d%c%f ”, 12,’a’,2.3);
Result: 12a2.3
printf(“\n Result: %d %c %f “, 12,’a’, 2.3);
Result:12 a 2.3
 scanf()
 The scanf() is used to read formatted data from the keyboard.
 The syntax of the scanf() can be given as,

scanf (“control string”, arg1, arg2, ………….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 the arguments arg1,
arg2,…, argn.
 Prototype of the control string:
[=%[*][width][modifiers]type=]
 * is an optional argument that suppresses assignment of the input field.
 That is, 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.
 modifiers 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 long double data values.
 Type – 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 listed in the below table:

Dept of CSE, KSSEM Page 18


Module 1- Introduction to C

Table 8.8- Flag specifiers for scanf ()

Example for printf() and scanf()

int num;

float fnum;

char ch, str[10];

double dnum;

short snum;

long int lnum;

printf(“\n Enter the values : “);

scanf("%d %f %c %s %e %hd %ld", &num, &fnum, &ch, str, &dnum, &snum, &lnum);

printf("\n num = %d \n fnum = %.2f \n ch = %c \n str = %s \n dnum = %e \n snum = %hd \n lnum =


%ld", num, fnum, ch, str, dnum, snum, lnum);

Dept of CSE, KSSEM Page 19

You might also like