CP - Unit-II - C Fundamentals

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

Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

21A4 Computer Programming


Unit 2
C Fundamentals

Introduction
History of ‘C’:
 The ALGOL programming language is the root of all modern languages introduced in 1960s by
international committee. The purpose behind this is to develop all purpose language which is
used to program all types of application instead of using different languages for different
purposes as COBOL for commercial applications, FORTRAN for engineering and scientific
applications and so on. But ALGOL was too abstract and too general.
 To overcome the drawback of ALGOL, new language called Combined Programming Language
(CPL) was developed in 1963. CPL was very big with many features and hence very hard to
learn and difficult to implement.
 In 1967, Martin Richards developed a language called Basic CPL (BCPL). But it was less powerful
and too specific.
 In 1970, Ken Thompson created new language called B. It was created for Unix operating
system at Bell Laboratories.
 At last, C was created by Dennis Ritchie at the Bell Laboratories in 1972. It was initially
implemented on a system that used the Unix operating system.
 In 1989 American National Standards Institute (ANSI) committee has approved a version of C
known as ‘ANSI C’.
 And then in 1990 International Standards Organization has approved C ANSI/ISO C (C89).

BCPL and B were typeless languages whereas C provides a variety of data types. The fundamental
types are characters, integers, floating point numbers of several sizes.

Though, it has been closely associated with the UNIX system, C is not tied to any one operating
system or machine. It has been used equally well to write major programs in many different
domains.

C - A Middle Level Language


There are 3 levels of programming languages. They are,
High Level languages: High level languages are application specific. They are used to develop
applications for a specific field. Example: Java, Python, etc.

Low Level languages: Assembly language and Machine language are called low level languages. Low
level languages provide nothing other than access to the machines basic instruction
set. Example: Assembler, etc.

Middle Level languages: Middle level languages provide facilities of both high level as well as low
level programming. Examples: C, etc.

Prof. Kuldeep S. Ratawa 1


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

C allows direct manipulation of bits, bytes and addresses. Thus, it is ideal for system level
programming. Compilers and Operating systems can be written using C language. C program is very
portable because it not hardware or system dependent.

Importance of C
 The increasing popularity of C is probably due to its many desirable qualities. It is a robust
language whose rich set of built-in functions and operators can be used to write any complex
program.
 Programs written in C are efficient and fast. This is due to its variety of data types and powerful
operators. It is many times faster than BASIC.
 There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several
standard functions are available which can be used for developing programs.
 C is highly portable. This means that C programs written for one computer can be run on
another with little or no modification.
 C language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules or blocks. A proper collection of these modules would
make a complete program. This modular structure makes program debugging, testing and
maintenance easier.
 Another important feature of C is its ability to extend itself. A C program is basically a
collection of functions that are supported by the C library. We can continuously add our own
functions to C library. With the availability of a large number of functions, the programming
task becomes simple.

C programming is applied in:


 System software development  Graphics and multimedia
 Embedded systems  Security software
 Compilers and interpreters  Financial software
 Device drivers  Industrial automation
 Game development  Aerospace and defense
 Database systems  Operating system kernels
 Networking applications  Legacy systems maintenance
 Scientific and numerical computing  Computer graphics
 Web development (primarily backend)

Basic Structure of C Programs

#include <stdio.h> // Include standard input/output library


int main()
{
printf (" Hello! This is First C program "); // Display the message
return 0; // Exit the program with a return status of 0 (indicating success)
}

Prof. Kuldeep S. Ratawa 2


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

1. Preprocessor Directives:
 These are special instructions that tell the computer how to prepare your code before it's
turned into a program.
 Imagine it as a set of rules and notes you give to a helper before they start building
something for you.
2. Main Function:
 Think of the main () function like the starting point of a race. It's where your program gets
going.
 This is where your computer begins executing the instructions you've written.
3. Statements:
 These are like individual steps or actions your program takes.
 For example, telling it to do math, talk to you, or decide what to do next.

Compiling and Execution of a Program

Process of execution of C program is as follows:

 Editor: The text editor is used to write a source code. The code should be in the standard
