You are on page 1of 131

CONTENTS

1.0. C programming basics

1.1. structure of a c program

1.2. character set of C language

1.3. Define keywords and list them

1.4. List the data types used in C

1.5. (i)define constants and variables

(ii)explain the declaration & initialization of variables

1.6. List five arithmetic operators supported by C

1.7. Define an expression and show how to evaluate an arithmetic expression

1.8. (i)define assignment statement and give the syntax of assignment statement

(ii)write the syntax for nested assignment statement

(iii)list the compound/shorthand assignment operators

1.9. Explain the increment and decrement operators

1.10. Explain printf() and scanf() functions with examples

1.11. Mention various types of conversation techniques and discuss them

1.12. List the four relational operators used in C

1.13. Give the operator precedence

1.14. List the three logical operators supported by C

1.15. List the three bitwise logical operators

2.0. Conditional statements and arrays

2.1. describe the conditional expression

2.2. list the four conditional statements supported by C


2.3. write syntaxes of following conditional statements

(i) if

(ii) if..else

(iii) nested if…else

2.4. write the syntax of switch case statement and explain

2.5. write a simple program based on conditional statements

(i)write a program to find whether a given year is leap year or not

(ii)write a program to find biggest of three numbers

(iii) write a program to check whether a given number is even or odd by using bitwise
logical operator

(iv) write a program to check whether a given character is vowel or consonant by using
switch case statement

(v) write a program to perform arithmetic operations using switch case statement

2.6. list three types of iterative statements supported by C

2.7. write the syntaxes of the following iterative statements and explain

(i)while

(ii)for

(iii)do…while

2.8. differentiate while and do while loops

2.9. differentiate break & continue statements

2.10. write syntaxes of nested loops and explain

2.11. write programs baed on iterative statements

(i)write a program to find sum of natural numbers

(ii)write a program to find sum of digits of a given number

(iii) write a program to check whether the given number is Armstrong or not
(iv) write a program to print Fibonacci series using loops

(v) write a program to print even and odd numbers

(vi) write a program to check whether a given number is prime number or not

(vii) write a program to print prime numbers between two given numbers

(viii) write a program to check whether a given number is palindrome or not

2.12. define an array

(i)declaration and initialization of one dimensional array

(ii)accessing the elements in thye array

2.13. (i)write a c program to find largest/smaleest number in an array

(ii) write a c program to sort the numbers in an array in ascending order

(iii) write a c program to find sum of elements of an array

2.14. explain declaration and initialization of two dimensional array

2.15. writw a c program to perform matrix addition/subtraction/multiplication

3.0. strings,functions & pointers

3.1. define string

3.2. explain different functions used for reading and writing strings with examples

3.3. explain the string manipulation functions strcat(),strcmp(),strcpy(),strlen() with


examples

3.4. state the use of functions in C

3.5. explain declaration of a function in program

3.6. write the operation of getchar(),getch(),getche() and putchar() functions

3.7. state the use of return statement

3.8. explain the passing of parameters to the function

3.9. write simple programs on functions call techniques


3.10. define a pointer

3.11. declare a pointer,assign a pointer,initialize a pointer

3.12. explain pointer arithmetic operations with examples

3.13. differentiate address and dereferencing operators

4.0. structure &unions

4.1. define a structure in C

4.2. write a syntax of structure declaration and explain

4.3. explain the method of declaring a structure variable

4.4. explain the method of initializing a structure variable

4.5. explain the method of accessing of members of a structure

4.6. illustrate structures with a program to read&print a book database consisting of title of
book,author,no.of pages,price as fields

4.7. explain how to find size of a structure

4.8. define a union

4.9. differentiate between structure and union

4.10. state the function of pre-processor directives in C

4.11. list the six pre-processor directives

4.12. explain the conditional pre-processor directives with example

4.13. explain the unconditional pre-processor directives with example

5.0. basics of matlab

5.1. state the need for matlab in solving engineering problems

5.2. list the major difference between matlab and C

5.3. list the arithmetic operators,relational operators,logical operators in matlab

5.4. differentiate elementwise multipilication/division/power operations and array


multiplication/division/power operations
5.5. state the usage of

i)linspace operator

ii)clc,clear,who,whos commands

5.6. give the synatax and usage of decision making statements used in matlab

i)if….end statement

ii)if…else…end statement

5.7. give the syntax and usage of loop statements used in matlab

i)while loop

ii)for loop

5.8. explain the creation 1D & 2D arrays and mxn matrices in matlab

5.9. illustrate with an example the matrix operations such as

i)addition ii)subtraction iii)multiplication

iv)transpose v)inverse used in matlab

5.10. list the common input/output functions in matlab

5.11. illustrate plot commands such as

I)plot(x,y) ii)fplot() iii)title()

iv)xlabel() v)ylabel() vi)ezplot

vii)subplot() viii)bar() ix)pie() in matlab

5.12. state of usage of:

i)SIMULINK ii)GUI
UNIT-1
C programming basics
1.1.Basic structure of a C program
A C program is divided into different sections. There are six main sections to a basic c
program.

 Documentation
 Link
 Definition
 Global Declarations
 Main functions
 Subprograms

So now that the introduction is out of the way, let us jump to the main discussion. The
whole code follows this outline. Each code has a similar outline. Now let us learn about
each of this layer in detail.

Let us look at a simple code that would print the words "Hello World" −
#include <stdio.h>

int main() {
/* my first program in C */
printf("Hello, World! \n");

return 0;
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 1


1.2.Character Set of C:
The C Character set consists of upper and lowercase alphabets, digits,
special characters andwhite spaces. The alphabets and digits are altogether
as the alphanumeric character.
1. Alphabets: ABCDEF.......... Z abcdef ............. z
2. Digits: 0 1 2 3 4 5 6 7 8 9

3. Special Characters:

, Comma < Opening angle bracket > Closing angle bracket

. Period _ Underscore ( Opening parenthesis

; Semi Colon $ Dollar sign ) Closing parenthesis

: Colon % Percent sign [ Opening square bracket

? Question mark # Number sign ] Closing square bracket

‘ Single quote & Ampersand { Opening brace

“ Double quote ^ Caret } Closing brace

! Exclamation mark * Asterisk / Slash

| Vertical Bar - Minus sign \ Back slash

~ Tilde + Plus sign White Space Characters

\v Vertical tab \b blank space \n new line

\r Carriage return \f form feed \t horizontal tab

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 2


1.3.Keywords:-
We can define the keywords as the reserved or pre-defined words that hold their own
importance. It means that every keyword has a functionality of its own. Since the keywords are
basically predefined words that the compilers use, thus we cannot use them as the names of
variables. If we use the keywords in the form of variable names, it would mean that we assign a
different meaning to it- something that isn’t allowed. The C language provides a support for 32
keywords, as mentioned below:
auto break case char

const continue default do

double else enum extern

float for goto if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while

KEYWORD
KEYWORD

Keyword is a pre-defined word.

It must be written in a lowercase letter.

Its meaning is pre-defined in the c compiler.

It is a combination of alphabetical characters.

It does not contain the underscore character.

Note: In C programming, you have to declare the variable before using it in the program.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 3


1.4.Data types used in c
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.
The types in C can be classified as follows −

Sr.No. Types & Description

1
Basic Types
They are arithmetic types and are further classified into: (a) integer types
and (b) floating-point types

Primary Data Types:


The C language has 5 basic (primary or primitive) data types, they are:
Integer - Used to store whole numbers like 1, 2, 100, 1000, etc.
Floating-point - Decimal point or real numbers values like 99.9, 10.5, etc.

Character - ASCII character set or generally a single alphabet like 'a', 'B', etc.
Double - Very large numeric values which are not allowed in Integer or Floating
point type.
Void - This means no value. This data type is mostly used when we define
functions.
Derived Data Types:
The C language supports a few derived data types. These are:
Arrays –
The array basically refers to a sequence (ordered sequence) of a
finite number of dataitems from the same data type sharing one
common name.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 4


Structures –
A collection of various different types of data type items that get
stored in a contagioustype of memory allocation is known as
structure in C.
*Note – In some of the situations, we can also call the structures
and unions to be UDT(User-defined Data Types).

Unions –
The unions are very similar to the structures. But here, the memory
that we allocate tothe largest data type gets reused for all the other
types present in the group.

Pointers –
The Pointers in C language refer to some special form of variables that one
can use for
holding other variables’ addresses.
Function –
A Function in C refers to a self-contained block of single or multiple
statements. It has itsown specified name.

User Defined Data Types:


C Supports a feature known as "type definition" that allows users to define
identifier that wouldrepresent an existing data type. The user defined data
types have an two types.
1. typedef 2. enumerated data type
1.5.

1.5.1.Constants:-
A constant is also identifier whose value can’t be hanged during the program execution. In ‘C’
language we can declare constant using “const” or “#define” macro. Constants are also called as
Literals. ‘C’ Constants is divided into 2 categories.
1. Numeric Constants
2. Character Constants

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 5


1. Numeric Constants:-
Numeric Constants are again divided into 2 types
a. Integer constants
b. Real constants / Floating point constant
a. Integer constants:- Integer constant accepts only integer data type values. They won’t
accept point values. They can be either +Ve or –Ve. Integer constants are again
divided into 2 categories.
i. infix int const
ii. suffix int const

i. infix int const:-


Infix integer constants indicates base of the value in which it has to be
read. These are again divided into 4 types.

ii. suffix int const:-


An integer literal can also have a suffix that is a combination of U and L,
for unsigned and long, respectively.
Eg:- 123 /*By default it is consider has integer */
123U, 123u /*It means unsigned integer */
123l, 123L /*Long integer constant */
123ul /*Unsigned long integer constant */
078 /*Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
85 /* decimal */
0213 /*octal*/
0x4b /*hexadecimal*/
30 /*int*/
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
b. Real Constant / Floating Point Constant:-
Real constants also know as floating point constants. These are having fractional part
either +Ve or –Ve. These real constant again 2 forms.

1. Decimal form – Decimal form it must contain decimal part. Eg:- 3.423, -8.964
2. Exponential form–Generally real or floating point constants are represented by using
a format
Mantissa e Exponent

Mantissa: -The part appearing before e, Mantissa is a real number expressed in


decimal notation.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 6


Exponent: -Exponent is an integer number, it is +Ve or –Ve
Letter 'e': -Letter ‘e’ separation the Mantissa and Exponent that can be written in
either lowercase (or) uppercase.
Eg:- 0.65x104 = 0.65e4
-2
12.5x10 = 12.5e-2
5
1.5x10 = 1.5e+5
3
3.18x10 = 3.18E3
-1.2x10-1 = -1.2E-1

2. Character Constants:-
Character constants are divide into 3 types.
a. Single Character Constants.
A character constants which has been specified with in single
quotes. This character maybe Letter (a b c etc…) or maybe Digit (0
to 9) or maybe Symbol (% # < ? etc…)
Eg:- ‘a’Character(or) ‘7’ Digit(or)& % @ Symbol
b. String Constants
A group of characters which are enclosed between double quotes
are called as string constants.
Eg:- “Hello” (or) “5+10”
c. Back Slash Character Constants
 There are some characters which have special meaning in C
language.
 They should be preceded by backslash symbol to make use of
special function of them.
 Given below is the list of special characters and their purpose.

S.No. Escape Sequence Character represented


1 \a Alert (bell, alarm)
2 \b Backspace
3 \f Form feed (new page)
4 \n New-line
5 \r Carriage return
6 \t Horizontal tab
7 \v Vertical tab
8 \' Single quotation mark
9 \" Double quotation mark
10 \? Question mark
11 \\ Backslash
12 \0 Null character

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 7


1.5.2.Variables:-
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location.
For Example:int playerScore = 95;
Here, playerScore is a variable of int type. Here, the variable is assigned an integer value 95.

Rules for naming a variable:


 A variable name can only have letters (both uppercase and lowercase letters), digits
and underscore.
 The first letter of a variable should be either a letter or an underscore.
 The variable name should not be a keyword.
 White space is not allowed.
 There is no rule on how long a variable name (identifier) can be. However, you may
run into problems in some compilers if the variable name is longer than 31 characters.
Note: In C programming, you have to declare the variable before using it in the
program.

The variable declaration indicates that the operating system is going to reserve a piece of
memory with that variable name.

Variable declaration

The syntax for variable declaration is as follows −


type variable_name;
or
type variable_name, variable_name, variable_name;
For example,
Int a,b;
float c;
double d;

Here, a, b, c, d are variables. The int, float, double are the data types.

Variable initialization

The syntax for variable initialization is as follows −


data type variablename=value;

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 8


For example,
int width, height=20;
char letter='R';
float base, area; //variable declaration
double d;
/* actual initialization */
width = 10;
area = 26.5;

1.6.list the arithmetic operators supported by C


The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer division. B%A=0

++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

Example
Try the following example to understand all the arithmetic operators available in C −
#include <stdio.h>

main() {

int a = 21;
int b = 10;

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 9


int c ;

c = a + b;
printf("Line 1 - Value of c is %d\n", c );

c = a - b;
printf("Line 2 - Value of c is %d\n", c );

c = a * b;
printf("Line 3 - Value of c is %d\n", c );

c = a / b;
printf("Line 4 - Value of c is %d\n", c );

c = a % b;
printf("Line 5 - Value of c is %d\n", c );

c = a++;
printf("Line 6 - Value of c is %d\n", c );

c = a--;
printf("Line 7 - Value of c is %d\n", c );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
1.7. Evaluation of Arithmetic Expression in c
An arithmetic expression in c is a combination of variables, constants, and operators
arranged as per the syntax of the language.C can handle any complex mathematical
expressions.

Examples of C expressions:
Algebraic Expression C Expression

axb–c a*b–c

(m + n)(x + y) (m + n) * (x + y)

ab / c (a*b) / c

3x2 + 2x + 1 (3 * x * x) + (2 * x) + 1

x/y+c x/y+c

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 10


Evaluation of Arithmetic Expression in c
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 the
result 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.
Examples of Evaluation Statement:

x = a * b - c;

y = b / c * a;

z = a - b / c + d;

When these statements are used in a program, the variables x, y, z, a, b, c and


d must be defined before used in the expressions.
 The blank space around an operator is optional and adds only to improve
readability.
Program to illustrate the concept of evaluation of expressions:

#include<stdio.h>

int main()

// Declaration of Variables

float a, b, c, x, y, z;

// Assigning Values to variables a, b, c

a = 10;

b = 12;

c = 2;

// Expressions

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 11


x = a - b / 3 + c * 2 - 1;

y = a - b / (3 + c ) * (2 -1);

z = a - (b / (3 + c) * 2) - 1;

// Print values of x , y , z after expression evaluation

printf("x = %f\n", x);

printf("y =%f\n", y);

printf("z =%f\n", z);

return 0;

1.8. Assignment operators:


Using assignment operators, we can assign value to the variables. Equality sign (=) is used as an
assignment operator in C.
Ex1: X=a+b;
Ex2: X=10;
Basically, the value of right-side operand will be assigned to the left side operand.

Pictorial Explanation:

Classified into 2 Types:


1) Simple assignment
2) Compound assignment / Short hand assignment

1) Simple assignment

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 12


2) Compound assignment / Short hand assignment

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
clrscr();
printf (“\na=%d”,a);
printf (“\n(a+=10)=%d”,a+=10);
printf (“\n(a-=10)=%d”,a-=10);
printf (“\n(a*=10)=%d”,a*=10);
printf (“\n(a/=10)=%d”,a/=10);
printf (“\n(a%=10)=%d”,a%=10);
getch();
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 13


