Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CS3353 Unit1

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

CS3353 C Programming and Data Structures

Syllabus

Variables – Data Types – Expressions using operators in C – Managing Input


and Output operations – Decision Making and Branching – Looping
statements. Arrays – – One dimensional and Two- dimensional arrays.
DATA TYPES IN C

The data type, of a variable determines a set of values that a variable might take and aset
of operations that can be applied to those values.

Data type refers to the type and size of data associated with the variable and functions.

Data types can be broadly classified as shown in Figure

Basic data type of C

Data Type Size in Range Format-


Bytes Specifier
int 2 -32768 to +32767 %d
short signed int 2 32768 to +32767 %d
(or)
signed int
Int short unsigned int 2 0 to 65535 %u
(or)
unsigned int
long signed int (or) 4 -2147483648 to 2147483647 %ld
long int
long unsigned int 4 0 to 4294967295 %lu

Char char or signed char 1 -128 to 127 %c


unsigned char 1 0 to 255 %c
float 4 -3.4e-38 to +3.4e38 %f

Allows 6 digits
after decimal point.
double 8 -1.7e-308 to +1.7e308 %lf

Allows 15 digits
after decimal
point.
long double 10 -1.7e-4932 to 1.7e4932 %LF

Allows 15 digits
after decimal
point.
/*Program*/
#include<stdio.h>
int main()
{
char a;
unsigned char b;
int i;
unsigned int j;
long int k;
unsigned long int m;
float x;
double y
long double z;

printf(―\n char and unsigned char‖);


scanf(―%c %c‖,&a,&b) //get char and unsigned char value
printf(―%c %c‖,a,b) //display char and unsigned char value

printf(―\n int unsigned int‖);


scanf(―%d %u‖,&i,&j) //get int unsigned int value
printf(―%d %u‖,i,j) //display int unsigned int value

printf(―\n long int unsigned long int‖);


scanf(―%ld %lu‖,&i,&j) //get long int and long unsigned int value
printf(―%ld %lu‖,i,j) //display int unsigned int value

printf(―\n float,double and long double‖);


scanf(―%f %lf %Lf‖,&i,&j) //get float,double and long double value
printf(―%f %lf %Lf‖,i,j) //display float,double and long double value

return 0;
}
The specifiers and qualifiers for the data types can be broadly classified into
three types

 Size specifiers— short and long


 Sign specifiers— signed and unsigned
 Type qualifiers— const, volatile and restrict.

Size qualifiers alter the size of the basic data types. There are two such qualifiers that can
be used with the data type int; these are short and long.

short, when placed in front of the data type int declaration, tells the C compiler that the
particular variable being declared is used to store fairly small integer values. Long specifies it
is a very big integer value.Long integers require twice the memory of than small ints.

Table: Sizes (bytes) of short int ,int,long int

16-bit Machine 16-bit Machine 16-bit Machine


(size in bytes) (size in bytes) (size in bytes)
short int 2 2 2
Int 2 4 4
long int 4 4 8

Table:Size and range of long long type (64-bit machine)

Data type Size (in Range


bytes)
long long int 8 -9, 223, 372, 036, 854, 775, 808 to
+9, 223, 372, 036, 854, 775, 808

unsigned long int or 4 0 to + 4, 294, 967, 295


unsigned long
unsigned long long int or 8 0 to + 18, 446, 744, 073,709, 551, 615
unsigned long long

