Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 23

GE6151- Computer Programming

-1-

UNIT II
Introduction :
C language is a general purpose and structured programming language developed by
'Dennis Ritchie' at AT &T's Bell Laboratories in the 1972s in USA.
Features of C :

Portability
Flexibility
Effectiveness and efficiency
Reliability
Interactivity

Execution of C Program :
C program executes in following 4 (four steps).

Creating Program : An editor like notepad or wordpad is used to create a C program.


This file contains a source code which consists of executable code. The file should be
saved as '*.c' extension only.
Compiling the program : The next step is to compile the program. The code is
compiled by using compiler. Compiler converts executable code to binary code i.e.
object code.
Linking a program to library : The object code of a program is linked with libraries that
are needed for execution of a program. The linker is used to link the program with
libraries. It creates a file with '*.exe' extension.
Execution of program : The final executable file is then run by dos command prompt.
Process
Save a program
Compile a program
Run a program
Output Window
Structure of C Program

Dept. of CSE, SVCET

Key
F2
Alt + F9
Ctrl + F9
Alt + F5

GE6151- Computer Programming

# include<stdio.h>
# Define
global variable declaration
main ()
{
Local Variable declaration
Statements
.
.
.

-2-

// Header file
// Preprocessor Directives
// Global Variable declaration
// main function declaration

}
Sub function ()
{
Local Variable declaration
Statements
.
.
.
}
Preprocessor Commands: These commands tells the compiler to do preprocessing
before doing actual compilation. Like #include <stdio.h> is a preprocessor command
which tells a C compiler to include stdio.h file before going to actual compilation.
Functions: Functions are main building blocks of any C Program. Every C Program
will have one or more functions and there is one mandatory function which is called
main() function.
Variables:

Variables are used to hold numbers, strings and complex data for

manipulation..
Statements & Expressions : Expressions combine variables and constants to create
new values. Statements are expressions, assignments, function calls, or control flow
statements which make up C programs.
Comments:

comments are used to give additional useful information inside a C

Program. All the comments will be put inside /*...*/ as given in the example above. A
comment can span through multiple lines.
Note :

Dept. of CSE, SVCET

GE6151- Computer Programming

C is a case sensitive programming language.

C has a free-form line structure.

End of each C statement must be marked with a semicolon.

Multiple statements can be one the same line.

Keywords :

-3-

Keywords are standard identifiers that have standard predefined

meaning in C. Keywords are all lowercase


Constants : C Constants are values, that values can not 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 available in C language.
Types of C constant:
1) Integer constants
2) Floating point constants
3) Character & String constants
Rules for constructing C constant:
1. Integer Constants in C:
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer constant.
If no sign precedes an integer constant, it is assumed to be positive.
Example : 23, 56, -103
2. Floating point / Real constants in C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
Example : 34.12, , 56.345, -103.87
3. Character and string constants in C:
A character constant is a single alphabet, a single digit or a single special symbol
enclosed within single quotes.
The maximum length of a character constant is 1 character.
String constants are enclosed within double quotes.
Example : .a, ,@, welcome

Dept. of CSE, SVCET

GE6151- Computer Programming

-4-

Variable
A variable is an entity whose value can change during the execution of a program. It is
nothing but a name given to a storage area that our programs can manipulate.
Rules for Declaring Variable Name
1) The name of a variable can be composed of letters, digits, and the
underscore character.
2) It must begin with either a letter or an underscore.
3) Upper and lowercase letters are distinct because C is case-sensitive.
4) Keywords are not allowed as variable name
5) No space between variable name
Syntax
Data type Variable Name1, variable name2, ;
Example :
int i, j, k;
char c, ch;
float f, salary;
double d;
Note : The C has other types of variable like Enumeration, Pointer, Array, Structure,
Union, etc. For this chapter, let us study only basic variable types.
Local Variables : Local variables scope is confined within the block or function where it
is defined. Local variables must always be defined at the top of a block. When execution
of the block starts the variable is available, and when the block ends the variable 'dies'
Global Variables : Global variable is defined at the top of the program file and it can be
visible and modified by any function that may reference it.
Data types
The data types are used to define a variable before its use. The definition of a variable
will assign storage for the variable and define the type of data that will be held in the
location. The Language has flowing data types
Integer Data Types: Integers are whole numbers with a range of values, range of
values are machine dependent. Generally an integer occupies 2 bytes memory space

