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

Module 1

Uploaded by

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

Module 1

Uploaded by

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

Module 1

Introduction to C: Introduction to computers, input and output devices, designing efficient programs.

Introduction to C, Structure of C program, Files used in a C program, Compilers, Compiling and


executing C programs, variables, constants, Input/output statements in C

1. DESIGNING EFFICIENT PROGRAMS

Algorithm
Def 1: Step-by-step procedure to solve a problem using a computer is called an algorithm.
Def 2: In Computer Science, A finite sequence of unambiguous steps to solve a problem is called an
algorithm.
Example 1: Algorithm for adding any two numbers.

Step 1: Start
Step 2: Input the two numbers to be added and assign them to variables X & Y respectively.
Step 3: Compute value Z such that Z = X+ Y
Step 4: Display the value of Z.
Step 5: Stop

Example 2: Algorithm for checking a given number is +ve or –ve (Assume 0 is positive)

Step 1: Start
Step 2: Input the number and assign it to variable X.
Step 3: Check if X is less than 0, then display “ The given number is –ve”. Otherwise display
“ The given number is +ve”
Step 4: Stop

Flowchart

Pictorial representation of an algorithm is known as flowchart. It represents the flow of execution of


instructions in an algorithm by a computer, using graphical notations.

22POP12 - Principle of Programming Using C Page 1


Basic notations used in a flow chart

22POP12 - Principle of Programming Using C Page 2


1. Flow chart for addition of two numbers:

2. Flowchart to check if a given number is +ve or –ve or zero

22POP12 - Principle of Programming Using C Page 3


2. INTRODUCTION TO C

 C was developed in the early 1970s by Dennis Ritchie at Bell Laboratories to be used by UNIX
operating system.
 It was named ‘C’ because many of its features were derived from an language called ‘B’.
 C was initially developed for writing system software
 Today, C has become a popular programming 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

Background

 C is derived from ALGOL. It was introduced in 1960s led the way for the development of
structured programming concept.
 In 1967, Martin Richards developed a language called BCPL (Basic Combine Programming
Language). It is basically a type-less language (no concept of data-types).
 In 1970, Ken-Thompson developed a language called B. It was used to develop the first version
of UNIX.
 C was developed by Dennis Ritchie in 1972 that took the concept from ALGOL, BCPL and B.
In addition to that C also supports the concepts of data types.
 C was documented and popularized in the book The C programming language by Brian W.
Kernighan and Dennis Ritchie in 1978. This book was popular and the language came to known
as ‘K & RC’.

22POP12 - Principle of Programming Using C Page 4


 In 1983, the American National Institute (ANSI) started working on defining standards for C.
This standard was approved in 1989 and came to known as ANSI C.
 In 1990, International Standard Organization (ISO) adopted the ANSI standard. This version of
C came to known as C89.
 In 1995, some changes were made to C89, the new modified version was known as C95.
 In 1995, some changes were made to C95, the new modified version was known as C99.

Characteristics of C

1. A high level programming language enables the programmer to concentrate on the problem
and not worry about the machine code on which the program would be run.
2. Small size. C has only 32 keywords. This makes it relatively easy to learn.
3. Makes extensive use of function calls.
4. C is well suited for structured programming. In this programming approach, C enables the user
to think of problems in terms of functions/modules where the collection of all the modules
makes up a complete program.
5. It supports loose typing (as a character can be treated as an integer and vice versa)
6. Stable language. ANSI C was created in 1983 and since then it has not been revised.
7. Quick language
8. Facilitates low level (bitwise) programming.
9. Supports pointers to refer computer memory, array, structures and functions.
10. C is a core language. Other programming languages are based on C.
11. 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.
12. C is an extensible language as it enables the user to add his own functions to the C library.

Uses of C

 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 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.

22POP12 - Principle of Programming Using C Page 5


 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

3. STRUCTURE OF C PROGRAM
A C program is composed of preprocessor commands, a global declaration and one or more functions.

Pre-processor directives

It contains special instructions that indicate how to prepare the program for compilation. One of the
most important and commonly used preprocessor commands is include which tells the compiler that to
execute the program, some information is needed from the specified header file.

Global Declaration Section

The global variables that can be used anywhere in the program are declared in the global declaration
section. This section also declares the user defined functions.

22POP12 - Principle of Programming Using C Page 6


main() Function Section

A C program contains one or more function, where a function is defined as a group of C statements
that are executed together. The statements in a C program 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 are divided into two parts – the declaration section and statement section.
 The declaration part declares all the variables that are used in the executable part. 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.
These two parts must be written in between the opening and closing braces { }. Each statement in the
declaration and statement part must end with a semicolon (;). The execution of program starts at
opening braces and ends at closing braces. All the statement between the braces forms the function
body. That contains a set of instructions to perform the given task.

Writing the first C program

22POP12 - Principle of Programming Using C Page 7


int main()

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.

Printf(“\nWelcome to the world of C”);