1.9.increment and decrement operators:
C has two special unary operators called increment (++) and decrement (--) operators. These
operators increment and decrement value of a variable by 1.
Increment operator (++)
It is used to increment the value of a variable by 1. These are 2 types :
i) Pre increment
ii) Post increment

i) Pre increment :
Increment operator is placed before the operand in pre increment and the value is first
incremented and then operation is performed on it.

Eg: a=10;
b=++a;

Output:‘a’ value 11
‘b’ value 11

ii) Post increment:


Increment operator is placed after the operand in post increment and the value is
incremented after the operation is performed.

Eg:a=10;
b=a++;

Output:‘a’ value 11
‘b’ value 10

Decrement operator (- - )
It is used to Decrement the value of a variable by 1. These are 2 types :
i) Pre Decrement
ii) Post Decrement

i) Pre Decrement :
Decrement operator is placed before the operand in pre Decrement and the value is first
Decremented and then operation is performed on it.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 14


Eg:a=10;
b= - - a;
Output:‘a’ value 9
ii) Post Decrement:
Decrement operator is placed after the operand in post Decrement and the value is
Decremented after the operation is performed

Eg:a=10;
b=a-- -- ;

Output:‘a’ value 9
‘b’ value 10

1.10. Explain printf() and scanf() functions with examples


The printf() function is used to display output and the scanf() function is used to take input from
users.

The printf() and scanf() functions are commonly used functions in C Language. These functions
are inbuilt library functions in header files of C programming.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 15


printf() Function
In C Programming language, the printf() function is used for output.

printf() function can take any number of arguments. First argument must be enclosed within the
double quotes “hello” and every other argument should be separated by comma ( , ) within the
double quotes.

Important points about printf():

 printf() function is defined in stdio.h header file. By using this function, we can print the
data or user-defined message on monitor (also called the console).
 printf() can print a different kind of data format on the output string.
 To print on a new line on the screen, we use “\n” in printf() statement.

C language is case sensitive programming language. For example, printf() and scanf() in lowercase
letters treated are different from Printf() and Scanf(). All characters in printf() and scanf() builtin
functions must be in lower case.

Syntax

printf("format specifier",argument_list);

The format string for output can


be %d (integer), %c (character), %s (string), %f (float) %lf (double) and %x (hexadecimal) variable.

Simple Example of printf() Function

#include<stdio.h>

int main()

int num = 450;

// print number

printf("Number is %d \n", num);

return 0;

Output : Number is 450

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 16


scanf() Function

The scanf() function is used to read input data from the console.

The scanf() function is builtin function available in the C library. scanf() function can read
character, string, numeric & other data from keyboard in C language.

scanf() reads formatted data from user and assign them in the variables provided the additional
arguments. Additional arguments must point to variables that have the same datatype as of user
input data format.

Syntax
scanf("format specifier",argument_list);

Simple Example of scanf() Function

#include<stdio.h>

int main()

int x;

printf("enter the number =");

scanf("%d",&x);

printf("The number is=%d",x);

return 0;

Output Window

enter the number =10


The number is=10

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 17


1.11.Mention various types of conversation techniques
Type conversion in C is the process of converting one data type to another. The type conversion is
only performed to those data types where conversion is possible. Type conversion is performed
by a compiler. In type conversion, the destination data type can’t be smaller than the source data
type. Type conversion is done at compile time and it is also called widening conversion because
the destination data type can’t be smaller than the source data type. There are two types of
Conversion:

Implicit Type Conversion


(Automatic type conversion)
(Type Promotion) 2. Explicit Type Conversion2 types
1. Implicit type conversion
2. Explicit type conversion
 Implicit type conversion is automatically done by the compiler by converting smaller data
type into a larger data type.
Eg: int i,x;
float f;
double d;
long int l;
Here, the above expression finally evaluates to a’double’ value

Explicit type conversion is done by the user by using (type) operator

Eg: int a,c;


float b;
c = (int) a + b

int float

float

int

Here, the resultant of ‘a+b’ is converted into ‘int’ explicitty and then assigned to ‘c’
Program:
#include<stdio.h>
#include<conio.h>
Void main ( )
{
printf (“\nval1=%d”, 5/2); Output
printf (“\nval2=%f”, 5.5/2); 2
printf (“\nval3=%f”, (float) 5/2); 2.75
getch(); 2.5
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 18


1.12.List the four relational operators used in C
The following table shows all the relational operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then −

Operator Description Example

== Checks if the values of two operands are equal or not. If yes, (A == B)


then the condition becomes true. is not
true.

!= Checks if the values of two operands are equal or not. If the (A != B)


values are not equal, then the condition becomes true. is true.

> Checks if the value of left operand is greater than the value of (A > B)
right operand. If yes, then the condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right (A < B)
operand. If yes, then the condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to (A >= B)
the value of right operand. If yes, then the condition becomes is not
true. true.

<= Checks if the value of left operand is less than or equal to the (A <= B)
value of right operand. If yes, then the condition becomes true. is true.

Example
Try the following example to understand all the relational operators available in C −
#include <stdio.h>
main() {

int a = 21;
int b = 10;
int c ;

if( a == b ) {
printf("Line 1 - a is equal to b\n" );
} else {
printf("Line 1 - a is not equal to b\n" );
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 19


if ( a < b ) {
printf("Line 2 - a is less than b\n" );
} else {
printf("Line 2 - a is not less than b\n" );
}

if ( a > b ) {
printf("Line 3 - a is greater than b\n" );
} else {
printf("Line 3 - a is not greater than b\n" );
}

/* Lets change value of a and b */


a = 5;
b = 20;

if ( a <= b ) {
printf("Line 4 - a is either less than or equal to b\n" );
}

if ( b >= a ) {
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
1.13.Give the operator precedence
Operator precedence determines which operator is performed first in an expression with
more than one operators with different precedence.

For example: Solve 10 + 20 * 30

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 20


Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 21


1.14.Logical operators:
The logical operators are used to test more than one condition, and these are used to combine 2
(or) more expressions logically. They are
1. && (Logical AND)
2. || (Logical OR)
3. ! (Logical NOR)

Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf(“Enter the values of a&b=”);
scanf(“%d%d”,&a,&b);
printf (“\n(a>b)&&(a<c)=%d”,(a>b)&&(a<b));
printf (“\n(a>b)||(a<b)=%d”,(a>b)||(a<b));
printf (“\n!(a>b)=%d”,!(a>b));
getch();
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 22


1.15. List the three bitwise logical operators
The following table lists the Bitwise operators supported by C. Assume variable 'A' holds
60 and variable 'B' holds 13, then −

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12,
both operands. i.e., 0000 1100

| Binary OR Operator copies a bit if it exists in either (A | B) = 61, i.e.,


operand. 0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) = 49, i.e.,
operand but not both. 0011 0001

~ Binary One's Complement Operator is unary and has the (~A ) = ~(60),
effect of 'flipping' bits. i.e,. 1100 0011

<< Binary Left Shift Operator. The left operands value is


A << 2 = 240
moved left by the number of bits specified by the right
i.e., 1111 0000
operand.

>> Binary Right Shift Operator. The left operands value is


A >> 2 = 15 i.e.,
moved right by the number of bits specified by the right
0000 1111
operand.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 23


UNIT – II
CONDITIONAL STATEMENTS AND ARRAYS
2.1.conditional expression:
The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements which depends upon the output of the expression. It is represented
by two symbols, i.e., '?' and ':'
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement
is also a decision-making statement.
Syn:- Expression1? expression2: expression3;

Meaning of the syntax :


• In the above syntax, the expression1 is a Boolean condition that can be either
True or False value.
• If the expression1 results into a true value, then the expression2 will execute.
• The expression2 is said to be true only when it returns a non-zero value.
• If the expression1 returns false value then the expression3 will execute.
• The expression3 is said to be false only when it returns zero value.

Program:
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a=10,b=5;
clrscr();
c=(a>b)?a:b;
printf (“Biggest Value is=”,c);
getch();
}
Output: Biggest value is=10

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 24


2.2.list the four conditional statements supported by C
Conditional Statements in C programming are used to make decisions based on the
conditions. Conditional statements execute sequentially when there is no condition
around the statements.
the different types of conditional statements are available in C language.

1. if statement
2. if else
3. if-else-if
4. switch

2.3.syntaxes of following conditional statements


(i) Simple if statement:
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is TRUE,
it executes the statement or block of statements. If the condition is FALSE, it skips the execution.
The general syntax and execution flow of the simple if statement is as follows...

Simple if statement is used when we have only one option that is executed or skipped based on a
condition.

Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a;
clrscr();
printf (“enter a number”);
scanf (“%d”, &a);
if (a>50)
{

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 25


a=a*10;
}
printf(“a=%d”,a);
}

Eg1:
Input
enter a number 60
Output
a=600

Eg2:
Input
enter a number 20
Output
a=20

(ii) if else statement:


 If –else statement takes care of true as well as false conditions.
 ‘Statement block-1’ is executed when the condition is true and ‘Statement block-2’ (or)
‘else block’ is executed when the condition is false.
Syntax:
if (condition)
{
Statement block1;
}
else
{
Statement block2;
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 26


Program
/* checking for even (or) odd number */
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
printf (“enter a number”);
scanf (“%d”, &n);
if (n%2 ==0)
{
printf (“%d is even number”, n);
}
else
{
printf( “%d is odd number”, n);
}
getch();
}
Eg1:
Input
enter a number 10
output
10 is even number

Eg2:
Input
enter a number 5
output
5 is odd number

(iii) Nested if - else statement:


The if-else statement is placed within another if-else statement such methods are called nested
if-else statement.
Syntax:
if (condition1)
{
if (condition2)
{
Statement block1;
}

else
{
Statement block2;
}
}

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 27


else
{
if (condition3)
{
Statement block3;
}
else
{
Statement block4;
}
}

Flow Chart:

Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf (“enter the values of a,b,c=”);
scanf (“%d%d%d”, &a,&b,&c);
if (a>b)
{
if (a>c)
printf (“%d is largest”, a);
else
printf (“%d is largest”, c);
}
else

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 28


{
if (b>c)
printf (“%d is largest”, b);
else
printf (“%d is largest”, c);
}
Printf(“the values of a,b,c are a=%d b=%d c=%d”,a,b,c);
getch();
}

input
enter the values of a,b,c = 10 20 30
output:
30 is largest
the values of a,b,c are a=10 b=20 c=30
2.4.syntax of switch case statement and explain
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called switch
variable. Here, We can define various statements in the multiple cases for the different values
of a single variable.

Syntax:
switch(expression)
{
case value1:
Statements
break;
case value2:
Statements
break;
….default: code to be executed if all cases are not matched;
;
}
First, the integer expression specified in the switch statement is evaluated. This value is then
matched one by one with the constant values given in the different cases. If a match is found,
then all the statements specified in that case are executed along with the all the cases present
after that case including the default statement. No two cases can have similar values. If the
matched case contains a break statement, then all the cases present after that will be skipped,
and the control comes out of the switch. Otherwise, all the cases following the matched case
will be executed.