Sign specifiers: for example fot int data type out of 2bytes(2*8=16bits) of its size the
highest bit(the sixtheenth bit) is used to store the sign of the integer value. The bit is 1 if
number is negative and 0 if the number is positive.

Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Sign of number
(1 for –ve and 0
for +ve0

Type qualifiers : There are two type qualifiers, const and volatile;
Eg: const float pi = 3.14156; // specifies that the variable pi can never be changed bythe
Program.
Table:Size and range in (16-bit machines)

Data type Size (in bits) Range


note:[1byte=8bits]
Char 8 –128 to 127
Int 16 –32768 to 32767
Float 32 1.17549 × 10–38 to 3.40282 × 1038
Double 64 2.22507 × 10–308 to 1.79769 × 10 308
Void 8 Valueless

Table:Size and range of (32-bit machine)

Data type Size (in bits) Range


note:[1byte=8bits]
Char 8 –128 to 127
Int 32 –2147483648 to 2147483647
Float 32 1.17549 × 10–38 to 3.40282 × 1038
Double 64 2.22507 × 10-308 to 1.79769 × 10 308
Void 8 Valueless

Allowed combinations of basic data types and modifi ers in C for a 16-bit
computer

STUDENTSFOCUS
VARIABLES
Variable is the name of memory location which holds the data. Unlike constant, variables are
changeable, value of a variable can be changed during execution of a program. A
programmer must chose a meaningful variable name.

Variables are used for holding data values so that they can be utilized for various
computations in a program.A variable must be declaed and then used for coputation work in
program./A variable is an identifier used for storing and holding some data(value).

All variables have three important attributes.

1.A data type: Like int, double, float. Once defined,the type of a C variable
cannot be changed.
2.A name of the variable.
3.A value that can be changed by assigning a new value to the variable. The
kind of values a variable can assume depends on its type.
Eg : for variable int salary,it can only take integer values can only take integer
values like 65000 and not 6500.0
Rules For Constructing Variables

1. A variable name can be a combination of alphabets, numbers and specialcharacter


underscore( _ ).
2. The first character in the variable name must be an alphabet.
3. No commas or blank spaces are available are allowed within a variable name.
4. No special symbol other than an underscore is allowed.
5.Upper and Lower case names are treated as different, as C is case sensitive, so it is
suggested to keep the variable names in lower case.

Declaring and Initializing a variable:=

Declaration of a variable must be done before it is used for any computation inhte
program.
Declaration tells the compiler what the variable name is.
 Declaration tells what type of data the variable will hold.
Until the variable is not defined/or/declared compiler will not allocate memory space tothe
variables.
 A variable can also be declared outside main() function.
A variable can also be declared in other program and declared using extern keyword.

int yearly_salary;
float monthly_salary;
int a;
double x;
int ECE1111;
Initializing a variable:=
Initializing a variable means to provide a value to variable
int yearly salary=5,00,000
float monthly salary=41666.66
Difference between identifier and variable
Identifier Variable
Indentifier is the name given to a While variable is used to name a memory
variable,function etc. location which stores data
An identifier can be a variable ,but not all All variables names are identifiers
identifiers are variables
Example : void average() Example: int average
{
}

Variables are a way of reserving memory to hold some data and assign names to them so that
we don’t have to remember the numbers like REG46735 or memory address like FFFFoxFF
and instead we can use the memory location by simply referring to the variable.

Every variable is mapped to a unique memory address.

And variable will be having a data type associated

int salary = 65000;

[[[[[[note A computer memory is made up of registers and cells. It accesses data in a


collection of bits, typically 8 bits, 16 bit, 32 bit or 64 bit. A computer memory holds information in
the form of binary digits 0 and 1 (bits).]]]]]]
Operators in C
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators –

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Special Operators

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

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
% B%A=0
integer division.
Increment operator increases the integer value by
++ A++ = 11
one.
Decrement operator decreases the integer value
-- A-- = 9
by one.

Relational Operators

The following table shows all the relational operators supported by C.


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
== (A == B) is not true.
yes, then the condition becomes true.
!= Checks if the values of two operands are equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.
Checks if the value of left operand is greater than the value
> (A > B) is not true.
of right operand. If yes, then the condition becomes true.
Checks if the value of left operand is less than the value of
< (A < B) is true.
right operand. If yes, then the condition becomes true.
Checks if the value of left operand is greater than or equal
>= to the value of right operand. If yes, then the condition (A >= B) is not true.
becomes true.
Checks if the value of left operand is less than or equal to
<= the value of right operand. If yes, then the condition (A <= B) is true.
becomes true.
Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then −

Operator Description Example


Called Logical AND operator. If both the operands are
&& (A && B) is false.
non-zero, then the condition becomes true.
Called Logical OR Operator. If any of the two operands is
|| (A || B) is true.
non-zero, then the condition becomes true.
Called Logical NOT Operator. It is used to reverse the
! logical state of its operand. If a condition is true, then !(A && B) is true.
Logical NOT operator will make it false.

Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
P q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
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
& (A & B) = 12, i.e., 0000 1100
It takes 1 if both operands has value 1.
Binary OR
Operator copies a bit if it exists in either operan
| (A | B) = 61, i.e., 0011 1101
The output of bitwise OR is 1 if at least one
corresponding bit of two operands is 1.
Binary XOR
^ 1 if the corresponding bits of two operands are (A ^ B) = 49, i.e., 0011 0001
opposite
Binary Ones Complement
~ (~A ) = -60, i.e,. 1100 0100
'flipping' bits- 0 changed to 1and 1 changed to 0
Binary Left Shift Operator.
<< The left operands value is moved left by the A << 2 = 240 i.e., 1111 0000
number of bits specified by the right operand.
Binary Right Shift Operator.
>> The left operands value is moved right by the A >> 2 = 15 i.e., 0000 1111
number of bits specified by the right operand.
Assignment Operators

The following table lists the assignment operators supported by the C language

Operator Description Example


Simple assignment operator. Assigns values from C = A + B will assign the value
=
right side operands to left side operand of A + B to C
Add AND assignment operator. It adds the right
C += A is equivalent to
+= operand to the left operand and assign the result to
C=C+A
the left operand.
Subtract AND assignment operator. It subtracts
C -= A is equivalent to
-= the right operand from the left operand and
C=C-A
assigns the result to the left operand.
Multiply AND assignment operator. It multiplies
C *= A is equivalent to
*= the right operand with the left operand and assigns
C=C*A
the result to the left operand.
Divide AND assignment operator. It divides the C /= A is equivalent to
/= left operand with the right operand and assigns the C=C/A
result to the left operand.
Modulus AND assignment operator. It takes C %= A is equivalent to
%= modulus using two operands and assigns the C=C%A
result to the left operand.
C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C << 2
C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

special Operators

Operator Description Example


int a;
sizeof() Returns the size of a variable.
sizeof(a), where a is integer, will return 2.
&a; returns the actual address of the
& Returns the address of a variable.
variable a .(OxFFA)
* Pointer to a variable. *a;
If Condition is true ? then value X :
?: Conditional Expression.
otherwise value Y
Operators Precedence in C

For example, x = 7 + (3 * 2); here, x is assigned 13, not 20 because operator * has
a higher precedence than +, so it first gets multiplied with 3*2 and then adds into
7.

Table showing highest precedence to lowest precedence

Category Operator Associativity


Postfix ( ) [ ] -> . ++ - - Left to right
Unary Unary +,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

Expression

Expression is a combination of variables(like a,b,m,n..), constants(3,2,1) and


operators(+,/*).

Eg : c+d

x/y+b+a*a*a

3.14 *r *r

Algebraic Expression C Expression


ab-c a*b-c
(m+n)(k+j) (m+n)*(k+j)
(ab/c) a*b/c
3x2+2x+1 3*x^2+2*x+1
Example Program
#include<stdio.h>
Program
int main( )
{
int x=2,y=3,result;
result=x*5+y*7;
printf(“result =:%d”,result);
return 0;
}
Expression evaluation
result=x*5 + y*7;
result=2*5 + 3*7;
result=2*5 + 3*7;
result=10 + 3*7;
result=10 + 21;
result=31;

Example program –find greatest of 3 numbers


Example of logical(&& logical AND) and relational operators(>)

#include<stdio.h>
int main()
{
int num1,num2,num3;

printf("\nEnter value of a, b and c:");

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

if((a>b)&&(a>c))
printf("\n %d is greatest",a);
else if(b>c)
printf("\n %d is greatest",b ");
else
printf("\n %d is greatest",c);
return 0;
}

Example program –find odd or even number


Example of Arithmetic(% mod) and relational operators(==)
#include<stdio.h>
int main()
{ int num,result;
if(num%2==0)
printf(“even number \n”);
else
printf(“odd number \n”);
return 0;
}
Bitwise XOR
Explanation

12 = 00001100 (In Binary)


#include <stdio.h> 25 = 00011001 (In Binary)
int main()
Bitwise XOR Operation of 12 and 25
{ 00001100
int a = 12, b = 25; 00011001
printf("Output = %d", a^b);
return 0; 00010101 = 21 (In decimal)
}

Output = 21

Bitwise complement 1‟s compliment Explanation

#include <stdio.h> 35 = 00100011 (In Binary)


int main()
{ Bitwise complement Operation of 35
printf("complement = %d\n",~35); ~ 00100011
return 0; 11011100 = 220 (In decimal)
}
OutPut:

complement = 220

Bitwise AND and OR operator


12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
#include <stdio.h> Bitwise AND Operation of 12 and 25
int main() 00001100
{ & 00011001
int a = 12, b = 25; 00001000 = 8 (In decimal)
printf("OutputAND = %d", a&b); Bitwise OR Operation of 12 and 25
printf("OutputOR = %d", a|b); 00001100
return 0; | 00011001
}
00011101 = 29 (In decimal)

OutputAND = 8
OutputOR = 29
Decision Making and Branching

Conditional Branching Conditional Branching


if statement break
nested if statement continue
if ..else statement goto
nested if else statement

These include conditional type branching and unconditional type branching.


if statement
It takes the following form

if(test-expression)

It allows the computer to evaluate the expression first and them depending on whether
the value of the expression is "true" or "false", it transfer the control to a particular
statements. This point of program has two paths to flow, one for the true and the other
for the false condition.
if(test-expression)
statement-block
{
statement-x;
}

The statement-block may be a single statement or group of statements. If the test


expression is true, the statement-block will be executed; otherwise the statement-block
will be skipped and the execution will jump to the statement-x. But when is condition
true both the statement-block and the statement-x are executed in sequence.

Eg: Example program: C Program to check


equivalence of two numbers using if statement

#include<stdio.h>
#include<conio.h>
void main()
{
int m,n;
clrscr();
printf(" \n enter two numbers:");
scanf(" %d %d", &m, &n);
if(m-n= = 0)
Eg-2 {
if (code = = 1) printf(" \n two numbers are equal");
{ }
salary = salary + 500; getch();
} }
printf("%d",salary);
Output:
44
Two Numbers are Equal
Nested if

The syntax for a nested if statement is as follows

if( cond 1)
{
/* Executes boolean expression when cond 1 is true */
if(cond 2) {
/* Executes when the boolean expression 2 is true */
}
}
Example:
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;
if( a == 100 ) {
/* if condition is true then check the following */
if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}

The if-else statement


The if-else statement is an extension of the simple if statement. The general form is If
the test- expression is true, then true-block statements immediately following if
statement are executed otherwise the false-block statements are executed.
if(test-expression)
Example: C program to find largest of twonumbers {true-block statements
#include<stdio.h> }
int main() else
{ {
int m,n,large; false-block statements
printf(" \n enter two }statement-x
numbers:"); scanf(" %d %d",
&m, &n); if(m>n)
large=
m; else
large=n
;
printf(" \n large number is = %d",
large); return 0;
}
Nested if-else statement
Nested if construct is also known as if-else-if construct.

Syntax-1 Syntax-2

if(test-condition-1) If(test-condition-1)

(stmts) if(test-condition-2)
else
statement-1;
if(condition 2)
else
Statement-1;
statement-2;
else

statement-2; else

statement-3;

statement-x statement-x

If the test-condition-1 is false, the statement-3 will be executed; other wise it continues
the second test. If the condition-2 is true, the statement-2 will be evaluated and then the
control is transferred to the statement-x.
Example:Program to relate two integers using =, > or <

#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}

// if both test expression is false


else
{
printf("Result: %d < %d",number1, number2);
}
return 0;
}
The switch statement:
When many conditions are to be checked then using nested if...else is very difficult, confusing and
cumbersome. So C has another useful built in decision making statement known as switch. This
statement can be used as multiway decision statement. The switch statement tests thevalue of a given
variable or expression against a list of case values and when a match is found, a block of statements
associated with that case is executed.
Eg-1
int i = 1;
switch(i) switch( code)
{ {
case 1: case 1:
printf("A"); stmts1;
break; break;
case 2: case 2:
printf("B"); stmts2;
break;
break;
case 3:
printf("C"); case 3:
break; stmts3
default: break;
} default:
stmtsx
}
For case 1,
EX: Program to find the salary of the Employee da=10% of basicsalary.
void main ()
{ For case 2,
float basic , da , salary ; int code ; da=15% of basic salary.
char name[25];
da=0.0; For case 3,
printf("Enter employee name\n"); da=20% of basic salary.
scanf("%[^\n]",name);
printf("Enter basic salary\n");
For default case:
scanf("%f",&basic);
da =0
printf("Enter code of the Employee\n");
scanf("%d",&code);
switch (code) o/p
{
case 1: Enter name of employee:
da = basic * 0.10;break; Kartiyani
Enter Basic
case 2: salary 5000
da = basic * 0.15;break;
case 3: Enter code of
da = basic * 0.20; employee 1
break;
default : Employee name
da = 0; is Kartiyani
} DA is 500 and total salary is 5500
salary = basic + da;
printf("Employee nameis\n");
printf("%s\n",name);
printf ("DA is %f and Total salary is =%f\n",da,
salary);
getch();
}
Rules for using switch statement

1. The expression (after switch keyword) must yield an integer value


2. The case label values must be unique.
3. The case label must end with a colon(:)

Difference between switch and if

 if statements can evaluate float conditions. switch statements cannot evaluate


float conditions.
 if statement can evaluate relational operators. switch statement cannot evaluate
relational operators i.e they are not allowed in switch statement.
BREAK

The break statement in C programming has the following two usages −

 When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following
theloop.
 It can be used to terminate a case in the switch statement

BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to
get back to the conditional test.

The syntax for a break statement in C is as follows −

break;

Example program
#include <stdio.h> Output:
int main ()
{ value of a: 10
int a = 10; value of a: 11
while( a < 20 ) value of a: 12
{ value of a: 13
printf("value of a: %d\n", a); value of a: 14
a++; value of a: 15
if( a > 15)
{
break;
}
}
return 0;
}
Continue

The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions
of the loop to execute. For the while and do...while loops, continue statement causes the
program control to pass to the conditional tests.

Syntax: continue;

Example program Output


#include <stdio.h> value of a: 10
int main () value of a: 11
value of a: 12
{ value of a: 13
int a = 10; value of a: 14
do { value of a: 16
value of a: 17
if( a == 15) value of a: 18
{ value of a: 19
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a) ;
a++;
} while( a < 20 );
return 0;
}
Break Continue
The break statement can be used in both The continue statement can appear only in
switch and loop (for, while, do while) loops. You will get an error if this appears
statements. in switch statement.
A continue doesn't terminate the loop, it
A break causes the switch or loop
causes the loop to go to the next iteration.
statements to terminate the moment it is
The continue statement is used to skip
executed. Loop or switch ends abruptly
statements in the loop that appear after the
when break is encountered.
continue.
The continue statement can appear only in
The break statement can be used in both
loops. You will get an error if this appears
switch and loop statements.
in switch statement.
When a break statement is encountered, it When a continue statement is
terminates the block and gets the control encountered, it gets the control to the next
out of the switch or loop. iteration of the loop.

GOTO

GOTO STATEMENT
„C‟ supports goto statement to branch unconditionally from one point to another in the program.

A goto statement in C programming provides an unconditional jump from the 'goto' to a


labeled statement.

NOTE − Use of goto statement is highly discouraged in any programming language


because it makes difficult to trace the control flow of a program, making the program hard to
understand and hard to modify. Any program that uses a goto can be rewritten to avoid
them.

Syntax

The syntax for a goto statement in C is as follows −

goto label;
..
.
label: statement;

Or

label: statement;
...

...

goto label;
Output

value of a: 10
value of a: 11
value of a: 12
Example program value of a: 13
#include <stdio.h> value of a: 14
int main () value of a: 16
{ value of a: 17
int a = 10; value of a: 18
ABCL:do value of a: 19
{
if( a == 15)
{
a = a + 1;
goto ABCL;
}
printf("value of a: %d\n", a) ;
a++;
}while( a < 20 );
return 0;
}
program to print “n‟ natural number

#include<stdio.h>
void main( )
{
int n,i=1;
clrscr();
printf("enter number");
scanf("%d\t",n);
printf("natural numbers from 1 to %d", n);
lb: printf("%d\t",i);
i++;
if(i<=n)
goto lb;
getch();
}
LOOPING STATEMENTS

Loop constructs supports repeated execution of statements when a condition matches.

If the loop Test Condition is true, then the loop is executed, the sequence of
statements to be executed is kept inside the curly braces {} is known as the Loop body.
After every execution of the loop body, condition is verified, and if it is found to be true the
loop body is executed again. When the condition check returns false, the loop body is not
executed, and execution breaks out of the loop.

Types of Loop

There are 3 types of Loop in C language, namely:

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

while loop
Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
while(condition)

statements;

Example-- Example: //Program to print first 10 natural numbers


#include<stdio.h
> void main( )
{
int x;
x =
1;
while(x <= 10)
{
printf("%d\t", x);
x++;
}
}
Output: 1 2 3 4 5 6 7 8 9 10
do while loop

In some situations it is necessary to execute body of the loop before testing the
condition. Such situations can be handled with the help of do-while loop. do statement
executes the body of the loop first and at the end, the condition is checked using while
statement. It means that the body of the loop will be executed at least once, even though the
starting condition inside while is initialized to be false.
General syntax

do {
statement(s);
} while( condition );

Example:// Program to print first 10 multiples of 5.


#include<stdio.h
> void main()
{
int a,
i; a =
5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 12);
}

Output

5 10 15 20 25 30 35 40 45 50 55 60
Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part


of the loop or to leave the loop

1) break statement