form as required for execution. Generally notepad, word processor, etc are used to write a
code. Some compilers like Borland C/C++ also provide editor.
 Source Code: This is the user readable plain text written using computer programming
language. It is the input for C compiler.
 C Preprocessor: This is the initial processing before compilation. In this stage source code is
converted into an expanded C source code which is the input for C compiler.
 C Compiler: Compiler converts the expanded high level source code into the machine
understandable low level code. Compiler checks for errors and ask user for corrections if any.
An error free code is then converted into object file. This code is user readable but not
executable.
 Linker: Linker takes one or more object files and linked with other supported standard library
files to produce one executable file.
 Loader: In this loading process the executable file loads from secondary memory to
main/primary memory. And then program run using systems loader.
Prof. Kuldeep S. Ratawa 3
Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Compiling C programs requires working with FOUR kinds of files:


1. Regular source code file contains instructions and functions having names that end with ‘.c’
extension.
2. Header file contains function declarations and various preprocessors statements that allow
access to externally defined functions. Headers files ends with ‘.h’ extension
3. Object files produced as the output of the compiler. They consists of functions definitions in
binary form but are not executable and ends with ‘.obj’ extension.
4. Binary executable files produced as the output of a program called a linker. The linker links
together a number of object files to produce a binary file that can be directly executed and
generally having ‘.exe’ as extension.

C Programming Language
Learning any new language involves first know what are the different alphabets, numbers, symbols
which form that particular language and learning C programming language is also falls on the same
category.

C Character Set:
A character denotes any single alphabet, number, special symbol used to represent particular
information. The reach set of valid alphabets, numbers and special symbols allowed in C is as:

Alphabets [A - Z] Uppercase letters [a - z] Lowercase letters


Digits 0,1,2,3,4,5,6,7,8,9
Special Characters , < > . _ ^ ! * / |
- \ ~ + ( ) ; $ : %
[ ] # ? ' & { } "
White Spaces \b \t \v \r \f \n \\ \’ \" \?
\0 \a

Prof. Kuldeep S. Ratawa 4


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Grammar of ‘C’ / C Tokens


 Data types
 Constants
 Variables
 Keywords
 Operands, Operators and Expressions

Data Types
There are five data types.
char - capable of holding one character. (size - 1 byte)
int - represents natural size of integers (size - 2 bytes)
float - hold numbers with six digits of precision. (size - 4 bytes)
double - hold numbers with ten digits of precision. (size - 8 bytes)
void - used to declare a function as returning no value (valueless)

Modifiers used with Basic Types


A modifier is used to alter the meaning of the base type (except void) to fit various situations more
precisely. Modifiers signed, unsigned, long, short can be applied to character and integer data types.
Long can also be applied to double.

On 16-bit machine size and range of data types


Type Size (bytes) Range
int or signed int 2 -32,768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
long int or signed long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 4 0 to 4,294,967,295
Float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932
char or signed char 1 -128 to 127
unsigned char 1 0 to 255

 signed: By default all the data types are of type signed. This modifier accepts both the values
positive as well as negative.
Example:
int x = 50;
int x = -50;
signed int x = 50;
signed int x = -50;

Prof. Kuldeep S. Ratawa 5


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

 unsigned: This modifier is used to change the data type, so that it can only store positive
values.
Example:
unsigned int x = 100;
unsigned int x = - 100; (wrong)

 short: This modifier is applied to data when a length shorter than the normal integer length is
sufficient.
Example:
short int a = 10; (consume less than 2 byte memory)

 long: A long is used when a length of more than the normal integer length is required.
Example:
long int a; occupies 4 bytes

2 + 2 4 bytes

Constants
A constant can be defined as a quantity that does not change.
 Integer constants
 Integer constant is an integer quantity containing sequence of digits.
 It has no decimal point.
 It can be either positive or negative.
 Blanks and commas are not allowed within integer constants.
 It must lie within the range of integer values (-32768 to 32767).

Example: 0, -11, 32109