When a case value matches with the switch value, the execution starts from that particular
case. This execution flow continues with next case statements also. To avoid this, we use

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 29


"break" statement at the end of each case. That means the break statement is used to
terminate the switch statement. However it is optional.

Example Program | Display pressed digit in words.


#include <stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;

switch( n )
{
case 0:
printf("ZERO") ;
break ;
case 1:
printf("ONE") ;
break ;
case 2:
printf("TWO") ;
break ;
case 3:
printf("THREE") ;
break ;
case 4:
printf("FOUR") ;
break ;
case 5:
printf("FIVE") ;
break ;
case 6:
printf("SIX") ;
break ;
case 7:
printf("SEVEN") ;
break ;
Output 1:
case 8:
Enter any digit: 5
printf("EIGHT") ;
FIVE
break ;
case 9:
Output 2:
printf("NINE") ;
Enter any digit: 15
break ;
Not a Digit
default:
printf("Not a Digit") ;

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 30


}
getch() ;
}
2.5.write a simple program based on conditional statements
write a program to find whether a given year is leap year or not

#include <stdio.h>
int main() {
int year;
year = 2016;

if (((year % 4 == 0) && (year % 100!= 0)) || (year%400 == 0))


printf("%d is a leap year", year);
else
printf("%d is not a leap year", year);

return 0;
}

Output

2016 is a leap year

write a program to find biggest of three numbers

#include <stdio.h>
int main()
{
int A, B, C;

printf("Enter three numbers: ");


scanf("%d %d %d", &A, &B, &C);

if (A >= B && A >= C)


printf("%d is the largest number.", A);

else if (B >= A && B >= C)


printf("%d is the largest number.", B);

else
printf("%d is the largest number.", C);
return 0;
}

Output:
Enter the numbers A, B and C: 2 8 1
8 is the largest number.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 31


write a program to check whether a given number is even or odd by using bitwise logical
operator
#include <stdio.h>

int main()
{
int num;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);

if(num & 1)
{
printf("%d is odd.", num);
}
else
{
printf("%d is even.", num);
}

return 0;
}

Output :
Enter any number: 15
15 is odd.

write a program to check whether a given character is vowel or consonant by using switch
case statement

#include <stdio.h>
int main() {
char c;
printf("Enter an Alphabet\n");
scanf("%c", &c);

switch(c) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 32


case 'o':
case 'O':
case 'u':
case 'U': printf("%c is VOWEL", c);
break;
default: printf("%c is CONSONANT", c);
}

return 0;
}

Output
Enter an Alphabet
e
e is VOWEL
Enter an Alphabet
Z
Z is CONSONANT

write a program to perform arithmetic operations using switch case statement

#include<stdio.h>
#include<conio.h>
int main()
{
int a,b;
int op;
printf(" 1.Addition\n 2.Subtraction\n 3.Multiplication\n
4.Division\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 33


break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
return 0;
}

Output :

1.Addition
2.Subtraction
3.Multiplication
4.Division
Enter the values of a & b: 20 15
Enter your Choice : 1
Sum of 20 and 15 is : 35

2.6.three types of iterative statements supported by C


By using these iterative control structures we can perform a set of statements repeatedly until the given
condition is satisfied.

 Repetition is also called Iteration, The CLanguage supports for Repetition looping
statements by using a single statement (or) set of statements can be executed repeatedly.
Thus we can reduce the length of program by using these statements in a program.
 The repetition of execution of block of statements as long as some condition is true is called
looping.
 Basically there are two types looping statements available. Those loops which check the test
condition at the entry-level and other checks test condition at the exit-level.
 The entry-level test will exit if the test condition is not satisfied where as exit-level loops
allow execution of atleast one iteration, before test condition is checked.

C-Language supports 3 types Looping /Repetitive(or)Iterative Control Statements:


1. while loop
2. do-while Loop
3. for loop

A loop basically consists of three parts:


a. Initialization
b. Test expression
c. Increment / Decrement or update value.

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 34


2.7.syntaxes of while,for and do…while

while :
The statements within the while loop would keep on getting executed till the condition remains
true. When the condition becomes false, the control passes to the first statement that follows
the body of the loop. This is a entry-level looping statement, we are checking the condition at
entry level itself.

Syntax:
while (condition )
{
Statements to be executed

Flow-Chart of while :

Prepared by Mr.BANDARU SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page | 35


Here the condition can be any valid expression. So as long as the expression evaluates to a non-
zero value the statements with in the loop would get executed.
Note:
1. The loop counter variable can be integer (or) float.
2. This is also called pre-test looping statement.
3. The while loop comes under conditional controlled loops.

Example : to print 10 natural numbers using while loop

#include<stdio.h>

int main()
{
int i=1;
while(i<=10)
{
printf("%d \n",i);
i++;
}
return 0;
}

Output
1
2
3
4
5
6
7
8
9
10

do-while loop :
do while loop is similar to while loop with the only difference that it checks for the condition
after executing the statements, and also exit control Loop.
 The body of do...while loop is executed once. Only then, the test expression is evaluated.
 If the test expression is true, the body of the loop is executed again and the test expression is
evaluated.
 This process goes on until the test expression becomes false.
 If the test expression is false, the loop ends.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 36


Syntax:

do
{
statements to be executed
}while(Condition);

Example : to print 10 natural numbers using do while loop


#include<stdio.h>
int main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
return 0;
}

Output
1
2
3
4
5
6
7
8
9
10

For Loop:
The for loop starts with a for statement followed by a set of parameters inside the parenthesis.
The for statement is in lower case. Please note that this is case sensitive, which means the for
command always has to be in lower case in C programming language. The initialization
statement describes the starting point of the loop, where the loop variable is initialized with a
starting value. A loop variable or counter is simply a variable that controls the flow of the loop.
The test expression is the condition until when the loop is repeated. Update statement is
usually the number by which the loop variable is incremented.

Syntax:
for(initialization;test-condition;increment/decrement loop counter)
{
body of loop;
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 37


Flow-Chart of for:

Example : to print 10 natural numbers using for loop


#include<stdio.h>
int main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
return 0;
}

Output

1
2
3
4
5
6
7
8
9
10
.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 38


2.8.difference between while and do while loops:

While Do While

It checks the condition first and then executes This loop will execute the statement(s) at least once, then
statement(s) the condition is checked.

While loop allows initialization of counter variables Do while loop allows initialization of counter variables
before starting the body of a loop. before and after starting the body of a loop.

It is an entry controlled loop. It is an exit controlled loop.

We do not need to add a semicolon at the end of a We need to add a semicolon at the end of the while
while condition. condition.

In case of a single statement, we do need to add


Brackets are always needed.
brackets.

In this loop, the condition is mentioned at the


The loop condition is specified after the block is executed.
starting of the loop.

Statement(s) can be executed zero times if the


Statement is executed at least once.
condition is false.

Generally while loop is written as: Generally do while loop is written as:
while (condition) { do{
Statements; // loop body Statements; //loop body
} } while (condition);

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 39


2.9.difference between break & continue statements :
Parameters Break Statement Continue Statement

Construct a This statement allows a user to exit a It does not allow a user to exit an overall
loop. loop's overall structure. loop structure.

Statements The break statement can be used in The switch statement and the continue
that switch conjunction with the switch statement. statement are incompatible. You can still
and loop It can also be used inside the while use it in for loops, do-while loops, and
loop, do-while loop, and for loop. It while loops. This means that continue can
means that both the loop and the only happen in a loop, not in a switch.
switch can easily break.

Control When the control reaches the break The control passes from the beginning of a
statement in a loop construct, it exits loop statement to the continue statement
immediately. as soon as it encounters it.

Function The break statement causes a loop or a The continue statement does not end the
switch to stop running in the middle of loop, but rather leads it to the next
a case's execution. It means that if a iteration. It means that if a loop
switch or a loop encounters a break, it encounters a continue statement, it will
will end abruptly. complete all of its iterations. The continue
statement is used to skip the statements
that follow the continue in a loop.

Syntax It can be written as: It can be written as:


break; continue;

2.10.syntaxes of nested loops :


A loop inside another loop is called a nested loop. The depth of nested loop depends on the
complexity of a problem. We can have any number of nested loops as required. Consider a
nested loop where the outer loop runs n times and consists of another loop inside it. The inner
loop runs m times. Then, the total number of times the inner loop runs during the program
execution is n*m.

Types of nested loops

 Nested while loop


 Nested do-while loop
 Nested for loop

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 40


Note: There can be mixed type of nested loop i.e. a for loop inside a while loop, or a while loop
inside a do-while loop.

Nested while loop


A while loop inside another while loop is called nested while loop.

Syntax of Nested while loop flow-chart

while (condition1)

statement(s);

while (condition2)

statement(s);

... ... ...

... ... ...

Example : C program to print the number pattern.

#include <stdio.h>
int main()
{
int i=1,j;
while (i <= 5)
{
j=1;
while (j <= i )
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 41
{
printf("%d ",j);
j++;
}
printf("n");
i++;
}
return 0;
}

Output:
1
12
123
1234
12345

In this program, nested while loop is used to print the pattern. The outermost loop runs 5 times
and for every loop, the innermost loop runs i times which is 1 at first, meaning only “1” is
printed, then on the next loop it’s 2 numbers printing “1 2” and so on till 5 iterations of the loop
executes, printing “1 2 3 4 5”. This way, the given number pattern is printed.

Nested do-while loop


A do-while loop inside another do-while loop is called nested do-while loop.

Syntax of Nested do-while loop


Do

{
statement(s);
do
{
statement(s);
... ... ...
}while (condition2);
... ... ...
}while (condition1);

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 42


Example : C program to print the given star pattern.
#include <stdio.h>
int main()
{
int i=1,j;
do
{
j=1;
do
{
printf("*");
j++;
}while(j <= i);
i++;
printf("n");
}while(i <= 5);
return 0;
}

Output :
*
**
***
****
*****

Nested for loop:


A for loop inside another for loop is called nested for loop.

Syntax of Nested for loop

for (initialization; condition; increment/decrement)


{
statement(s);
for (initialization; condition; increment/decrement)
{
statement(s);
... ... ...
}
... ... ...
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 43


Flowchart of Nested for loop

Example 3: C program to print all the composite numbers from 2 to a certain number
entered by user.
#include<stdio.h>
#include<math.h>
int main()
{
int i,j,n;
printf("Enter a number:");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
for(j=2;j<=(int)pow(i,0.5);j++)
{
if(i%j==0)
{
printf("%d is compositen",i);
break;
}
}
}
return 0;
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 44


Output :
Enter a number:15
4 is composite
6 is composite
8 is composite
9 is composite
10 is composite
12 is composite
14 is composite
15 is composite

2.11.programs based on iterative statements :

Write a C program to find the sum of first ‘n’ natural numbers


#include <stdio.h>
int main()
{
int n, i, sum = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
i = 1;
while ( i <=n )
{
sum += i;
i++;
}
printf("Sum = %d",sum);
}
Output:
Enter a positive integer: 12
Sum = 78

Write a C program to find sum of digits of a given number


#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 45


sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}

Output:

Enter a number:654
Sum is=15
Enter a number:123
Sum is=6

Write a Program to check whether a given number is Armstrong number or not


Armstrong number is a number that is equal to the sum of cubes of its digits. For example: 0, 1,
153, 370, 371 and 407 are the Armstrong numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int n, rem,sum=0,temp;
clrscr();
printf(“\n enter any number:\n”);
scanf(“%d”,&n);
temp=n;
while(n!=0)
{
rem=n%10;
sum=sum+rem*rem*rem;
n=n/10;
}
if(sum==temp)
printf(“given number is Armstrong number”);
else
printf(“given number is not Armstrong.c”);
getch();
}
Output:
enter any number
407
given number is Armstrong number

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 46


Write a program to print the Fibonacci series upto n
Fibonacci Series in C: In case of fibonacci series, next number is the sum of previous two
numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are
0 and 1.
#include<stdio.h>
#include<conio.h>
void main()
{
int n1=0,n2=1,n3,i,n;
clrscr();
printf("enter the range of series");
scanf("%d",&n);
printf("\n fibonacci series is");
printf("\t%d\t%d",n1,n2);
for(i=2;i<n;i++)
{
n3=n1+n2;
printf("\t%d",n3);
n1=n2;
n2=n3;
}
getch();
}
Output:
enter the range of series 5
Fibonacci series is 0 1 1 2 3

Write a program to print even and odd numbers


#include<stdio.h>
int main() {
int number;
int min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);
printf("Enter the maximum range: ");
scanf("%d",&max);
printf("Odd numbers in given range are: ");
for (number = min;number <= max; number++)
if(number % 2 !=0)
printf("%d ",number);
printf("\nEven numbers in given range are: ");
for (number = min;number <= max; number++)
if(number % 2 ==0)
printf("%d ",number);
return 0;
}
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 47
Result

Enter the minimum range: 1


Enter the maximum range: 20
Odd numbers in given ranges are: 1 3 5 7 9 11 13 15 17 19
Even numbers in given ranges are: 2 4 6 8 10 12 14 16 18 20

Write a program to check whether given no is prime or not.


