You are on page 1of 20

1

CS8251 – Programming in C
UNIT-I
SYLLABUS:-
Introduction to programming paradigms-Structure of C program-C programming:
Data types-Storage classes-Constants-Enumeration constants-Keywords-Operators:
Precedence and Associativity-Expressions-Input/Output Statements, Assignment
statements-Decision making statements-Switch statement-Looping statements-
Preprocessor directives-Compilation process.

Introduction to Programming:-
 A computer is an electronic machine that accepts data from the user, processes
the data by performing calculations and operations on it, and generates the
desired output as a result.
The computer system is divided into two types. They are
 System Software
 Application Software

“System software is the set of programs that allows the hardware to run properly.”
System software provides a general programming environment in which the
programmers can create the specific applications to suit their needs. This environment
provides new functions that are not available at the hardware level and it performs
tasks related to the execution of application program. Example: Operating System.

“Application software is a set of software that is designed to solve a particular


problem for the users.” Example: Games, Spreadsheets, Word processors, Database,
Web browsers.

Introduction to Programming Paradigms:-


A programming paradigm is a fundamental style of programming that defines how the
structure and basic elements of a program will be built. The different programming
paradigms which are used to develop the program are,

 Monolithic Programming
 Procedural Programming
 Structured Programming
 Object-oriented Programming
 Logic-oriented Programming
2

 Rule-oriented Programming
 Constraint-oriented Programming

Monolithic Programming:-
Monolithic programming language is also known as assembly language, which
consists of global data and sequential code. Monolithic programming language does
not support the concept of subroutines. Therefore, all the actions required to complete
a particular task are embedded within the same application itself.

B=10
Global Data
C=20

MOV A, B
ADD A, C
MOV SUM, B
JMP STOP
.... Sequential
STOP: EXIT code with JMP
instruction

Monolithic programming style makes the program size larger and also it makes it
difficult to debug and maintain.

Procedural Programming:-
In procedural programming style, the program is divided into subroutines and that can
be access global data. To avoid repetition of code, each subroutine performs a well-
defined task. The subroutines are executed by make a call to that subroutine.
FORTRAN and COBOL are the two popular procedural programming languages.

Global Data

Subroutines

Program
3

Advantages:-
 Programs are easier to write when compared to monolithic programming
language.
Disadvantages:
 There is no concept of reusability.
 Requires more time and effort to write programs.
 Programs are difficult to maintain.
 Since global data are used, the data can be altered.

Structured Programming:-
 Structured programming language is also known as modular programming
language. In structured programming language, the overall program structure is
broken down into separate modules.
 Modules are coded separately and once a module is written and tested
individually, it is then integrated with other modules to form the overall
program structure.
 Structured programming language supports sequence flow, selection and
repetition.

Global Data
Modules that have
local data and code

Program

Advantages:-
 Easy to understand and write the program.
 Easy to make changes in the program.
 Top-down approach for problem solving.

Disadvantages:-
 Since global data are used, the data can be altered.
4

Object-oriented Programming:-
 Object-oriented programming style is a programming paradigm which is based
on the concept of objects.
 An object is a combination of data and methods.
 Data are known as attributes of an object and the method refers the functions of
the object.
 In object-oriented programming language, the data are hidden and cannot be
accessible by external functions.
 It is a bottom-up approach for problem solving.
Logic-oriented Programming:-
 The logic-oriented programming style includes set of facts and rules to perform
a specific task.
Rule-oriented Programming:-
 The rule-oriented programming style includes “if-then-else” rules for
computation.
Constraint-oriented Programming:-
 The Constraint-oriented programming style includes set of conditions to solve a
particular problem.
Structure of C Program:-
Documentation Section

Preprocessor Directives

Global Declarations;

main()
{
Local Declarations;
Statements;
}
Function 1()
{
Local Declarations;
Statements;
}
...................................................
Function N()
{
Local Declarations;
Statements;
}
5

 A C program composed of preprocessor commands, a global declaration