Integer Valid Invalid
Base Description
constant Example Example
Any combination of digits from 0 0, 1510, - 54,321 (illegal ,)
Decimal 10
through 9 88, 123 10 20 30 (illegal space)
0786 (illegal 8)
Any combination of digits from 0 to
Octal 8 0, 01, 007 123 (doesn’t begin with 0)
7, the first digit must be 0
012.3 (illegal .)
Any combination of digits from 0 to 7
0x, 0x5, 123 (does not begin with 0x or 0X)
Hexadecimal 16 and A to F (either uppercase or
0Xbc7f 0x12g (illegal character g)
lowercase), must begin with 0x or 0X

 Floating point constants


 Floating point constant contains a decimal point or an exponent.
 It could be either positive or negative.
 No commas or blanks are allowed within a real constant.

Example: 0.0, -54.321, .3, 4. valid


1, 5.2.3 invalid
Prof. Kuldeep S. Ratawa 6
Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

 Character constants
 A character constant is character enclosed in single quotation marks.
 It can contain only one character.
 A character denotes an alphabet, digit or a special character.

Example: ‘A’, ‘1’, ‘$’, ‘=’ valid


“B”, ‘234’ invalid

Variables
A variable is the name of memory location that is used to hold a value which may vary during
program execution. Rules for naming a variable -
 A variable name can be any combination of alphabets, digits or underscores.
 The length of variable name can range from 1 to 8.
 The first character of the variable name must be an alphabet.
 No commas or blanks are allowed within a variable name.
 No special symbol other than underscore can be used.
C is a case sensitive language i.e. variable name ‘NAME’ and ‘name’ is different. Any variable must be
declared before using it in program.

Variable declaration
data_type variable_name ;

Example:
int abc; Meaningful names must be given to variables. Two or more
char name; variables of the same type can be declared separating them with
float avg; comma

Example:
long int i,j;
unsigned int answer;

Storage Classes
In C, storage classes are used to define the scope, lifetime, and visibility of variables.

1. auto: This is the default storage class for local variables. Variables declared as "auto" are
created when the function is called and destroyed when the function exits. They have block
scope, which means they are only accessible within the block of code in which they are
defined.
Ex:
void myFunction()
{
auto int x; // Declared as auto by default
}

Prof. Kuldeep S. Ratawa 7


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

2. register: Variables declared as "register" are stored in CPU registers for faster access.
However, the "register" keyword is only a hint to the compiler, and it may or may not place
the variable in a register, depending on the compiler and system architecture.
Ex: register int counter;

3. static: Variables declared as "static" have a longer lifetime than "auto" variables. They retain
their values between function calls and have file scope, meaning they are visible throughout
the entire file in which they are declared.
Ex: static int globalCounter; // File scope variable

4. extern: Variables declared as "extern" are used to indicate that the variable is defined in
another source file. They are typically used when you want to access a global variable that is
defined in a different file.
Ex: extern int globalVariable; // Declares a variable defined elsewhere

Keywords
Keywords are predefined or reserved words whose meaning is already defined by compiler. They are
used only for specific task.

There are total 32 keywords in C.

Data types : int, char, float, double


Qualifiers : signed, unsigned, short, long
Decision : if, else, switch, case, default
Loop : for, while, do
Jump : break, continue, goto
Function : void, return
Storage Class : auto, static, extern, register
Derived : struct, union
User-defined : typedef, enum
Others : const, sizeof, volitile

Restrictions:
 Keywords can be used only for their intended purpose.
 Keywords cannot be used as function name or user-defined variables.
 All keywords must be written in lowercase.

Operands, Operators and Expressions:


 An operator is a symbol or a special character that tells the computer to perform certain
mathematical or logical manipulations which is applied to operands to give a result.
Prof. Kuldeep S. Ratawa 8
Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

 Operators operate on operands. Operands can be constants or variables. If all operands are
constants in an expression it is called a constant expression. C constants can be any of the basic
data types.
 Operators can be classified as either unary, binary or ternary operators.
 Unary operators act on only one operand, binary operators act on two operands and ternary
operators operate on three operands.