2, 3, 5, 7, 11 and 13 are few prime numbers.
Above numbers can only be divided evenly by 1 or itself, so these numbers are prime numbers.

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,count=0;
clrscr();
printf("enter a number \n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
printf("given no is prime");
else
printf("given no is not prime");
getch();
}
Output:
enter a number
7
given no is prime

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 48


write a program to print prime numbers between two numbers
#include <stdio.h>
int main(){
int number1,number2,i,j,flag;
printf("enter the two intervals:");
scanf("%d %d",&number1,&number2);
printf("prime no’s present in between %d and %d:",number1,number2);
for(i=number1+1;i<number2;i++){// interval between two numbers
flag=0;
for(j=2;j<=i/2;++j){ //checking number is prime or not
if(i%j==0){
flag=1;
break;
}
}
if(flag==0)
printf("%d
",i);
}
return 0;
}

Output

enter the two intervals:10 50


the number of prime numbers present in between 10 and 50:11
13
17
19
23
29
31
37
41
43
47

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 49


write a program to check whether a given number is palindrome or not
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
printf("palindrome number ");
else
printf("not palindrome");
return 0;
}

Output:

enter the number=151


palindrome number

enter the number=5621


not palindrome number

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 50


2.12.ARRAY
An array is a collection of variables of the same type that are referred to through
common name. A specific element in an array is accessed by an index. In C, all arrays consist of
contiguous memory locations. The lower address corresponds to the first element and the
higher address to the last element. Arrays can have from One to Several Dimensions. The most
common array is the string, which is simply an array of characters terminated by a NULL. Arrays
and pointers are closely related.

Definition :
An array is defined as the collection of similar type of data items stored at contiguous
memory locations, sharing a common name but separated by subscript or index values.
Arrays can be classified into 3 types.
1. One Dimensional / Single Dimensional Array.
2. Two Dimensional Array.
3. Multi Dimensional Array.
(i)declaration and initialization of one dimensional array
One Dimensional / Single Dimensional Array :
We can visualize a one-dimensional array in C as a single row to store the elements.
Array Declaration:
To create an array, define the data type (like int) and specify the name of the array followed by
square brackets [].
Initialization:
An array can be initialized in 2 ways.
a) Compile time initialization
b) Runtime initialization

To insert values to it, use a comma-separated list, inside curly braces

Syntax : Datatype arrayname[arraysize];


Eg : int marks[4] = {25, 50, 75, 100}; /*Runtime initialization*/

The array elements are called by array name followed by the element numbers. A specific
element of an array can be accessed by an index and each element of the array starts with the
index of 0 to (n-1), where n is the size of the array.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 51


As per the above illustration, there are some of the following important points
 Index starts with 0.
 The array's length is 10, which means we can store 10 elements.
 Each element in the array can be accessed via its index.

The advantage of an array is as follows −


The ability to use a single name to represent a collection of items and to refer to an item
by specifying the item number enables the user to develop concise and efficient
programs.
For example,
float height [50]
This declares ‘height’ to be an array containing 50 float elements.
int group[10]
This declares the ‘group’ as an array to contain a maximum of 10 integer constants.
Individual elements are identified using "array subscripts". While complete set of values
are referred to as an array, individual values are called "elements".
Accessing the array elements is easy by using an array index.

For Example:
Suppose we have an integer array of length 5 whose name is marks.

int marks[5] = {5,2,9,1,1};

program to illustrate one dimensional arrays


#include<stdio.h>
int main()
{
int arr[5], i;

for(i = 0; i < 5; i++)


{
printf("Enter a[%d]: ", i);
scanf("%d", &arr[i]);
}

printf("\nPrinting elements of the array: \n\n");

for(i = 0; i < 5; i++)


{
printf("%d ", arr[i]);
}

return 0;
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 52


Output:

Enter a[0]: 11
Enter a[1]: 22
Enter a[2]: 34
Enter a[3]: 4
Enter a[4]: 34

Printing elements of the array:

11 22 34 4 34

2.13. (i)write a c program to find largest/smallest number in an array


#include <stdio.h>
int main()
{
int arr[100], n, i, small, large;

printf("Enter the number of elements you want to insert:");


scanf("%d", &n);

for (i = 0; i < n; i++)


{
printf("Enter element %d : ", i + 1);
scanf("%d", &arr[i]);
}

small = arr[0];
large = arr[0];

for (i = 1; i < n; i++)


{
if (arr[i] < small)
{
small = arr[i];
}

if (arr[i] > large)


{
large = arr[i];
}
}
printf("\nLargest element is : %d", large);
printf("\nSmallest element is : %d", small);
return 0;
}
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 53
Output

Enter the number of elements you want to insert : 6


Enter element 1 : 15
Enter element 2 : 2
Enter element 3 : 36
Enter element 4 : 18
Enter element 5 : 25
Enter element 6 : 30

Largest element is : 36
Smallest element is : 2

(ii) write a c program to sort the numbers in an array in ascending order

#include<stdio.h>
#include<conio.h>
void main()
{
int a[100];
int n,i,j,t;
clrscr();
printf("Enter no.of elements:");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
printf("\nAfter sorting");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
getch();
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 54


Output:
Enter no.of elements:5
20 40 10 50 30

After sorting
10
20
30
40
50
(iii) write a c program to find sum of elements of an array

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,x[20],sum=0;
clrscr();
printf("Enter array size=");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&x[i]);
for(i=0;i<n;i++)
{
printf("\n%d",x[i]);
sum=sum+x[i];
}
printf("\nThe sum of the array elements=%d",sum);
getch();
}

Output :
Enter array size=5

10
8
2
5
5
The sum of the array elements=30

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 55


2.14.two-dimenssional array:
C support multidimensional arrays. The simplest form of the multidimensional array is the two-
dimensional array. A two-dimensional array is, essentially, an array of one-dimensional arrays.
To declare a two-dimensional integer arrays. To declare a two-dimensional integer array num of
size 3, 4 you would write.
Ex: Int num[3][4];
Some other computer languages use commas to separate the array dimensions; C places each
dimension in its own set of brackets.
The 2D arrays can be initialized by following their declaration with a list of values enclosed
within braces
Ex: int num[3][4]= {1, 2, 3, 4, 5, 6, 7, 8,9,10,11,12};
Initialization can also be done row by row as follows:
Ex: int num[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};

Program to illustrate two dimensional array:

#include<stdio.h>
int main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
} Output
arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 56
2.15.write a c program to perform matrix addition/subtraction/multiplication

Write a C program for matrix Addition


main()
{
int a[3][3],b[3][3],c[3][3],i,j,m,n;
printf(“Enter the size of matrix”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of A matrix”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter the elements of B matrix”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“matrix addition is \n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
getch();

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 57


}
Output:
Enter the size of matrix 2 2
Enter the elements of A matrix 2 2 2 2
Enter the elements of B matrix 4 4 4 4
matrix addition is
6 6
6 6

2. Write a C program for matrix multiplication.


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,m,n,p,q;
clrscr();
printf("Enter 1st matrix row and col size=");
scanf("%d%d",&m,&n);
printf("Enter 2nd matrix row and col size=");
scanf("%d%d",&p,&q);
printf("Enter 1st matrix elements=\n");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter 2nd matrix elements=\n");
for(i=0;i<p;i++)
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
if(n==p)
{
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<p;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 58
}
printf("\nMultiplication of the two matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
printf("%5d",c[i][j]);
printf("\n");
}
}
else
printf("\nMultiplication is not possible");
getch();
}
Output:
Enter 1st matrix row and col size=2 3
Enter 2nd matrix row and col size=3 2
Enter 1st matrix elements=
123456

Enter 2nd matrix elements=


123456

Multiplication of the two matrix


22 28
49 64

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 59


UNIT – III
STRINGS,FUNCTIONS & POINTERS
3.1.String:

A string is a collection of characters (i.e., letters, numerals, symbols, and punctuation marks) in
a linear sequence. In C, a string is a sequence of characters concluded with a NULL character
'\0'. For example:

char str[] = "college.\0";

Like many other programming languages, strings in C are enclosed within double quotes(" "),
whereas characters are enclosed within single quotes(' '). When the compiler finds a sequence
of characters enclosed within the double quotation marks, it adds a null character (\0) at the
end by default.

Thus, this is how the string is stored:

c o l l e g e . \0
Declaration & initialization of strings:
Syntax : char stringname[size];
Ex : char name[10];
char address[20];

When the compiler assigns a character string to a character array, it automatically places a
NULLcharacter\0 (\zero) at the end of the string. Hence, the size should be equal to maximum
number of characters in the string plus one. Character arrays can be initialized when they are
declared.
char name[8] ={‘c’,’o’,’l’,’l’,’e’,’g’,’e’,’\0’};
When we initialize a character array by listing its elements, we must explicitly place a null
character.
char name[8]=”college”;
In this declaration \0 is not necessary, C language inserts a null character automatically.
The elements of character array are stored in contiguous memory locations.

Name[0] Name[1] Name[2] Name[3] Name[4] Name[5] Name[6]


c o l l e g e \0
6518 6520 6522 6524 6526 6528 6530 6532

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 60


Program to illustrate strings
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
char ch2[11]="javatpoint";

printf("Char Array Value is: %s\n", ch);


printf("String Literal Value is: %s\n", ch2);
return 0;
}

Output

Char Array Value is: javatpoint


String Literal Value is: javatpoint

3.2. explain different functions used for reading and writing strings
with examples
Strings can be read and displayed using some standard library functions. Those are
Input functions Output functions
scanf() printf()
gets() puts()
getchar() putchar()

scanf() and printf():


The strings can be read by scanf() function, and %s is the format specifier and printf() is used to
display the data. While using the scanf(), the length of string should not exceed the dimension
of character array. The drawback of scanf() is not capable of receiving multiword strings.
Ex: Dennis Ritchie
It accepts only Dennis. To overcome this we use functions gets() and puts();
Ex:
main()
{
char name[30];
printf(“Enter your name ”);
scanf(“%s”,name);/*& is not required while reading a string */
printf(“Your name is %s”,name);
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 61


Output: Enter your name
Dennis Ritchie
Your name is Dennis

gets() and puts():


gets() is a simple function that overcomes the drawback of scanf() and gets() is working as same
as printf() function.
Synatx for gets(): gets(str);
Synatx for puts(); puts(str);

Example program is:


main()
{
char name[30];
printf(“Enter your name ”);
gtes(name); /* function to read a string from user. */
puts(name); /* function to display a string. */
}

Output: Enter your name


Dennis Ritchie
your name is Dennis Ritchie

getchar() and putchar():


getchar() function is used to read a string but it can read only one character at a time from
entered string. If we want to read the entire string by using this function ,that has to be
executed repeatedly. putchar() is also can display one character at a time. To display all
characters in a string ,it has to be executed repeatedly.

Example:
#include<stdio.h>
void main()
{
char ch;
printf(“enter a string”);
ch=getchar();
putchar(ch);
}

Output:
Enter a string: pace
p

Example:
#include<stdio.h>
void main()

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 62


{
char string[20]=”hello world”;
int i=0;

while(string[i]!=’\0’)
{
putchar(string[i]);
i++;
}
}
Output:
hello world

program to illustrate reading string using scanf() function

#include <stdio.h>

int main()
{
char name[30];
printf("Enter your name : ");

scanf("%s", name);

printf("Hello %s!\n", name);


return 0;
}

Output:

enter your name : arjun

Hello arjun

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 63


3.3. explain the string manipulation functions strcat(),strcmp(),strcpy(),strlen()
with examples

There are many important string functions defined in "string.h" library.

No. Function Description

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination string.

3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

Strlen():
In C programming, we use strlen() to find the length of the string. String handling
function strlen() returns the number of characters in string.
strlen() Syntax

integer_variable = strlen(string or string_variable);

strlen() Examples

#include<stdio.h>
#include<string.h>
int main()
{
char str[30];
int len;

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 64


printf("Enter string:\n");
gets(str);
len = strlen(str);
printf("Length of given string is: %d", len);
return 0;
}
Output :
Enter string:
Welcome to C↲
Length of given string is: 12

strcpy():
String handling function strcpy() is used to copy content of one string variable to another string
variable i.e. strcpy(string2, string1) copies content of string1 to string2.
strcpy() Syntax

strcpy ( string2, string1);


strcpy() Program

#include<stdio.h>
#include<string.h>
int main()
{
char str1[30], str2[30];
printf("Enter string:\n");
gets(str1);
strcpy(str2, str1);
printf("Coped string is: %s”, str2);
return 0;
}

strcpy() Program Output


Enter string:
Welcome to C↲
Copied string is: Welcome to C

strcmp():
In C programming, string handling function strcmp() is used to compare two strings. This
function returns 0 if two strings are same otherwise it returns some integer value other than 0.
strcmp() Syntax

integer_variable = strcmp( string1, string2);

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 65


strcmp() Example

#include<stdio.h>
#include<string.h>

int main()
{
char str1[40], str2[40];
int d;

printf("Enter first string:\n");


gets(str1);
printf("Enter second string:\n");
gets(str2);
d = strcmp(str1, str2);
if(d==0)
{
printf("Given strings are same.");
}
else
{
printf("Given strings are different.");
}

return 0;
}

strcmp() Program Output

Run 1:
--------------
Enter first string:
Welcome to C↲
Enter second String:
Welcome to C↲
Given strings are same.

Run 2:
--------------
Enter first string:
Welcome↲
Enter second String:
Welcome to C↲
Given strings are different.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 66


strcat():
String handling function strcat() is used to concatenate two strings. Concatenation is the
process of merging content of one string to another string. Function strcat(str1,
str2) concatenates content of string str2 after content of string str1.

strcat() Syntax
strcat( string1, string2);

strcat() Example

#include<stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
printf("Enter first string:\n");
gets(str1);
printf("Enter second string:\n");
gets(str2);
strcat(str1,str2);
printf("Concatenated string is: %s", str1);
return 0;
}

strcat() Program Output

Enter first string:


Ram↲
Enter second String:
Shyam↲
Concatenated string is: RamShyam

strrev():
String handling function strrev() is used to reverse string in C programming language.
Function strrev(str1) reverses the content of string str1.
strrev() Syntax
strrev(string);

strrev() Program

#include<stdio.h>
#include<string.h>
int main()
{
char name[40];

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 67


printf("Enter your name: ");
gets(name);
strrev(name);
printf("Reversed name is: %s", name);

return 0;
}

strrev() Program Output

Enter youe name: Jenny↲


Reversed name is: ynneJ

strupr():
String handling function strupr() is used to convert all lower case letter in string to upper case
i.e. strlwr(str) converts all lower case letter in string str to upper case.

strlwr() Syntax
strupr( string);

strlwr() Program
#include<stdio.h>
#include<string.h>

int main()
{
char str[40];

printf("Enter string:\n");
gets(str);
strupr(str);
printf("String in uppercase is:");
puts(str);

return 0;
}
strlwr() Program Output

Enter string:
WeLcOmE To C 101. ↲
String in lowercase is:
WELCOME TO C 101.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 68


strlwr():
String handling function strlwr() is used to convert all upper case letter in string to lower case
i.e. strlwr(str) converts all upper case letter in string str to lowercase.

strlwr() Syntax
strlwr( string);

strlwr() Program
#include
#include<string.h>

int main()
{
char str[40];

printf("Enter string:\n");
gets(str);
strlwr(str);
printf("String in lowercase is:");
puts(str);

return 0;
}

strlwr() Program Output

Enter string:
WeLcOmE To C 101. ↲
String in lowercase is:
welcome to c 101.

3.4. & 3.5.state the use of functions in C &declaration of a program


In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 69


o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type.
o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.
o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function body;}

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...){


2. //code to be executed
3. }

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 70


Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