When break statement is encountered inside a loop, the loop is


immediately exited and the program continues with the statement
immediately following the loop.
2) continue statement

It causes the control to go directly to the test-condition and then continue the loop process.
On encountering continue, cursor leave the current cycle of loop, and starts with the next
cycle.

For Loop

for loop is used to execute a set of statements repeatedly until a particular condition is
satisfied. We can say it is an open ended loop. General format is,

for(initialization; condition; increment/decrement)


{
statement-block;
}

In for loop we have exactly two semicolons, one after initialization and second after the
condition. In this loop we can have more than one initialization or increment/decrement,
separated using comma operator. But it can have only one condition.

The for loop is executed as follows:

1. It first evaluates the initialization code.


2. Then it checks the condition expression.
3. If it is true, it executes the for-loop body.
4. Then it evaluates the increment/decrement condition and again follows from
step 2.
5. When the condition expression becomes false, it exits the loop.
Example: Program to print first 10 natural numbers
#include<stdio.h
> void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
Output: 1 2 3 4 5 6 7 8 9 10

Nested for loop


We can also have nested for loops, i.e one for loop inside another for loop. Basic
syntax is,

for(initialization; condition; increment/decrement)


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

#include<stdio.h> Output
void main( ) 1
{ 21
int i, j; 321
4321
for(i = 1; i < 5; i++) /* first for loop */
54321
{ printf("\n");
/* second for loop inside the first
*/ for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}
ARRAYS

<Arrays – Initialization – Declaration – One dimensional and Two-dimensional arrays.>

1. ONE DIMENTIONAL ARRAY

2. TWO DIMENTIONAL ARRAY

3. STRING ARRAYS (ONE DIMENTIONAL ARRAY and TWO DIMENTIONAL ARRAY)

4. MULTIDIMENTIONAL ARRAYS

An array is a collection of similar data items, accessed using a common name. The
collection of element can all be integers or be all decimal value or be all characters or
be all strings.
 A one-dimensional array is like a list
 A two dimensional array is like a table
 The C language places no limits on the number of dimensions in an array

ONE DIMENTIONAL ARRAY

Array Declaration:
To declare an array in C, a programmer specifies the type of the elements and the number
of elements required. The arraySize must be an integer constant greater than zero and
datatype can be any valid C data type.

Syntax1:
datatype arrayName[ arraySize ];
int n;
Example-1 Scanf(“%d”,&n);//getsize
int x[n]; //array declaration
int number[20]; int marks[44]; float
salary[10];
double value[25]; #include<stdio.h>
int main( )
#define N 100 {
int n=25; int main( ) int N=10,M=20;
double x[n], y[n]; int marks[N*M];//array dec
//array declaration { ....
int marks[N];//array dec return 0;
.... }
return 0;
}