Dept. of CSE, SVCET

GE6151- Computer Programming

-5-

and its value range limited to -32768 to +32767. The integer has three types namely int,
int and long int.
Syntax : int <variable name>;
Example :

int num1;
short int num2;
long int num3;

Floating Point Data Types: The float data type is used to store fractional numbers (real
numbers) with 6 digits of precision. Floating point numbers are denoted by the keyword
float. we can use the double to define the more range
Syntax :
Example :

float <variable name>;


float num1;
double num2;
long double num3;

Character Data Type: Character type variable can hold a single character and are
declared by using the keyword char. The another character data type is unsigned chars;
both occupy 1 byte each,
Syntax: char <variable name>;
Example :

char ch = a;

Derived Data types :


These data types are derived from the basic data type.
Arrays : Arrays are collections of data items all having the same data type, accessed
using a common name and an integer index.
Structures: Structures are collections of data items of either the same or different
types, each having a unique name within the collection, and accessed using those
names.
Unions : Unions are very much like structures, except that they only reserve enough
space for the largest contained data item, which is then shared by all of the defined
fields within the union.
Enumerated data type : enumerated type is an integer with a restricted list of legal
values, referred to by names.

Dept. of CSE, SVCET

GE6151- Computer Programming

S.No
1
2
3
4
5
6
7
8
9
10
11
12
13

-6-

storage
Range
Size
Char
1
127 to 127
Int
2
32,767 to 32,767
1E37 to 1E+37 with six digits of
Float
4
precision
1E37 to 1E+37 with ten digits of
Double
8
precision
1E37 to 1E+37 with ten digits of
long double
10
precision
long int
4
2,147,483,647 to 2,147,483,647
short int
2
32,767 to 32,767
unsigned short int 2
0 to 65,535
signed short int 2
32,767 to 32,767
long long int
8
(2power(63) 1) to 2(power)63 1
signed long int
4
2,147,483,647 to 2,147,483,647
unsigned long int 4
0 to 4,294,967,295
unsigned long
8
2(power)64 1
long int
C Data types

Operators
An operator is a symbol that specifies an operation to be preformed on the
operands. The data items that operators act upon are called operands some operators
require two operands called binary operators, while other acts upon only one operand
called unary operator.
Eg:
a+b : Where + is Operator a b are the Operands.
Types of operators
1) Arithmetic operators
2) Relational Operators
3) Logical operators
4) Assignment Operators
5) Increment and decrement Operators
6) Conditional Operators
7) Bitwise Operators
8) Size of () Operators
Arithmetic Operators
C provides all the basic Arithmetic operators like addition, subtraction, multiplication,
and division. The following table shows the Arithmetic operators and their meaning.
Operator Meaning
Dept. of CSE, SVCET

GE6151- Computer Programming

-7-

+
*
/
%

Addition
Subtraction
Multiplication
Division
Modulo division

The modulo division give the remainder of an integer division.


Relational Operators
Relational operators are used to compare two or more operands. Operands may
be variables, constants or expression. For example we may compare the age of two
persons. Or the price of two items and so on. These comparisons can be done with the
help of relations operators.
The following table show the Relational Operators
Operator

Meaning

<
<=
>
>=
==
!=

Is less than
Is less than or equal to
Is greater than
Ie greater than or equal
Is equal to
Is not equal to

a= 10, b= 15
(Expression)
a<b
a<=b
a>b
a>=b
a==b
a!=b

Answer
True
True
False
False
False
True

Logical Operator
Logical operators are used to combine the results of two or more conditions. C
has the following- Logical operators.
Operator
&&

Meaning
Logical And
Logical or
Logical Not

A=10, b=20,c=30
(a<b)&&(b<c)
(a>b)|| (b<c)
!A

Output
True
True
False

Assignment Operator
Assignment operators are used to assign a value or an expression or a value of a
variable to another variable.
Syntax:
Eg :

Variable = expression (or) value


x=10;

Dept. of CSE, SVCET

GE6151- Computer Programming

-8-