Types of Operators
 Arithmetic operators  Assignment operators
 Relational operators  Conditional operators
 Logical operators  Special operators
 Bitwise operators

Arithmetic operators:
Operator Meaning Example (a = 9, b = 2) Result
+ Addition a+b 11
- Subtraction a–b 7
* Multiplication a*b 18
/ Division (returns quotient) a/b 4
% Modulo operation (returns remainder) a%b 1

The division operator ( / ) requires that the second operand be nonzero.


1.0 / 3.0 = 0.333333 5 / 2.0 = 2.5
-2.0 / 3.0 = -0.666667 5.0 / 2 = 2.5
15 / 10 = 1

The remainder operator (%) requires that both operands be integers and the second operand be
nonzero. When one of the operands is negative, the sign of first operand is the sign of the result
operand.
5%2=1 -5 % 2 = -1
5 % -2 = 1 -5 % -2 = -1

Relational operators:
Operator Meaning Example ( a = 15, b =10) Result
> Greater than a>b True
< Less than a<b False
>= Greater than or equal to a>=b True
<= Less than or equal to a<=b False
== Equal to a==b False
!= Not equal to a!=b True

Note: Double equal to sign (= =) is used to compare two values. Single equal to sign (=) is used as
assignment operator.

Prof. Kuldeep S. Ratawa 9


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Logical operators:
Operator Meaning Example Result
12 && 0 0
&& Logical AND
8 && 3 1
10 || 5.5 1
|| Logical OR
9 || 0 1
! 20 0
! Logical NOT
!0 1

Note: Any non-zero value = Logical True (1) and Zero = Logical False (0)

Bitwise operators:

Operator Meaning Example ( a = 22, b = 10) Result


& Bitwise AND a&b 2
| Bitwise OR a|b 30
^ Bitwise exclusive OR a^b 28
~ Bitwise NOT ~ a (binary 00010110) (binary 11101001)
<< Left Shift a << 2 88
>> Right Shift a >> 2 5

Truth Table [Bitwise operator works on bits]

p q ~p p&q p|q p^q


0 0 1 0 0 0
0 1 1 0 1 1
1 1 0 1 1 0
1 0 0 0 1 1

Assignment operators:
It is the most common and well known operator in any language. This assignment operator (=) is
used in any valid c expression.

Example:
1. x = 5
2. c = a + b
3. p = q = r = 20 (multiple assignment)

Arithmetic assignment operators or Compound assignment operators


Operator Meaning Example ( x = 10 ) Result
+= Addition assignment x+=2 x = 12
-= Subtraction assignment x-=2 x=8
*= Multiplication assignment x*=2 x = 20
/= Division assignment x/=2 x=5
%= Modulus assignment x%=2 x=0
Prof. Kuldeep S. Ratawa 10
Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Conditional operators:
The conditional operator ( ? : ) works on three operands and also known as ternary operator. Format
for using conditional operator is as follows:

Exp1? Exp2 : Exp3


Exp1 is evaluated first and returns answer Exp2 if it is true and Exp3 if it is false.

Example:
If a = 100 ; b = 50 then

x = (a>b)? a :b (Answer: x = a )

Above expression is equivalent to :-


if ( a > b )
x = a;
else
x = b;

Special operators:

Operator Meaning
* Pointer operator
& Address operator
sizeof ( ) Size of operator (returns size of operand in bytes)
We will study * and & operators in the pointer chapter.

Example:
int i,j;
float k;
j = sizeof(i); // Answer j = 2 [ i is an integer and occupies 2 bytes ]
j = sizeof(k); // Answer j = 4 [ k is a float and occupies 4 bytes ]

Increment and Decrement operator:


Operator Meaning Example
a++ post increment
++ Increment by 1
++a pre increment
a-- post decrement
-- Decrement by 1
--a pre decrement
a++;
Both are same when used as simple statements
++a;

a = 3; Here a is first assigned to b and then increment by 1