Syntax-2

<storage class> datatype arrayName[ arraySize ];

Example: static int marks[20];


Array intitialization:
Example-1 int mark[5] = {55, 66, 77, 88, 99};

mark[0] = 55
mark[1] = 66
mark[2] = 77
mark[3] = 88
mark[4] = 99

Example-2 double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};

it means. .
balance[0] = 1000.0;
balance[1] = 2.0;
balance[2] = 3.4;
balance[3] = 7.0;
balance[4] = 50.0;

Automatic sizing

int arr[] = {3,1,5,7,9};

Here, the size of the array in these cases is equal to the number of elements present in the initializer
list as the compiler can automatically deduce the size of the array.
OPERATIONS ON ARRAYS
o Traversing an array
o Inserting an element in an array
o Searching an element in an array
o Deleting an element from an array
o Merging two arrays
o Sorting an array in ascending or descending order
Working with one dimensional array
STORE and DISPLAY VALUES IN AN ARRAY (traversing an array)
#include<stdio.h>
int main( ) Output:
{ Enter the array elements
int k,array[10];//array declaration 2
printf(―Enter the array elements:‖);
for(k=0;k<5;k++)
{
scanf(―%d ‖,&array[i]); // storing values in array
} Display the array elements
printf(―\n Display the array elements:‖); 2
for(k=0;k<5;k++)
{
printf(―%d \n‖,array[i]);//displaying values of array
}
return 0;
}
FIND SUM AND AVERAGE OF N NUMBERS
#include<stdio.h>
int main( ) Output:
Enter the array size: 6
{
Enter the array elements
int k,n,sum=0;array[10];//array declaration 9
float avg;
printf(―\n Enter the array size:‖);
scanf(―%d‖,&n);
printf(―\n Enter the array elements:‖);
for(k=0;k<n;k++)
{
scanf(―%d ‖,&array[i]); // storing values in array sum=27 and avg=4.50000
}
for(k=0;k<n;k++)
{
sum=sum+array[i]; //sum of array elements
}
avg=sum/n;
printf(―\n sum=%d and avg=%f ‖,sum,avg);
}
return 0; Output:
} Enter the arrayelements
REVERSE OF ARRAY ELEMENTS 2
#include<stdio.h> 4
int main( ) 3
{ 1
int k,n,array[10];//array declaration 8
Display the arrayelements
printf(―\n Enter the array size:‖);
8
scanf(―%d‖,&n);
1
printf(―\n Enter the array elements:‖);
3
for(k=0;k<n;k++)
4
2
{
scanf(―%d ‖,&array[i]); // storing values in array
}
printf(―\n array elements in reverse order:‖);
MM for(k=n-1;k>=0;k--)
{
printf(―%d \n‖,array[i]);//displaying values of array
}
return 0;
}
Write a program to print the position of the smallest number of n numbers using
arrays.