The printf function is defined in the stdio.h file and is used to print text on the screen. The message
that has to be displayed on the screen is enclosed within double quotes and put inside brackets.
The ‘\n’ is an escape sequence and represents a newline character. It is used to print the message on a
new line on the screen.

return 0;

This is a return command that is used to return the value 0 to the operating system to give an
indication that there were no errors during the execution of the program.

Escape Sequences (Backslash character constants)

Sometimes, it is necessary to use characters which cannot be typed or have special meaning in
C programming. For example: newline (enter), tab etc. In order to use these characters, escape
sequences are used.
For example: \n is used for newlines. The backslash ( \ )causes "escape" (or deviation) from the
normal way the characters are interpreted by the compiler. So instead of the character ‘n’, the meaning
of \n is a newline.

22POP12 - Principle of Programming Using C Page 8


4. FILES USED IN A C PROGRAM

1. Source File

It contains the source code of the program. The file extension of C source code file is “.c”. This file
contains C source code that defines the main function and maybe other functions. The main() is the
starting point of execution when you successfully compile and run the program.

2. Header File

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 when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those changes be
reflected in all other programs.

22POP12 - Principle of Programming Using C Page 9


Conventionally, header files names ends with a “.h”extension and its name can use only letters,
digits, dashes, and underscores. Although some standard header files are available in C, but the
programmer may also create his own user defined header files.

Standard Header Files

3. 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 of 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.

4. 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.

5. COMPILING AND EXECUTING C PROGRAMS

C is compiled language. So once the C program is written, you must run it through a C compiler.
 The source file (human-readable) is first processed with special program called a Compiler
that translate the source code into an object code. The object code contains the machine
instructions for the CPU. However, even the object file is not an executable file.
 Therefore, in the next step the object file is processed with another special program called a
linker. That translates the object file into executable file (machine-readable). The output of
the linker is an executable or runnable file.

22POP12 - Principle of Programming Using C Page 10


There is different compiler for every individual language; the same linker is used for object file
regardless of the original language in which the new program was written.

6. USING COMMENTS

It helps the reader to understand the code clearly. Comments are just a way of explaining what a
program does. 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 and 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.

7. KEYWORDS

 Keywords are the reserved words in C whose meanings are fixed by the language.
 Keywords are case sensitive. i.e. while and While are not the same.
 In C, All keywords are of lowercase.
 Keywords cannot be used as variable names. ( E.g. int char = 10; is not allowed in C since
char is keyword)
 There are 32 keyword in ANSI C:

22POP12 - Principle of Programming Using C Page 11


8. IDENTIFIERS
Names defined by programmers in a program are called Identifiers. These names can be variable
names, function names etc.
E.g.: x, y, sum, add() etc.
Rules for writing an identifier
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and
underscores.
2. The first letter of an identifier should be either a letter or an underscore. However, it is
discouraged to start an identifier name with an underscore.
3. There is no rule on the length of an identifier. However, the first 31 characters of identifiers are
discriminated by the compiler.(Depends on the compiler)
4. Cannot use a keyword as an identifier.
5. Identifiers must not contain white spaces. ( student name is is not valid identifier whereas
student_name is valid)

9. DATA TYPES

Every data used in a C program must have a type associated with it. That is referred to as data type.
E.g: 25 is Integer data type. 2.53 is floating point type etc.
Since data is normally stored in variables, we specify the data type of a variable when we declare the
variable name (i.e creating a variable). Hence language has defined a set of DATA TYPES that can be
used to declare variables.
The data type categories supported by ANSI C are:
1. Primary(Fundamental) data types
2. Derived Data types
22POP12 - Principle of Programming Using C Page 12
3. User-defined data types
Primary Data Types
The 5 Primary Data Types are following

(The difference between signed and unsigned numeric variable is that signed variables can be either
negative or positive but unsigned variable can be only positive.)

22POP12 - Principle of Programming Using C Page 13


10. VRIABLES
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.
1. 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. Numeric values may also be associated with
modifiers like short, long, signed and unsigned. By default, C automatically a numeric variable
signed.
2. Character variables can include any letter from the alphabet or from the ASCII chart and
numbers 0 – 9 that are put between single quotes.

Declaring Variable
To declare a variable specify data type of the variable followed by its name. The data type indicates
the kind of data that the variable will store. Variable names should always be meaningful and must
reflect the purpose of their usage in the program.
Variable declaration always ends with a semicolon.
data_type variable_name;
Example,
int emp_num;
float salary;
char grade;
double balance_amount;

22POP12 - Principle of Programming Using C Page 14


Initializing Variable
While declaring the variable, we can also initialize them with some value,
For example,
int emp_num = 7;
float salary = 5000;
char grde =’A’;

11. COSTANTS

Constants are fixed values that do not change during execution of the program.
E.g: 5, 100, “hello”, 14.52, ‘A’, ‘b’
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.