3.6. write the operation of getchar(),getch(),getche() and putchar()


functions
getch()

This function is used to get (read) single character from standard input device (keyboard)
without echoing i.e. it does not display the input character & it does not require [return] key
after input. getch() is declared in conio.h header file.

/*Compatible for TurboC compiler */


#include <stdio.h>
#include <conio.h>

int main()
{
char ch;

printf("Enter a character :");


ch=getch();
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 71
printf("\nEntered character is : %c",ch);
return 0;
}

Output

Enter a character:
Entered character is: G

Here, input character is G, which is not display while giving input.

getche()

This function is used to get (read) single character from standard input device (keyboard) with
echoing i.e. it displays the input character & it does not require [return] key after
input. getche() is declared in conio.h header file.

/*Compatible for TurboC compiler */


#include <stdio.h>
#include <conio.h>

int main()
{
char ch;
printf("Enter a character :");

ch=getche();
printf("\nEntered character is : %c",ch);

return 0;
}

Output

Enter a character: G
Entered character is: G

Here, input character is G, which displays character while giving input and does not require
[return] after pressing ‘G’.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 72


getchar()

This function is used to get (read) single character from standard input device (keyboard) with
echoing i.e. it displays the input character & require [return] key after input. getchar() is
declared in stdio.h header file.

#include <stdio.h>

int main()
{
char ch;
printf("Enter a character :");
ch=getchar();
printf("\nEntered character is : %c",ch);

return 0;
}

Output

Enter a character: G
Entered character is: G

Here, input character is G, which displays character while giving input and after pressing
[return] key, program’s execution will move to next statement.

putchar() & putch()

These functions are used to put (print) a single character on standard output device (monitor).

#include <stdio.h>
int main()
{
char ch;
printf("Enter a character :");
ch=getchar();
printf("\nEntered character is :");
putchar(ch);
return 0;
}

Output

Enter a character: G
Entered character is: G

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 73


3.7.use of return statement
C return statement ends the execution of a function and returns the control to
the function from where it was called. The return statement may or may not
return a value depending upon the return type of the function. For example, int
returns an integer value, void returns nothing, etc.
In C, we can only return a single value from the function using the return
statement and we have to declare the data_type of the return value in the
function definition/declaration.
Syntax:
return return_value;
Example for return with an expression

Int mul(int x,int y)

Int z;

Z=x*y;

Return(z);

3.8. passing of parameters to the function


When a function gets executed in the program, the execution control is transferred from
calling-function to called function and executes function definition, and finally comes back to
the calling function. When the execution control is transferred from calling-function to called-
function it may carry one or number of data values. These data values are called as parameters.
Parameters are the data values that are passed from calling function to called function.
In C, there are two types of parameters and they are as follows...

 Actual Parameters
 Formal Parameters

The actual parameters are the parameters that are speficified in calling function. The formal
parameters are the parameters that are declared at called function. When a function gets
executed, the copy of actual parameter values are copied into formal parameters.
In C Programming Language, there are two methods to pass parameters from calling function to
called function and they are as follows...

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 74


 Call by Value
 Call by Reference

Call by Value

In call by value parameter passing method, the copy of actual parameter values are copied to
formal parameters and these formal parameters are used in called function. The changes made
on the formal parameters does not effect the values of actual parameters. That means, after
the execution control comes back to the calling function, the actual parameter values remains
same. For example consider the following program...
Example Program

#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d\nnum2 = %d", num1, num2);
getch() ;
}
void swap(int a, int b) // called function
{
int temp ;
temp = a ;
a=b;
b = temp ;
}
Output:
Before swap: num1=10,num2 = 20
After swap:num1 = 10,num2 = 20

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 75


In the above example program, the variables num1 and num2 are called actual parameters and
the variables a and b are called formal parameters. The value of num1 is copied into a and the
value of num2 is copied into b. The changes made on variables a and b does not effect the
values of num1 and num2.

Call by Reference

In Call by Reference parameter passing method, the memory location address of the actual
parameters is copied to formal parameters. This address is used to access the memory locations
of the actual parameters in called function. In this method of parameter passing, the formal
parameters must be pointer variables.
That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters (pointers).
Whenever we use these formal parameters in called function, they directly access the memory
locations of actual parameters. So the changes made on the formal parameters effects the
values of actual parameters. For example consider the following program...
Example Program

#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int *,int *) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1, &num2) ; // calling function
printf("\nAfter swap: num1 = %d, num2 = %d", num1, num2);
getch() ;
}
void swap(int *a, int *b) // called function
{
int temp ;
temp = *a ;
*a = *b ;
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 76
*b = temp ;
}
Output:
Before swap: num1 = 10,num = 20
After swap: num1 = 20,num2 = 10

3.9. simple programs on functions call techniques


Program to calculate sum of two numbers using functions
#include <stdio.h>
int add(int a, int b);
void main()
{

int sum;
int a, b;
printf(" Enter the first and second number \n");
scanf("%d %d", &a, &b);
sum = add(a, b); // call add() function
printf( "The sum of the two number is %d", sum);
}
int add(int n1, int n2) // pass n1 and n2 parameter
{
int c;
c = n1 + n2;
return c;
}

Output:

Enter the first and second number


5
6
The sum of the two number is 11

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 77


3.10.define a pointer
A pointer is a derived data type in C that can store the address of other variables or a
memory. We can access and manipulate the data stored in that memory location using
pointers. Pointers in C are used to store the address of variables or a memory location.

 Pointers are used for dynamic memory allocation and deallocation.


 An Array or a structure can be accessed efficiently with pointers
 Pointers are useful for accessing memory locations.
 Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
 Pointers reduce the length of the program and its execution time as well.

3.11.declare a pointer,assign a pointer,initialize a pointer


Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To declare a
pointer, we use the * dereference operator before its name.
data_type * pointer_name;

The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to char
Initialization of pointer variable:
Pointer initialization is nothing but assigning value to the pointer variable. It contains the
address of a variable of the same data type. The ampersand(&) operator can be used to get the
address of a variable.
Int a;

int *p; // Pointer declaration

ptr = &a; //Pointer initialization

we can also combine the initialization with the declaration.

Int *p = &a;

ASSIGNING ADDRESS TO A POINTER:


Example program:
void main( )
{
int a=5;
int *pa;
pa=&a;
printf(“a=%d, address of a=%u”,*p,p);
Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 78
}

As you can see in the above figure, pointer‘*pa’ variable stores the address of ‘a’ variable, i.e.,
2008. The value of ‘a’ variable is 10. But the address of pointer variable ‘*pa’ is 1058.

By the help of * (indirection operator), we can print the value of pointer variable *pa.

Note :
Any type of pointer, it allocates only 2 bytes of memory,Because it stores the address of
memory location. In C language the memory address is in unsigned integer. (2 bytes for
unsigned int, in the range of 0 to 65535)

Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
int *pa;
pa=&a;
clrscr();
printf(" a -- Value of 'a'\t: %d",a);
printf("\n &a -- The memory addrss of 'a': %u",&a);
printf("\n pa -- Value of 'pa'\t: %u",pa);
printf("\n &p -- The memory address of '&pa': %u",&pa);
printf("\n*pa -- Value of 'a'\t: %d",*pa);
getch();
}
Output:
a - - Value of 'a' : 10
&a - - The memory address of 'a' : 65524
pa - - Value of 'pa' : 65524
&p - - The memory address of '&pa : 65522
*pa - - Value of 'a' : 10

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 79


3.12.pointer arithmetic operations
The Pointers variables are used to store the address of another variable. The address is nothing
but the memory location assigned to the variable. That means the pointer doesn’t store any
value, it stores the address. Hence, there are only a few operations that are allowed to perform
on Pointers. The operations are slightly different from the ones that we generally use for
mathematical calculations. The operations are as follows:

1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers of the same type.

Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it
actually increments by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size
of an int) and the new address it will points to 1004. While if a float type pointer is
incremented then it will increment by 4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is
decremented, it actually decrements by the number equal to the size of the data type for
which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by
4(size of an int) and the new address it will points to 996. While if a float type pointer is
decremented then it will decrement by 4(size of a float) and the new address will be 996.

Addition
When a pointer is added with a value, the value is first multiplied by the size of data type and
then added to the pointer.
Subtraction
When a pointer is subtracted with a value, the value is first multiplied by the size of the data
type and then subtracted from the pointer.
Subtraction of Two Pointers
The subtraction of two pointers is possible only when they have the same data type. The
result is generated by calculating the difference between the addresses of the two pointers
and calculating how many bits of data it is according to the pointer data type. The subtraction
of two pointers gives the increments between the two pointers.
For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The
difference between address is 4 bytes. Since the size of int is 4 bytes, therefore the increment
between ptr1 and ptr2 is given by (4/4) = 1.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 80


#include <stdio.h>
int main ()
{
int a = 10, b=20;
// Pointer to an integer
int *ptr1, *ptr2;
// Pointer stores the address of variable a
ptr1 = &a;
ptr2 = &b;
printf ("Pointer ptr1 before Increment: ");
printf ("%p \n", ptr1);
// Incrementing pointer ptr1;
ptr1++;
printf ("Pointer ptr1 after Increment: ");
printf ("%p \n\n", ptr1);
printf ("Pointer ptr2 before Decrement: ");
printf ("%p \n", ptr2);
// Decrementing pointer ptr2;
ptr2--;
printf ("Pointer ptr2 after Decrement: ");
printf ("%p \n\n", ptr2);
printf("Pointer ptr1 before Addition: ");
printf("%p \n", ptr1);
// Addition of 2 to pointer ptr1
ptr1 = ptr1 + 2;
printf("Pointer ptr1 after Addition: ");
printf("%p \n", ptr1);
printf("Pointer ptr2 before Subtraction : ");
printf("%p \n", ptr2);
// Subtraction of 2 from pointer ptr2
ptr2 = ptr2 + 2;
printf("Pointer ptr1 after Subtraction : ");
printf("%p \n", ptr2);
return 0;
}

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 81


Output:

3.13.address and dereferencing operators


The address operator (&) can be used with an lvalue, such as a variable, as in &var. This
expression yields the address of variable var, i.e., a pointer to it. Note that the address
operator cannot be used with constants and non-lvalue expressions. Thus, the
expressions &100,&(a+5) and &’X’ are invalid. If the type of variable var is T, the
expression &var returns a value of type T *,i.e., a pointer to type T. As mentioned earlier, we
need not know the exact address where a particular variable is stored in memory. We can use
the addressoperator to obtain its address, whatever it may be. This address can be assigned to
a pointervariable of appropriate type so that the pointer points to that variable.
The dereference operator (*) is a unary prefix operator that can be used with any pointer
variable, as in *ptr_var. This expression yields the value of the variable pointed at by that
pointer. Although the symbol for the dereference operator is the same as that of the
multiplication operator, its use is unambiguous from the context as the latter is a binary infix
operator used, as in expr1 * expr2.

Address operator De-referencing operator