#include <stdio.h>
int main()
{
int i, n, arr[20], small, pos;
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements : ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
small = arr[0] Output
for(i=1;i<n;i++) Enter the number of elements in the array : 5
{ Enter the elements : 7 6 5 14 3
if(arr[i]<small) The smallest element is : 3
{ The position of the smallest element in the
small = arr[i]; array is : 4
pos = i;
}
}
printf("\n The smallest element is : %d", small);
printf("\n The position of the smallest element in the array is:
%d", pos);
return 0;
}

Program example-1 Printing binary equivalent of a decimal number using array

Logic Here the remainders of the integer division of a decimal number by 2 are storedas
consecutivearrayelements.Thedivisionprocedure is repeateduntilthenumberbecomes
0.

#include <stdio.h> Output:


int main() Enter the decimal Integer: 12
{ Binary equivalent of 12 is: 1100
int bi[20],i,m,num,rem;
printf(―\n Enter the decimal Integer‖);
scanf(―%d‖,&n);
m=n;
for(i=0;i>n;i++)
{
rem=num%2;
bi[i]=rem;
num=num/2;
}
printf(―\n Binary equivalent of %d is: \t‖,m);
for(i--;i>=0;i--)
printf(―%d‖,a[i]);
return 0;
}
Program example- Fibonacci series using an array
Logic In Fibonacci series each element is the sum of the previous two elements. Thsi
program stores the series in an array Display the fibonacci elements
0
#include <stdio.h> 1
int main() 1
2
{ 3
int fib[15]; // array declaration 5
int i; 8
fib[0] = 0; // first array element value=0 13
fi b[1] = 1;// second array element value=1 21
34
for(i = 2; i < 15; i++) 55
{ 89
fib[i] = fib[i-1] + fib[i-2]; 144
} 233
printf(“\n Display the fibonacci elements:”); 377
for(i = 0; i < 15; i++)
{
printf(―%d\n‖, fi b[i]);
}
return 0;
}
Example- Inserting an Element in an Array
If an element has to be inserted at the end of an existing array, then the task of insertion is
quite simple. We just have to add 1 to the upper_ bound and assign the value. Here, we assume
that the memory space allocated for the array is still available. For example, if an array is declared to
contain 10 elements, but currently it has only 8 elements, then obviously there is space to
accommodate two more elements. But if it already has 10 elements, then we will not be able to add
another element to it.
Program to insert a number at a given location in an array
#include <stdio.h>
int main()
{
int i, n, num, pos, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\n Enter the number to be inserted : ");
scanf("%d", &num);
printf("\n Enter the position at which the number has to be added: ");
scanf("%d", &pos);
for(i=n–1;i>=pos;i––)
arr[i+1] = arr[i];
arr[pos] = num;
n = n+1;
printf("\n The array after insertion of %d is :num ");
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
getch();
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be added : 3
The array after insertion of 0 is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 4
arr[5] = 5

3. Deleting an Element from an Array

Algorithm to delete an element from the middle of an array

Step 1: [INITIALIZATION] SET I = POS


Step 2: Repeat Steps 3 and 4 while I <= N – 1
Step 3: SET A[I] = A[I + 1]
Step 4: SET I = I + 1
[END OF LOOP]
Step 5: SET N = N – 1
Step 6: EXIT

Write a program to delete a number from a given location in an array.


#include <stdio.h>
int main()
{
int i, n, pos, arr[10];
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\nEnter the position from which the number has to be deleted : ");
scanf("%d", &pos);
for(i=pos; i<n–1;i++) Output
Enter the number of elements in the array :
arr[i] = arr[i+1]; 5
n– –; arr[0] = 1
printf("\n The array after deletion is : "); arr[1] = 2
for(i=0;i<n;i++) arr[2] = 3
arr[3] = 4
printf("\n arr[%d] = %d", i, arr[i]); arr[4] = 5
getch(); Enter the position from which the number
return 0; has to be deleted : 3
} The array after deletion is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 5
TWO DIMENTIONAL ARRAY

Two dimentional arrays stores data in tabular column format represented as rows and columns

Array Declaration:
datatype arrayname[size][size];

Array Initialization:
int a[2][2]={ {1,4 },{2,3}}

int b[2][2]={1,4,2,3}

1 4
2 3

float[ ][ ]={12.3, 45.2,19.3,23.4}

12.3 45.2

19.3 23.4

Accessing two-dimensional Arrays

Program-sample two dimnentional array

#include <stdio.h>
int main()
{
int i,j;
int a[3][2] = {{4,7},{1,0},{6,2}};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 2; j++)
{
printf(“%d”, a[i][j]);
}
printf(“\n”);
}
return 0;
}
Row-1 4 7
Row -2 1 0
Row-3 6 2