b = a++; a=4,b=3
Here a is first incremented by 1 and then assigned to b
b = ++a;
a=4,b=4
Prof. Kuldeep S. Ratawa 11
Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Type casting:
An arithmetic operation gives an integer result if both operands are integers. Operation between two
real integers gives a real result. Let us consider mixed mode expressions where both operands are of
different types.

Generally if operands in the expression are different types, then the lower type is promoted to the
higher type, before the expression proceeds.

Example: c = (float) a / b ; // here a converts to float data type

Auto type casting:


In automatic type conversion, it is possible to store one type of value into a variable of another type.

Example:
int a;
float b;
a = 2.89; // a= 2 [ truncation of the fractional part ]
b = 4; // b = 4.000000

Operator precedence:
Precedence Operator Description Associativity
++ -- Suffix/postfix increment and decrement
() Function call
[] Array subscripting
1 . Structure and union member access Left-to-right
Structure and union member access through
->
pointer
(type){list} Compound literal(C99)
++ -- Prefix increment and decrement
+- Unary plus and minus
!~ Logical NOT and bitwise NOT
(type) Type cast
2 Right-to-left
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement
3 */% Multiplication, division, and remainder
4 +- Addition and subtraction
5 << >> Bitwise left shift and right shift
< <= For relational operators < and ≤ respectively
6
> >= For relational operators > and ≥ respectively Left-to-right
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)

Prof. Kuldeep S. Ratawa 12


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

11 && Logical AND


12 || Logical OR
13 ?: Ternary conditional
= Simple assignment
+= -= Assignment by sum and difference
Right-to-Left
14 *= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
15 , Comma Left-to-right

Library functions
Library functions are inbuilt functions and stored in a common place called library. All standard C
library functions are declared in header files. For example if you want to use printf() & scanf(), then
you have to include stdio.h file. We will study preprocessor directives and function in a separate
chapter in detail.

Input / Output functions:


C programming language provides pre-defined functions to perform input output operations. The
input functions are used to read input from keyboard and output functions are used to display
information on screen or printer.

printf() function
This function is used to display or print data on output screen.
Syntax:
printf(“Message to be display”);

Example:
printf(“Welcome to C programming”); // output is Welcome to C programming

printf() function is also used to display or print value of a variable on output screen.
Syntax:
printf(“format string”, list_of_variable);

Example:
A = 15;
printf(“Value = %d”, A); // output is Value = 15

Flag characters used in printf()


Flag Meaning
- Left justify the display
+ Display positive or negative sign of value
space Display space if there is no sign
0 Pad with leading zero
# Use alternate form of specifier

Prof. Kuldeep S. Ratawa 13


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Example:

scanf() function
This function is used to read values of different types from standard input device.
Syntax:
scanf(“format string”,list_of_variable_address);

Example:
scanf(“%d”,&a); // stores integer value in variable a
scanf(“%d %f”,&a,&b); // stores integer value in variable a and float value in variable b

Format specifiers:
Format String For Data Types Displays - printf() Reads - scanf()
%c Char Single character Single char
%d int Signed integer Signed decimal int.
%e float or double Exponential format Signed decimal
%f float or double Signed decimal Signed decimal
%o int Unsigned Octal Octal Value
%x %X int Unsigned Hex Unsigned Hex value
%u int Unsigned decimal int. Unsigned decimal int.

putchar() function
This function is used to display a single character on standard output screen.

Syntax:
putchar(variable_name);

Example:
putchar(ch); // this will display value of ch on output device (monitor)

getchar() function
This function is used to read a single character from standard input device (keyboard)

Syntax:
variable_name = getchar();

Prof. Kuldeep S. Ratawa 14


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Example:
ch = getchar(); // this will read value from standard device and stored in variable ch

puts() function
This function is used to print of display string on output device (monitor)

Syntax:
puts(string);

Example:
char name[20]; Output:
Enter your name: Amol
printf(“Enter your name: ”); Amol
gets(name);
puts(name);

gets() function
This function is used to read string and stores it into character array. The gets() function reads string
or sequence of characters till null character()
Syntax:
gets(string);

Example:
char name[20]; Output:
Enter your name: Amol
printf(“Enter your name”);
Amol
gets(name);
puts(name);