Compound assignment
Apart from assignment operator (=). C provides compound assignment
operators to assign a value to a variable in order to assign a new value to a variable
after performing a desired operation.
Some of the compound Assignment operators and their meaning given below.
Operator

Example

Meaning

+=

X+=y

X=x+y

-=

X-=y

X=x+y

*=

X*=y

X=x *y

/=

X/=y

X=x/y

%=

X%=y

X=x%y

Increment and decrement operators (Unary Operators)


C has two way useful operators not generally found in other languages. These
are the increment (++) and decrement (- -) operators. The ++ adds one to the variables
and - - subtracts one from the variables. These operators are called unary operators.
Because they acts upon only one variable.
Operator Meaning
++x

Pre increment

-- x

Pre decrement

X ++

Post increment

X --

Post decrement

Conditional operator (or) Ternary Operator


Conditional operator itself checks the condition and executes the statement
depending on the condition.
Syntax:
Exp1?Exp2: exp3
The ?: operator acts as a ternary operator, it first evaluate the condition, if its true (non
zero) the the expl is evaluated, if the condition is false (zero) then the exp 3 is
evaluated.
Dept. of CSE, SVCET

GE6151- Computer Programming

Eg:

-9-

big = a> b? a:b;

Bit wise operators


Bit wise operates are used to manipulate the data at bit level. It operates on
integers only. It may not be applied to flat or real. The operators and its meaning are
given below.
Operator

Meaning

&

Bitwise AND

Bitwise OR

Bitwise XOR

<<

Shift left

>>

Shift right

Ones complement

The size of () operator


The size of () is a unary operator, that returns the length I bytes of the specified
variables, and it is very useful to find the bytes occupied by the specified variables in the
memory.
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.
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

Dept. of CSE, SVCET

GE6151- Computer Programming

- 10 -

left hand side. All variables used in the expression must be assigned values before
evaluation is attempted. Example of evaluation statement : A = a * b c

Precedence in Arithmetic Operators


An arithmetic expression without parenthesis will be evaluated from left to right
using the rules of precedence of operators. There are two distinct priority levels of
arithmetic operators in C.
High priority * / %
Low priority + Rules for evaluation of expression

First

parenthesized

sub

expression

left

to

right

are

evaluated.

If parenthesis are nested, the evaluation begins with the innermost sub expression.

The precedence rule is applied in determining the order of application of


operators in evaluating sub expressions.

The associability rule is applied when two or more operators of the same
precedence

level

appear

in

the

sub

expression.

Arithmetic expressions are evaluated from left to right using the rules of precedence.
When Parenthesis are used, the expressions within parenthesis assume highest
priority.
Type conversions in expressions
Implicit type conversion
C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the expression
can be evaluated without loosing any significance. This automatic type conversion is
know as implicit type conversion
During evaluation it adheres to very strict rules and type conversion. If the
operands are of different types the lower type is automatically converted to the higher
type before the operation proceeds. The result is of higher type.

Dept. of CSE, SVCET

GE6151- Computer Programming

- 11 -

The following rules apply during evaluating expressions


1. If one operand is long double, the other will be converted to long double and result
will be long double.
2. If one operand is double, the other will be converted to double and result will be
double.
.
3. If one operand is float, the other will be converted to float and result will be float.
.
4. If one of the operand is unsigned long int, the other will be converted into unsigned
long int and result will be unsigned long int.
5. If one operand is long int and other is unsigned int then a. If unsigned int can be
converted to long int, then unsigned int operand will be converted as such and the result
will be long int. .....b. Else Both operands will be converted to unsigned long int and the
result will be unsigned long int.
.
6. If one of the operand is long int, the other will be converted to long int and the result
will be long int. .
7. If one operand is unsigned int the other will be converted to unsigned int and the
result will be unsigned int.
Explicit Conversion
Many times there may arise a situation where we want to force a type conversion in a
way that is different from automatic conversion.
Operator precedence and associatively
Each operator in C has a precedence associated with it. The precedence is used to
determine how an expression involving more than one operator is evaluated. There are
distinct levels of precedence and an operator may belong to one of these levels. The
operators of higher precedence are evaluated first.

Dept. of CSE, SVCET

GE6151- Computer Programming

- 12 -