The above array actually „looks‟ like this

1 2 3 4 5 6 7 8 9
Row 0 Row 1 Row 2
WORKING WITH TWO-DIMENSIONAL ARRAYS

Transpose of a matrix

Example program:-Transpose of a matrix

Transpose of A is AT=(aji), where i is the row number and j is the column number.

Program

#include <stdio.h>

int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
Sample output
// getting elements of the matrix Enter rows and columns of
printf("\nEnter elements of matrix:\n"); matrix: 2
for(i=0; i<r; ++i) 3
for(j=0; j<c; ++j)
{ Enter element of matrix:
printf("Enter element a%d%d: ",i+1, j+1); Enter element a11: 2
scanf("%d", &a[i][j]); Enter element a12: 3
} Enter element a13: 4
Enter element a21: 5
// Displaying the matrix a[][] */ Enter element a22: 6
printf("\n Entered Matrix: \n"); Enter element a23: 4
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) Entered Matrix:
{ 234
printf("%d ", a[i][j]);
if (j == c-1) 564
printf("\n\n");
}
Transpose of Matrix:
// Finding the transpose of matrix a 2 5
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) 3 6
{
transpose[j][i] = a[i][j]; 4 4
}

// Displaying the transpose of matrix a


printf("\nTranspose of Matrix:\n");
for(i=0; i<c; ++i)
for(j=0; j<r; ++j)
{
printf("%d ",transpose[i][j]);
if(j==r-1)
printf("\n\n");
}