section and one or more functions.
Documentation Section:-
Documentation section includes a set of comment lines that gives information about
the program such as name of the program, purpose of the program. Documentation
section is optional. It indicated by /* */.

Preprocessor Directives:-

 The preprocessor directives is also known as precomplier that contains special


instructions, which instructs the compiler to how to prepare for the program
compilation. It begins `
 The “define” directive is also used as preprocessor directive, which assign a
constant value to the symbolic constants.

Include Directive Syntax and Examples:-


Syntax: #include<standard header file>
Examples: #include<stdio.h>
#include<math.h>
Define Directive Syntax and Examples:-
Syntax: #define Name value
Examples: #define PI 3.14
#define MAX 100

Global Declaration Section:-

The variables that are declared outside the program can be accessed to all the functions in the
program. This variable declaration is known as global variable declaration.

Main Function Section:-


 The program may contain one or more functions but there must be one main( ) function.
 The execution of the C program begins with the main function.
 The main function begins by opening the curly brace and ends by closing the curly brace.
 The main( ) function consists of two parts: Local declaration and statement. Local declaration
is the declaration of variables inside the function. Statements are the set of instructions which
are used to perform a task.
 If we put “int main( )” in the main function, then the program will return the value to the
Operating system. If we put “void main( )” in the main function, then the program will
executes and produce output but the value is not returned to operating system.
6

User-Defined Function Section:-

Each user-defined function contains return type followed function name followed by an optional list
of arguments enclosed in parenthesis. The user-defined functions are executed by calling the function
name in the main function.

 The user-defined function also contains local variable declarations and statements to perform
a specific task.

Syntax:

return_type function_name( )
{
Local declaration;
Statements;
}

Example:

#include<stdio.h>
main( )
{
int a,b,c,d;
scanf(“ %d”, &a);
scanf(“ %d”, &b); Output
c = a + b;
prinf(“ %d is the sum result”, c); 1
d=int cube(int number); 2
prinf(“ %d is the cube result”, d); 3 is the sum result
} 3
9 is the cube result
int cube(int number)
{
int cube;
scanf(“ %d”, &number);
cube = number * number * number;
return(cube);
}

C Programming:-

Data Types:-

 Data types simply refer to the type and size of data associated
with variables and functions.
7

C Data Types:-

 There are four data types in C language. They are,

Basic Data Types in C Language:-

Integer Data Type:-

 Integer data type allows a variable to store numeric values.


 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use. If we are using 16 bit
processor, 2 byte (16 bit) of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of
memory for 64 bit processor is allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.

Character Data Type:-

 Character data type allows a variable to store only one character.


 Storage size of character data type is 1. We can store only one character using
character data type.
 “char” keyword is used to refer character data type.

Float Data Type:-

 Float data type allows a variable to store decimal values.


 Storage size of float data type is 4. This also varies depend upon the processor in
the CPU as “int” data type.
Double Data Type:-

 Double data type is also same as float data type.


 The storage size of double data type is 8.
8

Void Data Type:-

 Void type means no value.


 This is usually used to specify the type of functions which returns nothing.

SIZEOF() FUNCTION IN C LANGUAGE:

 sizeof() function is used to find the memory space allocated for each C data types.

#include <stdio.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
}

Output:-
Storage size for int data type:2
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8

Constants :-
 C Constants are also like normal variables. But, only difference is, their values
cannot be modified by the program once they are defined.
 Constants refer to fixed values. They are also called as literals
 Constants may be belonging to any of the data type.
Eg:- Pi = 3.14, The value of Pi is not changed. This refers to constants.
Syntax:
const data_type variable_name;
Types of C Constants:-
 Integer Constants
 Floating Point Constants
9

 Character Constants
 String Constants
Integer Constants:-
 It's referring to a sequence of digits. Integers are of three types viz:

1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Floating Point Constants:-

 It must have a decimal point


 It could be either positive or negative
 Floating point constants are also known as real constants.
Example:

12.5, 0.47
Character Constants:-

A character constant consists of a single character enclosed in single quotes.


Eg:- ‘a’, ‘@’

String Constants:-

 These are a sequence of characters enclosed in double quotes.


 Eg:- “Hello”

Example for Constants in C:-

#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
}
10

Output:-
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC

Enumeration Constants in C:-


Enumeration is a user defined datatype in C language. It is used to assign names to the
integral constant which makes a program easy to read and maintain. The keyword
“enum” is used to declare an enumeration.
Syntax:-
enum identifier [optional{ enumerator-list }];
or
enum enum_name{const1, const2, ....... };

The enum keyword is also used to define the variables of enum type.

Example:-

enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};

#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar; O/P
if(month == 0)
printf("Value of Jan");
Month is March
else if(month == 1)
printf("Month is Feb");
if(month == 2)
printf("Month is Mar");
}

Explanation:-
In the above program,
enum month { Jan, Feb, Mar }; or
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
11

/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */


enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22
respectively by default */

Keywords:-
Keywords are preserved words that have special meaning in C language. The meaning
of C language keywords has already been described to the C compiler. These meaning
cannot be changed.
Keywords in C languages are:-

C Tokens:-

 C tokens are the basic buildings blocks in C language which are constructed
together to write a C program.
 Each and every smallest individual units in a C program are known as C tokens.

C tokens are of six types. They are,


1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators
12

Keywords:-
Keywords are preserved words that have special meaning in C language. The meaning
of C language keywords has already been described to the C compiler. These meaning
cannot be changed.
Keywords in C languages are:-

Identifiers:-
 Each program elements in a C program are given a name called identifiers.
 Names given to identify Variables, functions and arrays are examples for
identifiers.
 Eg. x is a name given to integer variable in above program.

RULES FOR CONSTRUCTING IDENTIFIER NAME IN C:


1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.
Constants:-
 Constants refer to fixed values. They are also called as literals
 Constants may be belonging to any of the data type.
Eg:- Pi = 3.14, The value of Pi is not changed.
Strings:-
 Strings are the set of characters enclosed within double quotes.
 Eg:- “ Hello”
Special Symbols:-
 Special symbols includes (), {},etc.
13

Operators:-
 Operators are used to perform some operations on computer.
 Eg:- +, -, *, /, etc
Example:-

int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
printf ("Total = %d \n", total);
}

Where,
 {,}, (,) – delimiter/ Special Symbols
 int – keyword
 x, y, total – identifier/Variables
 main, {, }, (, ), int, x, y, total – tokens

[Refer Text Book for Types of Operators and Precedence and Associativity of
Operators]

Expressions:-
 An expression is a combination of variables constants and operators written
according to the syntax of C language.
 In C every expression evaluates to a value i.e., every expression results in some
value of a certain type that can be assigned to a variable.
 Every expression consists of at least one operand and can have one or more
operators.
 Operands are values and Operators are symbols that represent particular
actions.
14

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form

Variable = expression;

Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the
left hand side. All variables used in the expression must be assigned values before
evaluation is attempted.

Example of evaluation statements are


x=a*b–c
y=b/c*a
z = a – b / c + d;

Example:-

#include<stdio.h>
int main()
{
int x, y, total;
x = 10, y = 20; O/P
total = x + y;
printf ("Total = %d \n", total); Total = 30
}

Input/Output Statements:-

 In C Language input and output function are available as C compiler


function or C library provided with each C compiler implementation. These
all functions are collectively known as Standard I/O Library function.
 Here I/O stands for Input and Output used for different inputting and
outputting statements. These I/O functions are categorized into three
prcessing functions.
 Console input/output function (deals with keyborad and monitor), disk
input/output function (deals with floppy or hard disk) and port input/output
function (deals with serial or parallet port).
 As all the input/output statements deals with the console, so these are
also Console Input/Output functions. Console Input/Output function
accesses the three major files before the execution of a C Program.
15

stdin: This file is used to receive the input (usually is keyborad file, but can also
take input from the disk file).
stdout: This file is used to send or direct the output (usually is a monitor file, but
can also send the output to a disk file or any other device).
stderr: This file is used to display or store error messages.

Input/Output Statement:-

 Input and Output statement are used to read and write the data in C
programming. These are embedded in stdio.h (standard Input/Output header
file).
 There are mainly two of Input/Output functions are used for this purpose.
 Unformatted Input/Output Statement
 Formatted Input/Output Statement

Unformatted Input/Output Statement

a) getchar()
b) putchar()
c) gets()
d) puts()

getchar()

 This function is an Input function. It is used for reading a single character


from the keyboard.
 The general syntax is as:
v = getchar();

where, v is the variable of character type.


For example:
16

/*To read a single character from the keyboard using the getchar() function*/
#include
main()
{
char n;
n = getchar();
}

b) putchar()

This function is an output function. It is used to display a single character on the


screen. The general syntax is as:
putchar(v);

where v is the variable of character type.


Example
/*Program illustrate the use of getchar() and putchar() functions*/
#include
main()
{
char n;
n = getchar();
putchar(n);
}
c) gets()
This function is an input function. It is used to read a string from the keyboard.
The general syntax is as:
gets(v);

where v is the variable of character type.

Example
/*Program to explain the use of gets() function*/
#include
main()
{
char n[20];
gets(n);
}

d) puts()
17

This is an output function. It is used to display a string inputted by gets() function.


It is also used to display an text (message) on the screen for program simplicity.

The general syntax is as:

puts(v);
or
puts("text line");

where v is the variable of character type.


Example
/*Program to illustrate the concept of puts() with gets() functions*/
#include
main()
{
char name[20];
puts("Enter the Name");
gets(name);
puts("Name is :");
puts(name);
}

OUTPUT IS:
Enter the Name
Laura
Name is:
Laura

Formatted Input/Output Statement:-

Formatted I/O functions which refers to an Input or Ouput data that has been
arranged in a particular format. There are mainly two formatted I/O functions
discussed as follows:

a) scanf()
b) printf()

a) scanf()
The scanf() function is an input function. It used to read the mixed type of data
18

from keyboard. You can read integer, float and character data by using its control
codes or format codes.

The general syntax is as:

scanf("control strings",arg1,arg2,..............argn);
or
scanf("control strings",&v1,&v2,&v3,................&vn);

Where arg1,arg2,..........argn are the arguments for reading and v1,v2,v3,........vn all
are the variables.

/*Program to illustrate the use of formatted code by using the formatted scanf()
function */ #include
main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}

b) printf()

This is an output function. It is used to display a text message and to display the
mixed type (int, float, char) of data on screen.
The general syntax is as:
printf("control strings",&v1,&v2,&v3,................&vn);
or
printf("Message line or text line");
Where v1,v2,v3,........vn all are the variables.

Example
/*Below the program which show the use of printf() function*/

#include
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
19

scanf("%d",%f,%c",&a,&b,&c);
getch();
}

Assignment Statements:-

 Assignment statements are used to assign values to a variable using assignment


operators.
Syntax:-

Variable = constant / variable/ expression;

Where, ‘=’ is an operator which is used to assign values to the left hand side of the
variable.

#include<stdio.h>
int main()
O/P
{
int x, y, total;
x = 10, y = 20; Total = 30
total = x + y;
printf ("Total = %d \n", total);
}

Compilation Process:-

 The process of translating source code written in high level to low


level machine code is called as Compilation.
 The compilation is done by a special software known as compiler.
 The compiler checks source code for any syntactical or structural errors and
generates object code with extension .obj (in Windows) or .o(in Linux) if source
code is error free.

C compilation:-
20

The entire C compilation is broken to four stages.

 Pre-processing
 Compilation
 Assembling and
 Linking

 The preprocessor instructs the compiler to execute the source code in the
main() function.
 Compiler is an intermediator to translate the source code into object code.
 The source code is converted into object file by the assembler.
 Linker takes the generated object file into executable file. Linker is also
capable in linking library files.
 Once the linker is finished linking all the object files and libraries, you will
have an executable file that you can then run and the output can be obtained.

You might also like