Escape Sequences:
Escape sequences are the string argument of the printf() function used for printing hard-to-get
characters. A list of all escape sequences used in C is given below, each one of them represent one
character although they consist of two characters.

Escape sequence Character represented Example Output


\a Alert (Beep, Bell) printf(“ABCD\b”); ABC
\b Backspace AB
printf(“AB\nCD”);
\f Form feed CD
\n Newline (Line Feed) printf(“ABCD\rPQRS”); PQRS
\r Carriage Return printf(“AB\tCD”); AB CD
\t Horizontal Tab printf(“ \\ABCD\\ ”); \ABCD\
\v Vertical Tab printf(“ \”ABCD\” ”); “ABCD”
\\ Backslash
printf(“ \’ABCD\’ ”); ‘ABCD’
\' Single quotation mark
printf(“ \”ABCD\” ”); “ABCD”
\" Double quotation mark
printf(“ABCD\? ”); ABCD?
\? Question mark

Prof. Kuldeep S. Ratawa 15


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Writing a ‘C’ program


The steps of writing program with C, compiling this program and finally executing it requires THREE
components:
1. Operating system
2. A text editor
3. C Complier

Structure of C program

Line no. 1:
This is the comment block – optional and non executable in nature. Comments are added to make a
program more readable to you but the compiler must ignore the comments. There are two types of
comments in C: (a) Multi-line comments (also called block comments) and (b) single-line comments
(also called line comments).

Opening delimiter /* & Closing delimiter */ Compiler ignores everything you have typed between
the delimiters /* and */. For single-line comment, simply type the symbol // and then type the text
of comment to the end of that line.

Line no. 2:
The pre processor is a phase which occurs prior to compilation of a program. The preprocessor has
two main uses: it allows external files, such as header files, to be included and it allows macros to be
defined. It is written just before the main()in the C program.

Pre-processor commands are differ from program statements in two ways:


 They must begin in the first column and no spaces are allowed between ‘#’ and include.
 They are not terminated by a semicolon.

Line no. 3:
Every C program contains a function called main. This is the starting point of the program. A C
program must contain one or more function one of which must be main().

Prof. Kuldeep S. Ratawa 16


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Line no. 5, 6, 7:
This is the executable block of instructions to perform a specific functionality. printf() function is a
‘library function’ provided by complier which is ready to use. When printf ( ) function is executed, its
built-in instructions process it, i.e. string enclosed in quotation called as string constant or character
string is displayed on the output device, usually on VDU.

A program is made up of functions, functions are made up of statements and declarations


surrounded by curly braces { }.The basic building block in a C program is the function. Every C
program is a collection of one or more functions, written in some arbitrary order. One and only one
of these functions in the program must have the name main().

Instruction in C
Instructions in C are formed using different types of constants, variables and keywords.

There are basically four different types of instructions in C:


1. Type declaration instruction
2. Input / Output instruction
3. Arithmetic instruction
4. Control instruction

1. Type declaration instruction:


It is used to declare the type of variable being used in the program. Any variable used in the program
must be declared before using it in any statement.

Example:
int sal;
float pi;
char name, dept;

2. Input / Output instruction:


It is used to perform the function of supplying input data to a program and obtaining the output
result from it.

Example:
printf(“Enter number”);
scanf(“%d” , &A);

3. Arithmetic instruction:
A C arithmetic instruction consists of a variable name on the left hand side of = and variable name
and constant on the right hand side of =. The variable and constants appearing on the RHS of = are
connected by arithmetic operators like +,-,* and /.

Prof. Kuldeep S. Ratawa 17


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Example:
age = 30;
c = a + b;
avg = ( a+b+c+num)/4;

4. Control instruction:
It is used to control the sequence of execution of various statements in a C program. (Sequence,
selection/decision, repetition/loop, case control instructions)

Example:
do
{
--------- ;
--------- ;
} while (condition);