return 0;
}
Program -2(Transpose)

#include <stdio.h>

void main()
{
int array[10][10]; int i, j, m, n;

printf("Enter the order of the matrix \n");


scanf("%d %d", &m, &n);
printf("Enter the coefiicients of the matrix\n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
}
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("Transpose of matrix is
\n"); for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
printf(" %d", array[i][j]);
}
printf("\n");
}

$ cc pgm85.c
$ a.out
Enter the order of the matrix 3 3
Enter the coefficients of the matrix 3 7 9
2 7 5
6 3 4
The given matrix is 3 7 9
2 7 5
6 3 4
Transpose of matrix is 3 2 6
7 7 3
9 5 4
Matrix addition and subtraction

Addition If A and B above are matrices of the same type

Subtraction If A and B are matrices of the same type, then

Program to Add Two Matrices

#include <stdio.h>
int main(){
int r, c, a[100][100], b[100][100], sum[100][100], i, j;

printf("Enter number of rows (between 1 and 100): ");


scanf("%d", &r);
printf("Enter number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for(i=0; i<r; ++i) Output
for(j=0; j<c; ++j)
{ Enter number of rows (between
printf("Enter element a%d%d: ",i+1,j+1); 1 and 100): 2
scanf("%d",&a[i][j]); Enter number of columns
} (between 1 and 100): 3
printf("Enter elements of 2nd matrix:\n");
for(i=0; i<r; ++i) Enter elements of 1st matrix:
Enter element a11: 2
for(j=0; j<c; ++j)
Enter element a12: 3
{ Enter element a13: 4
printf("Enter element a%d%d: ",i+1, j+1); Enter element a21: 5
scanf("%d", &b[i][j]); Enter element a22: 2
} Enter element a23: 3
// Adding Two matrices Enter elements of 2nd matrix:
for(i=0;i<r;++i) Enter element a11: -4
for(j=0;j<c;++j) Enter element a12: 5
{ Enter element a13: 3
sum[i][j]=a[i][j]+b[i][j]; Enter element a21: 5
Enter element a22: 6
} Enter element a23: 3
// Displaying the result
printf("\nSum of two matrix is: \n\n"); Sum of two matrix is:
for(i=0;i<r;++i)
for(j=0;j<c;++j) -2 8 7
{
10 8 6
printf("%d ",sum[i][j]);
if(j==c-1)
{
printf("\n\n");
}
}
return 0;
}
Matrix multiplication

Matrix multiplication for two 2 × 2 matrices.

Finding norm of a matrix


The norm of a matrix is defi ned as the square root of the sum of the squares of the elements of a matrix.

#include <stdio.h>
#include <math.h>
#defi ne row 10
#defi ne col 10
int main()
{
fl oat mat[row][col], s;
int i,j,r,c;
printf(“\n Input number of rows:”);
scanf(“%d”, &r);
printf(“\n Input number of cols:”);
scanf(“%d”, &c);
for(i = 0 ; i< r; i++)
{
for(j = 0 ;j<c; j++)
{
scanf(“%f”, &mat[i][j]);
}
}
printf(“\n Entered 2D array is as follows:\n”);
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf(“%f”, mat[i][j]);
}
printf(“\n”);
}
s = 0.0;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
s += mat[i][j] * mat[i][j];
}
}
printf(“\n Norm of above matrix is: %f”, sqrt(s));
return 0;
}
C Program to read a matrix and find sum, product of all elements of two dimensional (matrix)
array