1. Integer Constant
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
 Decimal constant (base 10): It consist of a set of digits, 0 through 9, preceded by an optional –
or + sign.
Eg: 0, -9, 22 etc
 Octal constant (base 8): An Integer constant preceded by a zero (0) is an octal number. It
consists of a set of digits, 0 through 7.
Eg: 021, 077, 033 etc.
 Hexadecimal constant (base 16): It is preceded with 0x or oX. It contains digits from 0-9 and
alphabets A through F,
Eg: 0x7f, 0x2a, 0x521 etc

22POP12 - Principle of Programming Using C Page 15


2. Floating Point Constant

Integers are inadequate to represent quantities such as distance, heights, temperature, price and so on.
These quantities are represented by a number containing fractional parts like 12.32, 7.34 etc. Such
numbers are called floating point constants.
Eg:
0.0000234 // Fractional form
-0.22E-5 // Exponent form: mantissa E exponent
Note: E-5 is same as 10-5

3. Character Constant
A character constant consists of a single character enclosed in single quotes.
For example: 'a', 'l', 'm', 'F', ‘@’

4. String Constant
A string is sequence of characters enclosed in double quotes.
For example:
"good" //string constant
"" //null string constant
" " //string constant of six white spaces
"x" //string constant having a single character.
"Earth is round\n" //prints string with newline

Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and assign it a
value.
For Eg:
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.
#define PI 3.14159
Rules that need to be applied to a #define statement
Rule 1: Constant names are usually written in capital letter
Rule 2: No blank space are permitted in between # and define.

22POP12 - Principle of Programming Using C Page 16


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 semi – colon.

12. INPUT/OUTPUT STATEMENTS IN C


I/O functions in C are categorized as:
1. Unformatted I/O functions
E.g. getchar(), putchar()
2. Formatted I/O Functions
E.g. scanf(), printf()
Unformatted I/O
1. Reading a character
This means taking character input from the user.
 General Syntax:
variable_name = getchar();
E.g.
char c;
c = getchar();
Program: Reading a character
#include<stdio.h>
int main()
{
char c;
printf("Enter a character:");
/* getchar function waits for user to type a Character*/
c = getchar();
printf("Character %c is entered",c);
return 0;
}
Output:
Enter a character: A
Character A is entered
22POP12 - Principle of Programming Using C Page 17
2. Writing a character
Outputting a character on to standard output device
Function: putchar(variable_name);
#include<stdio.h>
int main()
{
char c;
printf("Enter a character:");
c = getchar();
printf("Character entered is:");
putchar(c);
return 0;
}
Output:
Enter a character: A
Character entered is: A

Formatted I/O
1. Formatted Output - THE PRINTF() FUNCTION
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
printf(“Control string", arg1,arg2,arg3,…,argn);
The parameter control string is a C string that contains the text that has to be written on to the standard
output device.
E.g.:
int a = 10,b=5,sum;
sum = a+b;
printf("The sum of %d and %d is %d. \n",a,b,sum);
Output:
The sum of 10 and 5 is 15.

22POP12 - Principle of Programming Using C Page 18


Examples:
printf("hello world"); ==> hello world
printf(“ "); ==>prints a blank space
printf("\n"); ==>prints a new line
printf("hello\nworld"); ==>hello world
printf("a=%d \t b=%d",10,5); ==>a=10 b=5(tab inserted)

Outputting Integers:
General format specification: %wd
w==> Specify minimum field width for the output.
That many (w) spaces is reserved on screen for the data displayed
"%ld" ==> For long int
"%hd" ==> For short int

Output of Real Numbers


General format specifier
%w.pf or %w.pe (e.g 1.234e3)
w ==> width specification
p ==> precision specification
Default precision is 6.
printf("%f",2.3) ==>2.300000
printf("%.3f",2.3) ==> 2.300

2. Formatted Input - THE SCANF() FUNCTION

Formatted Input refers to input data expected/inputted in predefined format in the program.
E.g.: Entered data: 15.75 123 John
This data is read to corresponding type variables. Function used for formatted Input: scanf
General format:
scanf("control string",arg1,arg2,…,argn);
 Control string(format string): specifies order in which data to be entered and the type of the
data expected.
 arg1,arg2,…,argn : variables where data is stored.
 E.g: scanf("%d %c %f", &num,&ch,&fno);

22POP12 - Principle of Programming Using C Page 19


Inputting Integers

General format of control string: %wd


w ==> Specifies width of the data to read
d ==> Indicated we want to read an integer.
E.g. scanf("%5d", &num1)
Reads five digits of user entered number
E.g: scanf("%d", &num1)
Read maximum possible digits(value) from the number entered.

Formatted Input: Strings


General format: %ws
E.g: %s , %5s
char str[10];
scanf("%s",str); // Read till first space or \n found
scanf("%5s",str); // Read first 5 characters
scanf("%[^\n]",str); // Read until \n is found. May not work well with all compilers.

22POP12 - Principle of Programming Using C Page 20

You might also like