Points to Remember
 The C language is developed by Dennis Ritche.
 C is structured, middle level language programming language.
 C programming is a case sensitive programming language.
 There are basic 4 data types – character, integer, float, double.
 The C language has 32 keywords.
 Operator precedence and associativity determines the evaluation order of expressions.
 A C program must contain one or more function one of which must be main().
 Instruction = Keywords + Constants + Variables

C Programs
1. Hello World
2. Sum of Two Numbers
3. Product of Two Numbers
4. Division of Two Numbers
5. Average of Three Numbers
6. Cube of Integers
7. Area of a Rectangle
8. Area and Circumference of a Circle
9. Area of a Triangle
10. Conversion of Fahrenheit to Celsius
11. Conversion of Feet to Inches
12. Simple Interest Calculation

Prof. Kuldeep S. Ratawa 18


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

EXTRA FOR UNDERSTANDING PURPOSE

1. Compiler:
 A compiler translates the entire source code of a program into machine code or an
intermediate code before execution.
 It reads the source code files and generates object files or directly executable files.
 Compilation is a separate process from execution. The compiled code can be executed
multiple times without the need for recompilation unless changes are made to the
source code.
 Compilers are generally used for languages like C, C++, and Java.
 Compiled programs tend to be faster in execution compared to interpreted programs
because the translation process is done upfront.
2. Interpreter:
 An interpreter reads the source code line by line and executes it immediately.
 It does not produce a standalone machine code or intermediate code file but
translates and executes the code directly.
 Interpretation and execution occur simultaneously, without a separate compilation
step.
 Interpreters are often used in scripting languages like Python, Ruby, and JavaScript.
 Interpreted programs tend to have slower execution compared to compiled programs
because the code is translated and executed at runtime.
Here are some key differences between compilers and interpreters:
 Performance: Compiled programs generally execute faster than interpreted programs
because they are translated into machine code or an intermediate representation
beforehand.
 Portability: Interpreted programs are usually more portable since they do not rely on
machine-specific compiled binaries.
 Error Detection: Compilers perform a comprehensive analysis of the entire code and can
catch errors at compile time, while interpreters may only detect errors as they encounter
them during runtime.
 Ease of Debugging: Interpreters often provide better support for debugging since they can
give more detailed information about the state of the program during execution.
 Flexibility: Interpreted languages are often more flexible as they allow dynamic typing and
runtime evaluation of code constructs.

Prof. Kuldeep S. Ratawa 19


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

The basic structure of a C program typically includes the following elements:


1. Preprocessor Directives: These are lines of code that begin with #. They are processed by the
preprocessor before compilation and are used for including header files (#include), defining
constants (#define), and performing other tasks like conditional compilation.
2. Main Function: Every C program must have a main() function. Execution of a C program
begins from the main() function. It serves as the entry point of the program. The main()
function can optionally return an integer value to the operating system indicating the success
or failure of the program execution.
3. Variables and Data Types: Declarations of variables and their data types come next. In C, you
declare variables at the beginning of a block. This section also includes any necessary variable
initialization.
4. Executable Statements: These are the actual instructions or actions that the program will
perform. These statements can include assignments, conditional statements (if, else, switch),
loops (for, while, do-while), function calls, etc.
5. Functions: Apart from main(), a C program may contain other functions as well. Functions
encapsulate a set of statements to perform a specific task. They help in organizing code and
promoting reusability.
6. Comments: Comments are used to improve code readability and understanding. They are
ignored by the compiler. C supports two types of comments: single-line comments (//) and
multi-line comments (/* */).

#include <stdio.h> // Preprocessor directive

int main() { // Main function


// Variable declaration and initialization
int x = 10;
int y = 20;

// Executable statements
if (x < y) {
printf("x is less than y\n");
} else {
printf("x is greater than or equal to y\n");
}

return 0; // Returning 0 indicates successful program execution


}

Prof. Kuldeep S. Ratawa 20


Prof Ram Meghe College of Engineering & Management, Badnera - Amravati [IT-B]

Libraries for use by C programs really consist of two parts: header files that define types and macros
and declare variables and functions; and the actual library or archive that contains the definitions of
the variables and functions

Prof. Kuldeep S. Ratawa 21

You might also like