include <stdio.h>
#define MAXROW 10 Enter number of Rows :3
#define MAXCOL 10 Enter number of Cols :3
int main()
{ Enter matrix elements :
int matrix[MAXROW][MAXCOL]; Enter element [1,1] : 1
int i,j,r,c; Enter element [1,2] : 1
int sum,product; Enter element [1,3] : 1
Enter element [2,1] : 2
printf("Enter number of Rows :");
Enter element [2,2] : 2
scanf("%d",&r);
Enter element [2,3] : 2
printf("Enter number of Cols :");
scanf("%d",&c); Enter element [3,1] : 3
Enter element [3,2] : 3
printf("\nEnter matrix elements :\n"); Enter element [3,3] : 3
for(i=0;i< r;i++)
{ SUM of all elements : 18
for(j=0;j< c;j++) Product of all elements :216
{
printf("Enter element [%d,%d] : ",i+1 ,j+1);
scanf("%d",&matrix[i][j]);
}
}
sum=0;
product=1;
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
sum+=matrix[i][j];
product*= matrix[i][j];
} }
printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);
return 0;
}
Find the sum of diagonal elements of a matrix 1 2 3
#include < stdio.h > 2 4 6
int main() 3 5 8
{
int a[10][10],i,j,sum=0,r,c; Sum of diagonal=13
clrscr();
printf("\n Enter the number of rows and column ");
scanf("%d%d",&r,&c);
printf("\nEnter the %dX%d matrix",r,c);
for(i=0;i < r;i++)
{
for(j=0;j < c;j++)
{
scanf("%d",&a[i][j]);
}//for
}//for
for(i=0;i < r;i++)
{ for(j=0;j < c;j++)
{ if(i==j)
{
sum+=a[i][j];
}
}//for
}//for
printf("\nThe sum of diagonal elements is %d",sum); return 0;
}//main

Sum of rows and columns

#include <stdio.h>
void main () Output
{
int array[10][10]; Enter the order of the matrix
int i, j, m, n, sum = 0; 22
printf("Enter the order of the matrix\n"); Enter the co-efficients of the matrix
scanf("%d %d", &m, &n); 23 45
printf("Enter the co-efficients of the matrix\n");
for (i = 0; i < m; ++i) 80 97
{ Sum of the 0 row is = 68
for (j = 0; j < n; ++j) Sum of the 1 row is = 177
{ Sum of the 0 column is = 103
scanf("%d", &array[i][j]); Sum of the 1 column is = 142
}
}
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
sum = sum + array[i][j] ;
}
printf("Sum of the %d row is = %d\n", i, sum);
sum = 0;
}
sum = 0;
for (j = 0; j < n; ++j)
{
for (i = 0; i < m; ++i)
{
sum = sum + array[i][j];
}
printf("Sum of the %d column is = %d\n", j, sum);
sum = 0;
}
}
C Program to do the Sum of the Main & Opposite Diagonal Elements of a MxN Matrix

#include <stdio.h>
void main ()
{ static int array[10][10]; Enter the order of the matix
int i, j, m, n, a = 0, sum = 0; 22
printf("Enetr the order of the matix \n"); Enter the co-efficients of the matrix
scanf("%d %d", &m, &n); 40 30
if (m == n ) 38 90
{ The given matrix is
printf("Enter the co-efficients of the matrix\n"); 40 30
for (i = 0; i < m; ++i) 38 90
{
for (j = 0; j < n; ++j) The sum of the main diagonal elements is
{ = 130
scanf("%d", &array[i][j]); The sum of the off diagonal elements is
} = 68
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}

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


{
sum = sum + array[i][i];
a = a + array[i][m - i - 1];
}
printf("\nThe sum of the main diagonal elements is = %d\n", sum);
printf("The sum of the off diagonal elements is = %d\n", a);
}
else
printf("The given order is not square matrix\n");
}

C Program to Find the Frequency of Odd & Even Numbers in the given Matrix
#include <stdio.h>
void main()
{

static int array[10][10];


int i, j, m, n, even = 0, odd = 0;

printf("Enter the order ofthe matrix \n");


scanf("%d %d", &m, &n);

printf("Enter the coefficients of matrix \n");


for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &array[i][j]);
if ((array[i][j] % 2) == 0)
{
++even;
}
else
++odd;
}

printf("The given matrix is \n");


for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
printf("\n The frequency of occurrence of odd number = %d \n", odd);
printf("The frequency of occurrence of even number = %d\n", even);

Enter the order of the matrix


33
Enter the coefficients of matrix
34 36 39
23 57 98
12 39 49
The given matrix is
34 36 39
23 57 98
12 39 49

The frequency of occurrence of odd number = 5


The frequency of occurrence of even number = 4

You might also like