The & is a unary operator in C which returns The * is a unary operator which returns the
the memory address of the passed operand value of object pointed by a pointer variable.
Address operator can be denoted by & De-referencing operator can be denoted by *

This is also known as address of operator It is known as value of operator. It is also used
for declaring pointer variable.
Example: Example:
int number; Int number,*ptr;
a=&number Number=200;
Ptr=&number;
N=*ptr;

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 82


UNIT – IV
STRUCTUTRES AND UNIONS
4.1. define a structure in C

Structure is a user-defined datatype in C language which allows us to


combine data of different types together. Structure helps to construct
a complex data type which is more meaningful. It is somewhat similar
to an Array, but an array holds data of similar type only. But structure
on the other hand, can store data of any type, which is practical more
useful.

For example: If I have to write a program to store Student


information, which will have Student's name, age, branch, permanent
address, father's name etc, which included string values, integer values
etc

4.2.syntax of structure declaration


struct [structure_tag]
{
//member variable 1
//member variable 2
...
}[structure_variables];
Example:
struct Student
{
char name[25];
int age;
char branch[10];
// F for female and M for male
char gender;
};

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 83


Here struct Student declares a structure to hold the details of a student
which consists of 4 data fields, namely name, age, branch and gender. These
fields are called structure elements or members.

Each member can have different datatype, like in this case, name is an
array of char type and age is of int type etc. Student is the name of the
structure and is called as the structure tag.

4.3.Declaring Structure Variables

It is possible to declare variables of a structure, either along with structure definition or


after the structure is defined. Structure variable declaration is similar to the declaration of
any normal variable of any other datatype. Structure variables can be declared in following
two ways:
1) Declaring Structure variables separately
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};
struct Student S1, S2; //declaring variables of struct Student
2) Declaring Structure variables with structure definition
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 84


4.4. Structure Initialization
Like a variable of any other datatype, structure variable can also be initialized at compile time.
There are two ways to initialize a structure.
Initialize whole structure at once
struct Patient
{
float height;
int weight;
int age;
};
struct Patient p1 = { 180.75 , 73, 23 }; //initialization
initializing every member of structure individually
struct Patient p1;
p1.height = 180.75; //initialization of each member separately
p1.weight = 73;
p1.age = 23;

4.5. Accessing Structure Members


To access any member of a structure, we use the member access operator (.). The member access
operator is coded as a period between the structure variable name and the structure member that
we wish to access. You would use the keyword struct to define variables of structure type.
Syntax:
<structure_variable>.<member_name>
example
#include<stdio.h>
#include<string.h>
struct Student
{
char name[25];
int age;
char branch[10];
//F for female and M for male
char gender;
};

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 85


int main()
{
struct Student s1;

/*
s1 is a variable of Student type and
age is a member of Student
*/
s1.age = 18;
/*
using string function to add name
*/
strcpy(s1.name, "Viraaj");
/*
displaying the stored values
*/
printf("Name of Student 1: %s\n", s1.name);
printf("Age of Student 1: %d\n", s1.age);

return 0;
}
Output:
Name of Student 1: satish
Age of Student 1: 18

4.6.illustrate structures with a program to read&print a book


database consisting of title of book,author,no.of pages,price as fields
#include<stdio.h>
#include<string.h>
#define SIZE 20

struct bookdetail
{
char name[20];

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 86


char author[20];
int pages;
float price;

};

void output(struct bookdetail v[],int n);

void main()
{
struct bookdetail b[SIZE];

int num,i;
printf("Enter the Numbers of Books:");
scanf("%d",&num);
printf("\n");
for(i=0;i<num;i++)

printf("\t=:Book %d Detail:=\n",i+1);

printf("\nEnter the Book Name:\n");


scanf("%s",b[i].name);

printf("Enter the Author of Book:\n");


scanf("%s",b[i].author);

printf("Enter the Pages of Book:\n");


scanf("%d",&b[i].pages);

printf("Enter the Price of Book:\n");


scanf("%f",&b[i].price);

output(b,num);

void output(struct bookdetail v[],int n)

int i,t=1;

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 87


for(i=0;i<n;i++,t++)

printf("\n");

printf("Book No.%d\n",t);

printf("\t\tBook %d Name is=%s \n",t,v[i].name);

printf("\t\tBook %d Author is=%s \n",t,v[i].author);

printf("\t\tBook %d Pages is=%d \n",t,v[i].pages);

printf("\t\tBook %d Price is=%f \n",t,v[i].price);

printf("\n");

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 88


4.7.explain how to find size of a structure
The sizeof() operator is commonly used in C. It determines the size of the expression or the
data type specified in the number of char-sized storage units. The sizeof() operator contains a
single operand which can be either an expression or a data typecast where the cast is data type
enclosed within parenthesis. The data type cannot only be primitive data types such as integer
or floating data types, but it can also be pointer data types and compound data types such as
unions and structs.
Syntax:

Sizeof(<variable_name>);

Example:

Program to determine size of a structure using sizeof() operator

#include<stdio.h>

struct stud {
int roll;
char name[10];
int marks;
};

int main() {
int size;
struct stud s;

size = sizeof(s);
printf("nSize of Structure : %d", size);

return(0);
}

Output:
Size of Structure 'S' = sizeof(roll) + sizeof(name) + sizeof(mark)
= 2 + 10 + 2
= 14

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 89


4.8.union
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.
To define a union, you must use the union statement in the same way as you did while defining
a structure. The union statement defines a new data type with more than one member for your
program.
Syntax:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];

Example:
Union book
{
Char name[50];
Int price;
};

Program to illustrate union


#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main ()

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 90


{
union Data data;
data.i = 10;
printf ("data.i : %d\n", data.i);
data.f = 220.5;
printf ("data.f : %f\n", data.f);
strcpy (data.str, "C Programming");
printf ("data.str : %s\n", data.str);
return 0;
}
Output:

Use of union
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multiple-purpose.

 It occupies less memory or space compared to the structure

 We can use union in c when we have the same memory location for more than one data
member.

 It will only take the space of the largest data member.

 With the help of union in c you can only access the last variable directly.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 91


4.9.differences between structure and union

Struct Union

The struct keyword is used to define a The union keyword is used to define union.
structure.

Each variable member occupied a unique Variables members share the memory space of the
memory space. largest size variable.

Each variable member will be assessed at a Only one variable member will be assessed at a time.
time.

It allows accessing and retrieving any data It allows accessing and retrieving any one data
member at a time. member at a time.

All variable members store some value at Exactly only one data member stores a value at any
any point in the program. particular instance in the program.

The structure allows initializing multiple Union allows initializing only one variable member at
variable members at once. once.

It is used to store different data type It is used for storing one at a time from different data
values. type values.

Syntax Syntax
struct [structure name] union [union name]
{ {
type element_1; type element_1;
type element_2; type element_2;
. .
. .
} variable_1, variable_2, …; } variable_1, variable_2, …;

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 92


4.10. function of pre-processor directives in C

The C preprocessor is a micro processor that is used by compiler to transform your code before
compilation. It is called micro preprocessor because it allows us to add macros.

The C preprocessor is a macro processor that is used automatically by the C compiler to


transform your program before actual compilation (Proprocessor direcives are executed before
compilation.). It is called a macro processor because it allows you to define macros, which are
brief abbreviations for longer constructs. A macro is a segment of code which is replaced by the
value of macro. Macro is defined by #define directive.

Preprocessing directives are lines in your program that start with #. The # is followed by an
identifier that is the directive name.

For example, #define is the directive that defines a macro. Whitespace is also allowed before
and after the #.

The # and the directive name cannot come from a macro expansion. For example, if foo is
defined as a macro expanding to define, that does not make #foo a valid preprocessing
directive.

All preprocessor directives starts with hash # symbol.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 93


4.11. list of pre-processor directives

1. #include
2. #define
3. #undef
4. #ifdef
5. #ifndef
6. #if
7. #else
8. #elif
9. #endif
10. #error
11. #pragma

The preprocessor will process directives that are inserted into the C source code. These
directives allow additional actions to be taken on the C source code before it is compiled into
object code. Directives are not part of the C language itself.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No. Macro Description

1 _DATE_ represents current date in "MMM DD YYYY" format.

2 _TIME_ represents current time in "HH:MM:SS" format.

3 _FILE_ represents current file name.

4 _LINE_ represents current line number.

5 _STDC_ It is defined as 1 when compiler complies with the ANSI standard.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 94


Preprocessor directives begin with a pound (#) symbol and may have several arguments.
The following are some of the preprocessor directives that you can use in your source code:

Directive Description

Include another C file into the current file at the location of the #include statement
#include
prior to compiling the source code.

#define Define a macro which can be used as a constant throughout the source code.

#undef Clear a macro which was previously defined.

#if Conditional expresssion which can be used to include source code for compilation.

Allows the inclusion of source code if the provided macro identifier has been
#ifdef
defined. Equivalent to #if defined(identifier).

Allows the inclusion of source code if the provided macro identifier has not been
#ifndef
defined.

Provides an alternate inclusion of source code when used with the #if, #ifdef, or
#elif
#ifndef directives and the #elif condition evaluates to true.

Allows the inclusion of source code if the preceeding #if, #ifdef, or #ifndef directive
#else
expression evaluates to false.

#endif Signals the end of a #if, #ifdef or #ifndef condition .

#warning Report a warning message and continue preprocessing.

#error Report error and stop preprocessing.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 95


Program to illustrate usage of #define pre-processor directives

#include <stdio.h>

// macro with parameter


#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;

area = AREA(l1, l2);

printf("Area of rectangle is: %d", area);

return 0;
}
Output :

Area of the rectangle is 50

4.12.conditional pre-processor directives


The conditional directives are:
o #ifdef - If this macro is defined
o #ifndef - If this macro is not defined
o #if - Test if a compile time condition is true
o #else - The alternative for #if
o #elif - #else an #if in one statement
o #endif - End preprocessor conditional
Program:
#include <stdio.h>

void main ()

printf ("CTUTORIAL");

#if 2>5!=2<5

printf ("A");

printf ("B");

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 96


#else

printf ("C");

printf ("D");

#endif

printf ("Welcome");

Output: CTUTORIALABWelcome

4.13.unconditional pre-processor directives


The unconditional directives are:
o #include - Inserts a particular header from another file
o #define - Defines a preprocessor macro
o #undef - Undefines a preprocessor macro
Program to illustrate #define

#include<stdio.h>
#define PI 3.1415
Main()
{
Printf(“%f”,PI);
}
Output :

3.14

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 97


UNIT – V
BASICS OF MATLAB
MATLAB stands for Matrix Laboratory. It is a high-performance language that is used for
technical computing. It was developed by Cleve Molar of the company MathWorks.Inc in the
year 1984.It is written in C, C++, Java. It allows matrix manipulations, plotting of functions,
implementation of algorithms and creation of user interfaces.

Matlab or Matrix Laboratory is a high-level programming language consisting of an interactive


environment mainly used for numeric computation, programming, and visualization. It has
been developed by MathWorks. The basic functions of Matlab are plotting of functions and
data, the creation of user interfaces, matrix manipulations. It also provides support for
interfacing with other programming languages in C, C++, Fortran, and Java. Besides, it is also
used to analyze data, create models and applications, and also develop algorithms.

5.1.matlab in solving engineering problems


MATLAB is a high-performance language for technical computing. It integrates computation,
visualization, and programming in an easy-to-use environment where problems and solutions
are expressed in familiar mathematical notation. Typical uses include:

 Math and computation


 Algorithm development
 Modeling, simulation, and prototyping
 Data analysis, exploration, and visualization
 Scientific and engineering graphics
 Application development, including Graphical User Interface building

MATLAB is an interactive system whose basic data element is an array that does not require
dimensioning. This allows you to solve many technical computing problems, especially those
with matrix and vector formulations, in a fraction of the time it would take to write a program
in a scalar noninteractive language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally written to provide easy
access to matrix software developed by the LINPACK and EISPACK projects, which together
represent the state-of-the-art in software for matrix computation.

MATLAB has evolved over a period of years with input from many users. In university
environments, it is the standard instructional tool for introductory and advanced courses in
mathematics, engineering, and science. In industry, MATLAB is the tool of choice for high-
productivity research, development, and analysis.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 98


MATLAB features a family of application-specific solutions called toolboxes. Very important to
most users of MATLAB, toolboxes allow you to learn and apply specialized technology.
Toolboxes are comprehensive collections of MATLAB functions (M-files) that extend the
MATLAB environment to solve particular classes of problems. Areas in which toolboxes are
available include signal processing, control systems, neural networks, fuzzy logic, wavelets,
simulation, and many others.

The MATLAB System

The MATLAB system consists of five main parts:

The MATLAB language.


This is a high-level matrix/array language with control flow statements, functions, data
structures, input/output, and object-oriented programming features. It allows both
"programming in the small" to rapidly create quick and dirty throw-away programs, and
"programming in the large" to create complete large and complex application programs.

The MATLAB working environment.


This is the set of tools and facilities that you work with as the MATLAB user or programmer. It
includes facilities for managing the variables in your workspace and importing and exporting
data. It also includes tools for developing, managing, debugging, and profiling M-files,
MATLAB's applications.