The operators of same precedence are evaluated from right to left or from left to right
depending on the level. This is known as associativity property of an operator.
The table given below gives the precedence of each operator.

Orde
r
1

Category

Operator

Highest precedence (
[
?
:
.

Operation

Associativity

Function call
]

L
?
R
Left to Right

Unary

!
~
+
++
&
*
Size of

Logical negation (NOT) R


?
L
Bitwise 1s complement Right -> Left
Unary
plus
Unary
minus
Pre or post increment
Pre or post decrement
Address
Indirection
Size of operant in bytes

Member Access

.*
?*

Dereference
Dereference

L?R

Multiplication

*
/
%

Multiply
Divide
Modulus

L?R

Additive

+
-

Binary
Plus
Binary Minus

L?R

Shift

<<
>>

Shift
Shift Right

L?R

Relational

<
<=
>
>=

Less
than
L?R
Less than or equal to
Greater
than
Greater than or equal to

Dept. of CSE, SVCET

Left

GE6151- Computer Programming

- 13 -

Equality

==
!=

Equal
Not Equal to

to

L?R

Bitwise AAND

&

Bitwise AND

L?R

10

Bitwise XOR

Bitwise XOR

L?R

11

Bitwise OR

Bitwise OR

L?R

12

Logical AND

&&

Logical AND

L?R

14

Conditional

?:

Ternary Operator

R?L

15

Assignment

=
*=
%=
/=
+=
-=
&=
^=
|=
<<=
>>=

Assignment
Assign
product
Assign
reminder
Assign
quotient
Assign
sum
Assign
difference
Assign bitwise AND
Assign bitwise XOR
Assign bitwise OR
Assign
left
shift
Assign right shift

R?L

16

Comma

Evaluate

L?R

INPUT OUTPUT OPERATIONS


Input means to feed some data into program. This can be given in the form of file
or from command line, output means to display some data on screen, printer or in any
file. Scanf() is used to read data from a key board. For outputting results we have used
extensively the function printf(). which sends results out to a terminal. We have to
include the header file is # include < stdio.h > at the beginning.
Input Function (scanf()):
The formatted input refers to input data that has been arranged in a particular
format. Input values are generally taken by using the scanf function. The syntax of scanf
function is
scanf (control string1, control string2, control string n , arg1, arg2 arg n);

Dept. of CSE, SVCET

GE6151- Computer Programming

- 14 -

The format field is specified by the control string and the arguments arg1, arg2,
.argn specifies the addrss of location where address is to be stored. The
control string specifies the field format
Example :

scanf (%d %d, &sum1, &sum2);

%c reads a single character


%d read a decimal integer
%e read a floating point value
%f read a floating point value
%g read a floating point value
%h read a short integer
%i read a decimal, hexadecimal, or octal integer
% o read an octal integer
%s read a string
%u read an unsigned decimal integer
%x read a hexadecimal integer
Output function (printf()):
The printf ( ) function is quite flexible. It allows a variable number of arguments, labels
and sophisticated formatting of output. The general form of the printf ( ) function is
Syntax :
printf (control string1, control string2, control string n , arg1, arg2 arg n);
example : printf(%d%d, a,b);
Single character input output:
The getchar function can be used to read a character from the standard input
device. The getchar syntax is Variable name = getchar():
The putchar function which in analogous to getchar function can be used for
writing characters one at a time to the output terminal. The syntax is
putchar (variable name);
Example :
in = getchar ( ) ;

// assign the keyboard input value to in.

putchar (in);

// out put in value to standard screen.

String input and output:

Dept. of CSE, SVCET

GE6151- Computer Programming

- 15 -

A string is an array or set of characters. The function gets accepts the name of the
string as a parameter, and fills the string with characters that are input from the
keyboard till newline character is encountered. The syntax is gets(variable);
The puts function displays the contents stored in its parameter on the standard screen.
The syntax is puts(variable);
Example
gets (s);
puts(s);
Decision Making Statements :
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false. There are two kinds
of decision making statements
1. if-else statements
2. Switch Statements
1. if-else statements :
If the expresion is true the body of loop will be executed otherwise the body of loop will
be skipped. The syntax is :
Syntax
if (expresion)
{
Satement 1;
.
.
.
Statement n;
}

Example program

Dept. of CSE, SVCET

Flow chart

GE6151- Computer Programming

- 16 -

#include<stdio.h>
main()
{
Int num;
Printf(Enter the number to check);
scanf(%d,&num);
if (num>0)
{
printf(The number is positive number)
}
}
Output :
Enter the number to check : 56
The number is positive number
If-else statements :
If the the given condition is to true, then the if block of code will be executed, otherwise
else block of code will be executed. The syntax is
Syntax
if (expresion)
{
If / true block;
}
else
{
else / false block;
}

Dept. of CSE, SVCET

Flow chart

GE6151- Computer Programming

- 17 -

Example program
#include<stdio.h>
main()
{
Int mark;
Printf(Enter the mark);
scanf(%d,&mark);
if (mark>=50)
{
printf(PASS)
}
else
{
printf(FAIL)
}
}
Output :
Enter the mark : 35
FAIL
Nested if else Statements
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement .
Syntax :
if(expression 1)
{
/* Executes when the expression 1 is true */
}
else if(expression 2)
{
/* Executes when the expression 2 is true */
}

Dept. of CSE, SVCET

GE6151- Computer Programming

- 18 -

else if(expression 3)
{
/* Executes when the expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example program
include <stdio.h>
main ()
{
int a = 100;
if( a == 10 )
{
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
printf("Value of a is 30\n" );
}
else
{
printf("None of the values is matching\n" );
}
printf("Exact value of a is: %d\n", a );
}
Out put
None of the values is matching
Exact value of a is: 100
Switch statements
In switch...case, expression is either an integer or a character. If the value of
switch expression matches any of the constant in case, the relevant codes are executed
and control moves out of the switch...case statement. If the expression doesn't matches
any of the constant in case, then the default statement is executed. The syntax is

Dept. of CSE, SVCET

GE6151- Computer Programming

Syntax
switch(expression)
{
case constant-expression :
statement(s);
break;
case constant-expression :
statement(s);
break;
default : /* Optional */
statement(s);
}

Example program
#include <stdio.h>
main ()
{
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
Dept. of CSE, SVCET

- 19 -

Flow chart

GE6151- Computer Programming

- 20 -

printf("Better try again\n" );


break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
}
Output
Well done
Your grade is B
Break and Continue
Two keywords that are very important to looping are break and continue. The
break command will exit the most immediately surrounding loop regardless of what the
conditions of the loop are. Break is useful if we want to exit a loop under special
circumstances
Looping Statements
Loop control statements in C are used to perform looping operations until the
given condition is true. Control comes out of the loop statements once condition
becomes false. Loops are used to repeat a block of code.
The different type of looping statements are
1. for loop
2. while loop
3. do-while loop
1.for loop
The for loop is used to execute the group of statement until the condition is true. The
Syntax of for loop is given below
Syntax

Dept. of CSE, SVCET

Flow chart

GE6151- Computer Programming

- 21 -

for (initialization; condition; counter/ update)


{
Statement 1
Statement 2
.
.
.
Statement n
}

The variable initialization allows you to either declare a variable and give it a value or
give a value to an already existing variable. The condition tells the program that while
the conditional expression is true the loop should continue to repeat itself. The counter /
update section is the control variballe of loop. The variable value can increment or
decrement

Example program
#include <stdio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
Dept. of CSE, SVCET

GE6151- Computer Programming

- 22 -

Output : 0 1 2 3 4 5 6 7 8 9
While loop
In while loop control statement, loop is executed until condition becomes false. The
syntax for while loop is

Syntax

Flow chart

while(condition)
{
Statement 1
Statement 2
.
.
.
Statement n
}
Example program
#include <stdio.h>
main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
Output : 3, 4 5 6 7 8 9
Do while loop
The loop is executed irrespective of the condition for first time. Then second time
onwards, loop is executed until condition becomes false. The syntax for do-while loop is

Dept. of CSE, SVCET

GE6151- Computer Programming

Syntax
do
{
Statement 1
Statement 2
.
.
.
Statement n
} while(condition)

Example program
#include <stdio.h>
main()
{
int i=23;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
Output : 23

Dept. of CSE, SVCET

- 23 -

Flow chart

You might also like