Handle Graphics.
This is the MATLAB graphics system. It includes high-level commands for two-dimensional and
three-dimensional data visualization, image processing, animation, and presentation graphics.
It also includes low-level commands that allow you to fully customize the appearance of
graphics as well as to build complete Graphical User Interfaces on your MATLAB applications.

The MATLAB mathematical function library.


This is a vast collection of computational algorithms ranging from elementary functions like
sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse,
matrix eigenvalues, Bessel functions, and fast Fourier transforms.

The MATLAB Application Program Interface (API).


This is a library that allows you to write C and Fortran programs that interact with MATLAB. It
include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 99


Uses of mat lab:

1. Embedded Systems
2. Control systems
3. Digital signal processing
4. Wireless communications
5. Image processing and computer vision
6. Internet of Things
7. Test and Measurement
8. Computational Biology
9.Computational finance

5.2.differences between mat lab and C language

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 100


5.3. arithmetic operators,relational operators,logical operators in
matlab
An operator is a symbol in computer programming and mathematics which is used to perform
specific mathematical or logical operations or you can also define it as a character that represents
an action for example ‘+’ is a character that represents addition similarly Boolean operators are
used to working with true/false values.
One more important fact to keep in mind is operators in MATLAB work for both scalar and non-
scalar data.
Types of Operators
MATLAB offers the following type of operators:
 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Set operators

1. Arithmetic Operators
Matlab provides two types of Arithmetic operators
Matrix arithmetic operators
Array arithmetic operators
Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed
element by element, both on one dimensional and multi-dimensional array.
The matrix operators and arrays operators are differentiated by the period (.) symbol. However,
as the addition and subtraction operation is same for matrices and arrays, the operator is same for
both cases.

The following table gives brief description of the operators –

S.No. operator Operator & Description

1 + Addition or unary plus. A+B adds the values stored in variables A


and B. A and B must have the same size, unless one is a scalar. A
scalar can be added to a matrix of any size.

2 - Subtraction or unary minus. A-B subtracts the value of B from A. A


and B must have the same size, unless one is a scalar. A scalar can
be subtracted from a matrix of any size.

3 * Matrix multiplication. C = A*B is the linear algebraic product of the


matrices A and B. More precisely,

For non-scalar A and B, the number of columns of A must be equal


to the number of rows of B. A scalar can multiply a matrix of any
size.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 101


4 .* Array multiplication. A.*B is the element-by-element product of the
arrays A and B. A and B must have the same size, unless one of
them is a scalar.

5 / Slash or matrix right division. B/A is roughly the same as B*inv(A).


More precisely, B/A = (A'\B')'.

6 ./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j).


A and B must have the same size, unless one of them is a scalar.

7 \ Backslash or matrix left division. If A is a square matrix, A\B is


roughly the same as inv(A)*B, except it is computed in a different
way. If A is an n-by-n matrix and B is a column vector with n
components, or a matrix with several such columns, then X = A\B is
the solution to the equation AX = B. A warning message is
displayed if A is badly scaled or nearly singular.

8 .\ Array left division. A.\B is the matrix with elements B(i,j)/A(i,j). A


and B must have the same size, unless one of them is a scalar.

9 ^ Matrix power. X^p is X to the power p, if p is a scalar. If p is an


integer, the power is computed by repeated squaring. If the integer
is negative, X is inverted first. For other values of p, the calculation
involves eigenvalues and eigenvectors, such that if [V,D] = eig(X),
then X^p = V*D.^p/V.

10 .^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j)
power. A and B must have the same size, unless one of them is a
scalar.

11 ' Matrix transpose. A' is the linear algebraic transpose of A. For


complex matrices, this is the complex conjugate transpose.

12 .' Array transpose. A.' is the array transpose of A. For complex


matrices, this does not involve conjugation.

2.Relational operators

Relational operators can also work on both scalar and non-scalar data. Relational operators for
arrays perform element-by-element comparisons between two arrays and return a logical array of
the same size, with elements set to logical 1 (true) where the relation is true and elements set to
logical 0 (false) where it is not.

The following table shows the relational operators −

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 102


Sr.No. operator Operator & Description

1 < Less than

2 <= Less than or equal to

3 >
Greater than

4 >= Greater than or equal to

5 == Equal to

6 ~= Not equal to

Logical operatorsLogical operators perform logical operations and output the result in Boolean
state true or false using the numbers 1 and 0, respectively.

o Element-wise: It works on corresponding elements of logical arrays..


o Short-circuit: It works on scalar, logical expressions.

Element-Wise Operators and Functions

The following logical operators and functions execute element-wise logical operations on their
inputs to produce a like-sized output array. The examples are shown in the following table use
vector inputs A and B, where

Symbol Role

& Logical AND It returns 1 for every element location that is true (nonzero) in both
arrays and 0 for all other elements.

| Logical OR It returns 1 for every element location that is true (nonzero) in either one or
the other, or both arrays, and 0 for all other elements.

~ Logical NOT It complements each element of the input array, A.

xor It returns 1 for every element location that is true (nonzero) in only one array, and 0 for
all other elements.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 103


Bitwise operators:

MATLAB provides various functions for bit-wise operations like 'bitwise and', 'bitwise or' and
'bitwise not' operations, shift operation, etc.
The following table shows the commonly used bitwise operations −

Function Purpose

bitand(a, b) Bit-wise AND of integers a and b

bitcmp(a) Bit-wise complement of a

bitget(a,pos) Get bit at specified position pos, in the integer array a

bitor(a, b) Bit-wise OR of integers a and b

bitset(a, pos) Set bit at specific location pos of a

bitshift(a, k) Returns a shifted to the left by k bits, equivalent to multiplying by


2k. Negative values of k correspond to shifting bits right or dividing
by 2|k| and rounding to the nearest integer towards negative
infinite. Any overflow bits are truncated.

bitxor(a, b) Bit-wise XOR of integers a and b

swapbytes Swap byte ordering

Set operations:

MATLAB provides various functions for set operations, like union, intersection and testing for
set membership, etc.
The following table shows some commonly used set operations −
Sr.No. Function Function & Description

1 intersect(A,B) Set intersection of two arrays; returns the values common to


both A and B. The values returned are in sorted order.

2 intersect(A,B,'rows') Treats each row of A and each row of B as single entities and
returns the rows common to both A and B. The rows of the
returned matrix are in sorted order.

3 ismember(A,B) Returns an array the same size as A, containing 1 (true) where


the elements of A are found in B. Elsewhere, it returns 0 (false).

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 104


4 ismember(A,B,'rows') Treats each row of A and each row of B as single entities and
returns a vector containing 1 (true) where the rows of matrix A
are also rows of B. Elsewhere, it returns 0 (false).

5 issorted(A) Returns logical 1 (true) if the elements of A are in sorted order


and logical 0 (false) otherwise. Input A can be a vector or an N-
by-1 or 1-by-N cell array of strings. A is considered to be sorted
if A and the output of sort(A) are equal.

6 issorted(A, 'rows') Returns logical 1 (true) if the rows of two-dimensional matrix A


is in sorted order, and logical 0 (false) otherwise. Matrix A is
considered to be sorted if A and the output of sortrows(A) are
equal.

7 union Sets union of two arrays

8 unique Unique values in array

5.4. elementwise multipilication/division/power operations and array


multiplication/division/power operations
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You
can use these arithmetic operations to perform numeric computations, for example, adding two
numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by
element operations and support multidimensional arrays. The period character (.) distinguishes the
array operations from the matrix operations. However, since the matrix and array operations are the
same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Array Operations

Array operations execute element by element operations on corresponding elements of vectors,


matrices, and multidimensional arrays. If the operands have the same size, then each element in the
first operand gets matched up with the element in the same location in the second operand. If the
operands have compatible sizes, then each input is implicitly expanded as needed to match the size of
the other. For more information, see Compatible Array Sizes for Basic Operations.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 105


As a simple example, you can add two vectors with the same size.

A= 1 1 1

1 1 1

B= 123

123

A+B = 2 3 4

2 3 4

Matrix Operations

Matrix operations follow the rules of linear algebra and are not compatible with multidimensional
arrays. The required size and shape of the inputs in relation to one another depends on the operation.
For nonscalar inputs, the matrix operators generally calculate different answers than their array
operator counterparts.

For example, if you use the matrix right division operator, /, to divide two matrices, the matrices must
have the same number of columns. But if you use the matrix multiplication operator, *, to multiply two
matrices, then the matrices must have a common inner dimension. That is, the number of columns in
the first input must be equal to the number of rows in the second input. The matrix multiplication
operator calculates the product of two matrices with the formula,

C(i,j)= ∑ A(i,k)B(k,j).
n k=1

To see this, you can calculate the product of two matrices.

A = [1 3;2 4]

A= 1 3

2 4

B = [3 0;1 5]

B= 3 0

1 5

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 106


A*B = 6 15

10 20

The previous matrix product is not equal to the following element-wise product.

A.*B = 3 0

2 20

5.5.linspace operator,clc,clear,who,whos commands


linspace

Generate linearly spaced vector. linspace is similar to the colon operator, “:”, but gives direct control
over the number of points and always includes the endpoints. “lin” in the name “linspace” refers to
generating linearly spaced values as opposed to the sibling function logspace, which generates
logarithmically spaced values.

Syntax

y = linspace(x1,x2)

y = linspace(x1,x2,n)

Description

y = linspace(x1,x2) returns a row vector of 100 evenly spaced points between x1 and x2.

y = linspace(x1,x2,n) generates n points. The spacing between the points is (x2-x1)/(n-1).

clc

Clear Command Window

collapse all in page

Syntax

clc

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 107


Description

clc clears all the text from the Command Window, resulting in a clear screen. After running clc, you
cannot use the scroll bar in the Command Window to see previously displayed text. You can, however,
use the up-arrow key ↑ in the Command Window to recall statements from the command history.

Use clc in a MATLAB® code file to always display output in the same starting position on the screen.

clear

Remove items from workspace, freeing up system memory

Syntax

clear

clear name1 ... nameN

clear -regexp expr1 ... exprN

clear ItemType

Description

clear removes all variables from the current workspace, releasing them from system memory.

clear name1 ... nameN removes the variables, scripts, functions, or MEX functions name1 ...
nameN from memory.

clear -regexp expr1 ... exprN removes all variables that match any of the regular expressions listed.
This option only removes variables.

clear ItemType removes the types of items indicated by ItemType, such as all, functions, or classes.

who

List variables in workspace

Syntax

who

who -file filename

who global

who ___ var1 ... varN

who ___ -regexp expr1 ... exprN

C = who(___)

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 108


Description

who lists in alphabetical order the names of all variables in the currently active workspace.

who -file filename lists the variable names in the specified MAT-file.

who global lists the variable names in the global workspace.

who ___ var1 ... varN lists only the specified variables. Use this syntax with any of the arguments in
the previous syntaxes.

who ___ -regexp expr1 ... exprN lists only the variables that match the specified regular expressions.

C = who(___) stores the names of the variables in the cell array C.

whos

List variables in workspace, with sizes and types

Syntax

whos

whos -file filename

whos global

whos ___ var1 ... varN

whos ___ -regexp expr1 ... exprN

S = whos(___)

Description

whos lists in alphabetical order the names, sizes, and types of all variables in the currently active
workspace.

whos -file filename lists variables in the specified MAT-file.

5.6.synatax and usage of decision making statements used in matlab


Decision making structures require that the programmer should 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.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 109


i)if….end statement
The if is a conditional statement that provides the functionality to choose a block of code to
execute at run time.
A predefined condition is checked, and the remaining code executes based on the output of the
condition.
The if statement is defined by the if keyword.
The control flows within the if block if the condition is found true.
Syntax:
if expression
Statements
end
Example:

% MATLAB program to illustrate


% if-end statement

number = 28;

if number>10
fprintf('The number is greater than 10.');
end

Output:
The number is greater than 10.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 110


ii)if…else…end statement
If the first condition is not true, then we can define other statements to run by using
the else keyword.
Syntax:
if expression
Statements
else
Statements
end

Example:

% MATLAB program to illustrate


% if-else-end statement

number = 28;

if number<10
fprintf('The number is greater than 10');
else
fprintf('The number is not less than 10');
end

Output:
The number is not less than 10

5.7.syntax and usage of loop statement


There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially. The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
Syntax
for index = values
statements
end

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 111


Description
for index = values, statements, end executes a group of statements in a loop for a specified
number of times. values has one of the following forms:
s.no format description
1 initVal:endVal Increment the index variable from initVal to endVal by 1, and
repeat execution of statements until index is greater than endVal
2 initVal:step:endVal Increment index by the value step on each iteration, or
decrements index when step is negative
3 valArray Create a column vector, index, from subsequent columns of
array valArray on each iteration

Example:

MATLAB code to illustrate


%for loop
for i = 1:5
fprintf('%d ',i)
end

Output:
12345

while

while loop to repeat when condition is true


Syntax
while expression
statements
end
Description
while expression, statements, end evaluates an expression, and repeats the execution of a
group of statements in a loop while the expression is true. An expression is true when its result
is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the
expression is false.
a = 10;
% while loop execution
while( a < 20 )
fprintf('value of a: %d\n', a);
a = a + 1;
end

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 112


When you run the file, it displays the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

5.8. explain the creation 1D & 2D arrays and mxn matrices in matlab
All variables of all data types in MATLAB are multidimensional arrays. A vector is a one-
dimensional array and a matrix is a two-dimensional array.
We have already discussed vectors and matrices. In this chapter, we will discuss
multidimensional arrays. However, before that, let us discuss some special types of arrays.
Creation of 1D array:

to sreate a single dimensional array with four elements in a single row separate the elements
with a comma(,) or an space.

Example:

A = [1 2 3 4 ]

Matlab will executes the above statements and return the following result.

A= 1 2 3 4

This type of vector is called a row vector.

Creation of 2d array:

To create a matrix that has multiple rows,sepate the rows with semicolon.these are called 2D
arrays.

For example,let us create a 2x3 arrays

a = [1 2 3 ; 4 5 6 ; 7 8 10]

Matlab will executes the abovenstatements and retuen the following result

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 113


1 2 3

A= 4 5 6

6 7 9

Creation of mXn matrices

An m x n matrix is an ordered rectangular array of elements containing m rows and n columns.


Each matrix element is given two indices, the first identifying the row and the second
identifying the column: A square matrix is one in which the number of rows equals the number
of columns.

A matrix is a two-dimensional array of numbers.


In MATLAB, you create a matrix by entering elements in each row as comma or space delimited
numbers and using semicolons to mark the end of each row.
To reference an element in the m th row and nth column, of a matrix mx, we write −
mx(m, n);

For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created
in the last section, we type −

a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
a(2,5)
MATLAB will execute the above statement and return the following result −
ans = 6
To reference all the elements in the mth column we type A(:,m).
Let us create a column vector v, from the elements of the 4th row of the matrix a −

a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];
v = a(:,4)
MATLAB will execute the above statement and return the following result −
v=
4
5
6
7
You can also select the elements in the mth through nth columns, for this we write −

a(:,m:n)

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 114


MATLAB will execute the above statement and return the following result −
ans =
2 3
3 4
4 5
5 6

5.9.matrix operations
In this section, let us discuss the following basic and commonly used matrix operations −
Addition of Matrices
Subtraction of matrices
Matrix Multiplication
Inverse of a Matrix
Transpose of a Matrix

Addition of Matrices
You can add matrices. Both the operand matrices must have the same number of rows and
columns.
Example
a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c=a+b
d=a-b
When you run the file, it displays the following result –

8 7 9
C= 6 5 14
12 15 10

Subtraction of matrices

Example

a = [ 1 2 3 ; 4 5 6; 7 8 9];
b = [ 7 5 6 ; 2 0 8; 5 7 1];
c= a - b
when you run this file,it displays the following result -

-6 -3 -3
d= 2 5 -2
2 1 8

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 115


Matrix Multiplication
Consider two matrices A and B. If A is an m x n matrix and B is an n x p matrix, they could be
multiplied together to produce an m x p matrix C. Matrix multiplication is possible only if the
number of columns n in A is equal to the number of rows n in B.
In matrix multiplication, the elements of the rows in the first matrix are multiplied with
corresponding columns in the second matrix.
Each element in the (i, j)th position, in the resulting matrix C, is the summation of the products
of elements in ith row of first matrix with the corresponding element in the j th column of the
second matrix.
Matrix multiplication in MATLAB is performed by using the * operator.

Example

Create a script file with the following code −

a = [ 1 2 3; 2 3 4; 1 2 5]
b = [ 2 1 3 ; 5 0 -2; 2 3 -1]

prod = a * b
When you run the file, it displays the following result −
1 2 3
a= 2 3 4
1 2 5

2 1 3
b= 5 0 -2
2 3 -1

18 10 -4
Prod = 27 14 -4
22 16 -6

Transpose of a Matrix
The transpose operation switches the rows and columns in a matrix. It is represented by a
single quote(').
Example
Create a script file with the following code −
a = [ 10 12 23 ; 14 8 6; 27 8 9]
b = a'
When you run the file, it displays the following result −

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 116


10 12 23
a= 14 8 6
27 8 9

10 14 27
b= 12 8 8
23 6 9

Inverse of a Matrix
The inverse of a matrix A is denoted by A−1 such that the following relationship holds −

AA−1 = A−1A = 1
The inverse of a matrix does not always exist. If the determinant of the matrix is zero, then the
inverse does not exist and the matrix is singular.
Inverse of a matrix in MATLAB is calculated using the inv function. Inverse of a matrix A is given
by inv(A).

Example

Create a script file and type the following code −

a = [ 1 2 3; 2 3 4; 1 2 5]
inv(a)
When you run the file, it displays the following result −

1 2 3
a= 2 3 4
1 2 5

-3.5000 2.0000 0.5000


Ans = 3.0000 -1.0000 -1.0000
-0.5000 0 0.5000

5.10.common input/output functions in matlab


Declare function name, inputs, and outputs
Syntax
function [y1,...,yN] = myfun(x1,...,xM)

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 117


Description
example
function [y1,...,yN] = myfun(x1,...,xM) declares a function named myfun that accepts
inputs x1,...,xM and returns outputs y1,...,yN. This declaration statement must be the first
executable line of the function. Valid function names begin with an alphabetic character, and
can contain letters, numbers, or underscores.
Input function:
x = input(prompt)

txt = input(prompt,"s")

An output function is a function that an optimization function calls at each iteration of its
algorithm. Typically, you use an output function to generate graphical output, record the
history of the data the algorithm generates, or halt the algorithm based on the data at the
current iteration.

You can create an output function as a function file, a local function, or a nested function.

Output functions are:

 fminbnd
 fminsearch
 fzero
5.11.plot commands
MATLAB is an interactive multi-programming language and numeric computing environment
developed by MathWorks. MATLAB provides the Commands that will be used when the user
wants to interact with any application using the command line interface.

plot(x,y) fplot( f ) title

xlabel ylabel Ez plot

subplot bar pie

1.plot(x,y)

To plot the graph of a function, you need to take the following steps −
 Define x, by specifying the range of values for the variable x, for which the function is to
be plotted
 Define the function, y = f(x)
 Call the plot command, as plot(x, y)
Following example would demonstrate the concept. Let us plot the simple function y = x for the
range of values for x from 0 to 100, with an increment of 5.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 118


Create a script file and type the following code −

x = [0:5:100];
y = x;
plot(x, y)
When you run the file, MATLAB displays the following plot −

fplot( f ) : plots the curve defined by the function y = f(x) over the default interval [-5 5] for x .

Examples
Plot Expression
Try This ExampleCopy Command Copy Code

Plot sin(x) over the default x interval [-5 5].


fplot(@(x) sin(x))

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 119


fplot( f , xinterval ) plots over the specified interval. Specify the interval as a two-element vector
of the form [xmin xmax] .

example:
Specify Plotting Interval and Plot Piecewise Functions

Plot the piecewise function

excos(x)−3<x<00<x<3.
Plot multiple lines using hold on. Specify the plotting intervals using the second input argument
of fplot. Specify the color of the plotted lines as blue using 'b'. When you plot multiple lines in
the same axes, the axis limits adjust to incorporate all the data.
fplot(@(x) exp(x),[-3 0],'b')
hold on
fplot(@(x) cos(x),[0 3],'b')
hold off
grid on

MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust
the axes to spruce up the graph.
 The xlabel and ylabel commands generate labels along x-axis and y-axis.
 The title command allows you to put a title on the graph.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 120


 The grid on command allows you to put the grid lines on the graph.
 The axis equal command allows generating the plot with the same scale factors and the
spaces on both axes.
 The axis square command generates a square plot.

Example
Create a script file and type the following code −

x = [0:0.01:10];
y = sin(x);
plot(x, y), xlabel('x'), ylabel('Sin(x)'), title('Sin(x) Graph'),
grid on, axis equal
MATLAB generates the following graph −

Ez plot:

Syntax
ezplot(f)

ezplot(f,xinterval)

ezplot(f2)

ezplot(f2,xyinterval)

ezplot(funx,funy)

ezplot(funx,funy,uinterval)

ezplot(___,fig)

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 121


ezplot(ax,___)

h = ezplot(___)

Description
example
ezplot(f) plots the curve defined by the function y = f(x) over the default interval [-2π 2π] for x.
ezplot automatically adds a title and axis labels to the plot.
ezplot(f,xinterval) plots over the specified interval. Specify the interval as a two-element vector
of the form [xmin xmax].
ezplot(f2) plots the curve defined by the implicit function 0 = f2(x,y) over the default interval [-
2π 2π] for x and y.
ezplot(f2,xyinterval) plots over the specified interval. To use the same interval for both x and y,
specify xyinterval as a two-element vector of the form [min max]. To use different intervals,
specify a four-element vector of the form [xmin xmax ymin ymax].
ezplot(funx,funy) plots the parametrically defined planar curve defined by x = funx(u) and y =
funy(u) over the default interval [0 2π] for u.
ezplot(funx,funy,uinterval) plots over the specified interval. Specify the interval as a two-
element vector of the form [umin umax].
ezplot(___,fig) plots into the specified figure window. Use any of the input argument
combinations in the previous syntaxes that include an interval.
ezplot(ax,___) plots into the axes specified by ax instead of the current axes gca. Specify the
axes before any of the input argument combinations in any of the previous syntaxes except for
the ones that involve fig. This syntax does not support the fig input.
h = ezplot(___) returns either a chart line or contour object. Use h to modify the chart line or
contour after it is created. For a list of properties, see Line Properties and Contour Properties.

Sub plot:

subplot( m , n , p ) divides the current figure into an m -by- n grid and creates axes in the
position specified by p . MATLAB® numbers subplot positions by row. The first subplot is the
first column of the first row, the second subplot is the second column of the first row, and so
on.

Syntax
subplot(m,n,p)

subplot('Position',pos)

subplot(___,Name,Value)

subplot(m,n,p) divides the current figure into an m-by-n grid and creates axes in the position
specified by p. MATLAB® numbers subplot positions by row.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 122


subplot('Position',pos) creates axes in the custom position specified by pos. Use this option to
position a subplot that does not align with grid positions.

subplot(___,Name,Value) modifies axes properties using one or more name-value pair


arguments. Set axes properties after all other input arguments.

Bar() :

 To plot a single series of bars, specify y as a vector of length m. The bars are positioned from 1
to m along the x-axis.
 To plot multiple series of bars, specify y as a matrix with one column for each series.

bar(x,y) draws the bars at the locations specified by x.


bar(___,style) specifies the style of the bar groups. For example, use 'stacked' to display each
group as one multicolored bar.
example
bar(___,color) sets the color for all the bars. For example, use 'r' for red bars.

Examples
Create Bar Graph
Try This ExampleCopy Command Copy Code

y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y)

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 123


Pie() :
 pie( X ) draws a pie chart using the data in X . Each slice of the pie chart represents an
element in X . If sum(X) ≤ 1 , then the values in X directly specify the areas of the pie
slices. pie draws only a partial pie if sum(X) < 1 .
 If sum(X) > 1, then pie normalizes the values by X/sum(X) to determine the area of each
slice of the pie.
 If X is of data type categorical, the slices correspond to categories. The area of each slice
is the number of elements in the category divided by the number of elements in X.
Examples
Create Pie Chart with Offset Slices
Try This ExampleCopy Command Copy Code

Create a pie chart of vector X.


X = [1 3 0.5 2.5 2];
pie(X)

Offset the second and fourth pie slices by setting the corresponding explode elements to 1.

5.12.usage of SIMULINK,GUI :
SIMULINK:
Simulink is a simulation and model-based design environment for dynamic and embedded
systems, integrated with MATLAB. Simulink, also developed by MathWorks, is a data flow
graphical programming language tool for modelling, simulating and analyzing multi-domain
dynamic systems. It is basically a graphical block diagramming tool with customizable set of
block libraries.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 124


It allows you to incorporate MATLAB algorithms into models as well as export the simulation
results into MATLAB for further analysis.
Simulink supports −

 system-level design
 simulation
 automatic code generation
 testing and verification of embedded systems
There are several other add-on products provided by MathWorks and third-party hardware and
software products that are available for use with Simulink.
The following list gives brief description of some of them −
 Stateflow allows developing state machines and flow charts.
 Simulink Coder allows the generation of C source code for real-time implementation of
systems automatically.
 xPC Target together with x86-based real-time systems provide an environment to
simulate and test Simulink and Stateflow models in real-time on the physical system.
 Embedded Coder supports specific embedded targets.
 HDL Coder allows to automatically generate synthesizable VHDL and Verilog.
 SimEvents provides a library of graphical building blocks for modelling queuing systems.
Simulink is capable of systematic verification and validation of models through modelling style
checking, requirements traceability and model coverage analysis.
Simulink Design Verifier allows you to identify design errors and to generate test case scenarios
for model checking.

GUI :
Graphical user interfaces (GUIs), also known as apps, provide point-and-click control of your
software applications, eliminating the need for others to learn a language or type commands in
order to run the application. You can share apps both for use within MATLAB and also as
standalone desktop or web apps.

 Convert a script into a simple app: Choose this option when you want to share a script
with students or colleagues and allow them to modify variables using interactive controls.
 Create an app interactively: Choose this option when you want to create a more
sophisticated app using a drag-and-drop environment to build the user interface.
 Create an app programmatically: Choose this option when you want to create an app’s
user interface by writing the code yourself.

Prepared by Mr.B.SATISH KUMAR | Mail ID: satishkumar.pace@gmail.com Page 125

You might also like