0% found this document useful (0 votes)
8 views35 pages

Module 1 C Programming JDecisionMakingStructureArrays

Uploaded by

mohansharan486
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views35 pages

Module 1 C Programming JDecisionMakingStructureArrays

Uploaded by

mohansharan486
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

Module-1 1

Module-1

C programming: Decision making, control


structures and arrays.

Origin of C ( Who developed C? )

C was developed by Dennis Ritchie in early 1970’s at “AT & T’s Bell Labs”.
C was first developed for UNIX operating system. Latter C becomes very popular with DOS.
Before C , some other languages were used like BCPL which were further enhanced to produce
language B. B led to the development of C.

What Are The Applications Of C?


C is used for writing:
1. Operating System.
2. Compilers.
3. Database Managers.
4. Interpreters.
5. Assemblers.
6. Editors.
7. Spread sheet.
8. CAD and Animations.

What are the elements of a c program?


1. Keywords: int, char, if, for, enum, goto, etc
2. Identifiers: sum, employee, total, emp_id etc.
3. Data types: int, char, float and double.
4. Constants: 10, 2.5, “abc”
5. Operators: +, -, <<, &&
6. Special symbols: [], (),→, etc
Module-1 2

What is an identifier?
Identifiers are names of programming elements such as variables and functions. Identifier in C is
made up of letters, digits, and underscore. An identifier may start with either letter or an
underscore.
• Identifiers are used to name
o Variables, Constants, Functions, structures, enum, etc.
Rules to construct identifiers:→
1. An identifier must start with either letter or underscore.
2. An identifier can be a combination of any letter, digit, or an underscore.
3. An identifier can contain both uppercase or lower case letters.
4. An identifier may be of any length (Depends on architecture or compiler).

What is a keyword?
Every C word is classified as either keyword or an identifier. All keywords have fixed meaning
and these meanings can not be changed. Keywords serve as basic building blocks for program
statements. Examples:
int char float goto break continue
if else sizeof while for register
do const static auto extern double

What are the data types available in C ?

Data types in c++ can be classified as:

1. Primary data type (or built-in data type).


2. Derived data type.
3. User-defined data type.

Data types

1. Primary data types 2. Derived data types 3. User-defined data types


a. int. a. Arrays. a. Structures.
b. char. b. Pointers. b. Union.
c. float. c. Strings c. Enum.
d. double.
Module-1 3

What is a variable?
“A variable is a logical location in a computer memory which can take any values of the
specified type”. Or
“A variable is an object that may take on any values of specified type”.
A variable must be declared by specifying the data type and the identifier.
Syntax Example
DataType id1, id2, … idn; int val, num;

Primitive types in C language.

Type Format Specifier Memory Size


char %c 1 Bytes

int %d or %i 2 or 4 Bytes

float %f 4 Bytes

double %x 8 Bytes

What is modifier?

C allows you to modify the size of the data type by affixing one of the following:

Memory-size Memory size


Modifier Description
(in bytes) (in bits)
Means the integer not bigger than an int. 2 bytes 16 bits
short int Dependent on some machines.
short int is generally half of int.
long int Size is double of int. 4 bytes 32 bits

long float Size is double of float. 8 bytes 64 bits


Means that the integer without a sign. 2 bytes 16 bits
unsigned int. One bit larger than ordinary int.
Module-1 4

Explain the complete structure of a c program.

C program is a collection of one or more functions. A function is one or more statements


designed to perform a specific task. A c program may contain one or more sections as shown
below:

Documentation section // optional part


Global Declaration // optional part
Link section

// Main Function section


main ( )
{
Declaration part of main function;
Statement part of the main function;
}

Sub Function section // optional part


Function-1
Function-2
.........
.........
function-n

/ * The first c program demo*/ Documentation


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

void main( )
{ Main function
printf ( “hello”); section
}

//sub function section


Module-1 5

Some Examples.

• Convert the equation in C language format and Identify Operators and Operands.

1. C = 2 X2 + 5XY + Z where X = 2, Y = 3, Z = 1.

C language form of above equation is:


C=2*X*X+5*X*Y+Z;
Operators: ‘=’, ‘+’, ‘*’.
Variables: C, X, Y, Z.
C Program:

File Name : - sample1.c

# include < stdio.h >


void main( )
{
int c, x, y, z;
clrscr ( ) ;
x = 2;
y = 3;
z = 1;
c = 2 * x * x + 5 * x * y + z;
printf ( “Value of c is = %d”, c ) ;
}

• Similarly Convert the following equations into C language form and Identify Operators,
variables and constants.
2. D = 2 X3 + 5 X2 + Y where X = 2, Y = 2.
3. C = 2 A3 – 3 AB2 + 4 A2B + B where A = 1, B = 2.
4. Z = X3 + Y3X + XY where X = 1, Y = 1.

• Write a program to find simple Interest SI = PNR/100.


Where P = 10000, N = 3, R = 0.4

• Write a program to find Average and sum of A, B and C


Where A = 10, B = 30 , C = 20.
Module-1 6

Input and output statements

• Classification of input/output statements


1. Formatted input/output: printf, scanf
Formatted functions perform the required conversions of data during input or
output.
2. Unformatted input/output: getch, getchar, gets, putchar, puts
Un-Formatted functions does not perform any conversion while input or output.

1.1. Formatted printf function

printf function can handle any basic data type and offers several facilities to specify the
format of data display. printf performs formatted output to the standard output device.
printf performs following actions:

1. Accept a format string (or conversion string) followed by series of arguments.


2. Convert every argument to the corresponding format specifier contained in the
format string.
3. Output the formatted data in the desired format.

The general form of printf function:


printf (“format string”, variable list) ;

The format string includes:


a. All the text labels: All type of characters.
b. Escape character: Like \n, \t, \b etc.
c. Format specifier: Like %d, %f, %c, %s %x etc.

Example:
printf (“Total is : %d %d \n”, a, b) ;

Which contain %d a format specifier and \n a escape character. printf function converts
the argument a and b into integer format as specified by %d, and at the last it converts \n
as line feed.
Module-1 7

Some important format specifiers are shown in the table:


Type specifier Input type
%c Character
%i, %d Integer
%f Real number of float type
%lf Real number of double type
%s Character string
%o Octal
%h Short integer
%x Hexadecimal

1.2. Formatted function: scanf()


- scanf means scan formatted - is a basic formatted input function
- scanf reads until [ whitespace character is found, maximum number of characters
have been read, an error is detected or end of file is reached].
• General form of scanf
scanf (“format string”, variable list) ;

The format string includes:


a. Format specifiers: %d, %c, %f …
b. Field width ‘w’: %4d, %-10s, %0.2f, …

Example:

Statement scanf (“%2d %5d”, &n1, &n2);


Value 50 is assigned to n1
Input1 50 1234
Value 1234 is assigned to n2
Value 12 is assigned to n1 (because of %2d)
Input2 1234 50
Value 34 is assigned to n2
Module-1 8

1.3. Un-Formatted function:


i. getch(),getche(), getchar(),
ii. gets()
iii. putchar(), puts()

i) getch(), getche(), getchar()


functions getch, getche and getchar used to read a single character from console.
• Difference between getch, getche and getchar
getch() getche() getchar()
is a nonstandard library is a nonstandard library is a standard library
function function function
Does not echo the character Echo the character Echo the character
Returns the character read Returns the character read Returns the character read
without waiting for ENTER without waiting for ENTER only after ENTER key or
key or other key. key or other key. other key is pressed.
When to use: When to use: When to use:
//to read password //to read characters //to read characters

• Example:
void main()
{
char ch;
printf(“Enter the character: “);
ch = getch();
printf(“character by getch: %c ”, ch);
ch = getche();
printf(“character by getche: %c”, ch);
ch = getchar();
printf(“character by getchar: %c”, ch);
}
Output:
Module-1 9

ii) gets()
function gets() used to reads a character string from console and stores it into the
given character array.

• Format:
char* gets(char *str)
- Argument: str – is a pointer to an array of character where the string is stored.
- Return value: str on success, NULL on failure.
- This function returns str on success, and NULL on error or when end of file occurs,
while no characters have been read.

• Example

void main()
{
char str[50];

printf("Enter a string : ");


gets(str);

printf("You entered: %s", str);


}

Output:
Enter a string : RNSIT
You entered: RNSIT

iii) putchar(), puts()


- function putchar() is a library function that writes a specified character to stdout.
- function puts() is a library function that writes a specified string to stdout.
• Format:
int putchar(int arg)
int puts(const char *str)
- Arguments: arg is the character to be written.
arg is promoted to int (ASCII) and passed as argument.
str is character string passed as argument.
- Return value: On successful, non-negative value is returned. On error, returns EOF.
Module-1 10

• Example:
#include <stdio.h>
void main()
{
char str[50]= “RNSIT”;
puts(str);
}
Output:
RNSIT

Exampl2:
#include <stdio.h>
void main()
{
char ch;
printf(“Enter character”)
ch = getchar();
printf(“data read =”);
putchar(ch);
}
Output:
Enter character : R
Data read : R
Module-1 11

What are the types of operators used in C ?


Generally operators are classified as
1. Arithmetic operators.
Arithmetic operators Performs simple mathematical calculations.
Operators : +, -, *, /, %.
2. Relational operators.
Relational operators are used to compare arithmetic or character expressions.
Operators : <, >, <=, >=, = =, !=.
3. Logical operators.
Logical operators are used to compare logical or relational expressions.
Operators : &&, || , !.
4. Bitwise operators.
Bitwise operators operate on each bit of data.
Operators : &, |, <<, >>, ~.
5. Assignment operators.
Assignment operators Evaluates the Expression on the right side &
assigns the result to left side.
Operators: =, +=, -=, *=.
6. Increment and decrement operators.
This operator Increment or decrement the value by 1.
Operators: ++, --.
7. Conditional operators.
Conditional operator is also called as Ternary operator. It consists of
combination of two symbols as → (?) and ( : ).
8. Comma operators.
This is used to separate the expressions, constants, variables, etc.
Operator: ‘ , ’
9. Other operators.
Other Operators are:
sizeof() , . , -> , * , etc.
Module-1 12

What are the control statements used in c?


Control statements can be categorized as follows:
1. Decision making statement.
a. Simple if statement.
b. if - else statement.
c. switch statement.
d. Conditional operator.
e. go - to statement.
2. Loop constructs.
a. for loop construct.
b. while construct.
c. do – while construct.

1. Decision making with if statements.

1. a. Simple if statement.

Syntax:
if (test-condition)
{
statements;
}

Example on simple if statement: Find the bigger of two numbers.

main ( )
{
int a, b, big ;
printf (“Enter value for a & b : \n”) ;
scanf (“%d %d”, &a, &b) ;

if (a > b )
big = a ;

if (b > a )
big = b ;

printf (“Bigger value is : %d”, big) ;


}
Module-1 13

1. b. if - else statement.

Syntax:
if (test-condition)
{
Statements;
}
else / /if above condition is not true
{
Statements;
}

The condition following if is always enclosed within a pair of parenthesis.


• If the condition whatever it is, is true then the first parenthesis
statements gets executed.
• If the condition, is not true then the first parenthesis statements will not
be executed; instead the program skips towards to the else parenthesis
if it is written.

Flowchart:

False
Test

True
Body of if for true Body of else for false

Next statement
Module-1 14

Example on if-else statement:

Find the bigger of two numbers. (File name: ifelse.c)

main ( )
{
int a, b, big ;
printf (“Enter value for a & b : \n”) ;
scanf (“%d %d”, &a, &b) ;

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

printf (“Bigger value is : %d”, big) ;


getch ( ) ;
}

Find the number is odd or even. (File name: ifelse1.c)

main ( )
{
int n ;
printf (“Enter any number : \n”) ;
scanf (“%d ”, &n) ;

if ( n % 2 == 0 )
{
printf (“the number %d is even”, n) ;
}
else
{
printf (“the number %d is odd”, n) ;
}
getch ( ) ;
}

Ques : Do the same program using Bitwise and operator


Module-1 15

Example: write a menu driven to find (File name: ifMenu.c)


1. Addition.
2. Subtraction.
3. Multiplication
4. Division.

main ( )
{
int a, b, ch, result ;
printf (“Enter two values :”);
scanf (“%d %d”, &a, &b) ;

// Code to display menu


printf (“1. Addition. \n 2. Subtraction. \n”) ;
printf (“3. Multiplication. \n 4. Division. \n”) ;

// Code to Accept Choice.


printf (“Enter Your Choice :”) ;
scanf (“%d”, &ch) ;

// Code to take decision on Choice.


if (ch = = 1 )
result = a + b ;

if (ch = = 2 )
result = a - b ;

if (ch = = 3 )
result = a * b ;

if (ch = = 4 )
result = a / b ;

printf (“The result is : %d”, result) ;


}

Do the same program for (+, -, *, /) symbols as shown:


+. Addition.
-. Subtraction.
*. Multiplication
/. Division
Module-1 16

1. c. Switch statement.

“The control statement which allows us to make a decision from the number of choices at
once is called a switch statement.”

If the number of alternatives are too many then using if control statement increases
complexity and program becomes difficult to read and understand. C has a built in multi
way decision statement known as a switch.

The switch statement tests the value of a given variable (or expression) against the list of
case values, and when a match is found, a block of statements associated with that case is
executed.

Syntax:
switch ( expression )
{
case value-1: block ;
break ;
case value-2: block ;
break ;
… …
… …
… …
default: default block ;
break ;
}

• Note that case labels end with colon (:).

• The break statement at the end of each block signals the end of particular case, and
control exits from the switch statement.

• The default is an optional case. Default will be executed if the value of the expression
does not match with any of the case values.
Module-1 17

Example: write a menu driven to find


+. Addition. *. Multiplication
-. Subtraction. /. Division.
main ( )
{ int a, b, result ;
char ch ;
printf (“Enter two values :”);
scanf (“%d %d”, &a, &b) ;
// Code to display menu
printf (“+. Addition. \n -. Subtraction. \n”) ;
printf (“*. Multiplication. \n /. Division. \n”) ;
// Code to Accept Choice.
printf (“Enter Your Choice :”) ;
scanf (“%c”, &ch) ;
// Code to take decision on Choice.
switch ( ch )
{
case ‘+’ : result = a + b ; break ;
case ‘-’ : result = a - b ; break ;
case ‘*’ : result = a * b ; break ;
case ‘/’ : result = a / b ; break ;
}
printf (“The result is : %d”, result) ;
}

Example: Accept day number of a week and display the corresponding week day
main ( )
{ int N ;
printf (“Enter The Day number :”);
scanf (“%d ”, &N) ;
switch ( N )
{
case 1 : printf (“Sunday”) ; break ;
case 2 : printf (“Monday”) ; break ;
case 3 : printf (“Tuesday”) ; break ;
case 4 : printf (“Wednesday”) ; break ;
case 5 : printf (“Thursday”) ; break ;
case 6 : printf (“Friday”) ; break ;
case 7 : printf (“Saturday”) ; break ;
default : printf (“Invalid No”) ; break ;
}
}
Module-1 18

What is the difference between if – else and switch statement.

Sr.
switch if – else
No
Switch offers a better way of writing In very few situations we are
1. programs than if. It leads to more left with no choice but to use if
structured program.
Even if there are multiple statements Every if or else part has to be
to be executed in each case, there is included in braces if they
2.
no need to enclose them within a contain more than one
pair of braces { }. statement.
Switch will not work with logical Any logical operators can be
3. operators can not be used as case used as if-else conditions.
labels. e.g. case i <= 20 : e.g. if (i <=20)
The constants in the case statements The constants in the test
of switch can be either ‘char’ or condition of if-else statements
4.
‘int’ data type only. ‘float’ or can of any data type.
‘double’ doesn’t work.
No two case values may be the Even though two if conditions
5. same. can be same, logically we
should not use it.
Nested switch are very rarely used. Nested if-else are more used
6.
than nested switch.
Example: Example:
int N = 15 ; int N = 15 ;
switch ( N % 2 ) if ( N%2 = = 0)
7. { printf(“Even”);
case 0: printf(“Even”); break; else
case 1: printf(“Odd”); break; printf(“Odd”);
}
Module-1 19

1. d. Conditional Operator (Ternary Operator). [ ?: ]

Conditional operator can be used as an alternate for simple ‘if – else’


statement. This operator consists of two symbols as the question mark (?) and
a colon (:).

Syntax:
Result = ( exp1 ) ? exp2 : exp3 ;

If expression (exp1) is true, then (exp2) is evaluated otherwise (exp3) is


evaluated.

Consider the following example:

if (x > 0 )
flag = 0 ;
else
flag = 1 ;
This statement can be replaced by conditional operator as:

flag = ( x > 0 ) ? 0 : 1 ;

Example: find the output of the following

1. for x = 5 find→ a = ( (x > 0) && (x < 0) ) ? 2 : (x %2 ? x : 2) ;


2. for a = 5 , b = 5, c = 7 find→
num = (a = = b) ? (a > c ? 3 : 4) : (b > c ? 6 : 8);
3. for num = 10 find → k = (num > 5) ? (num <= 10 ? 10 :20) : 50 ;
4. int tag = 10, code = 1;
if (tag = 0)
code > 1 ? printf (“Correct”) : printf (“True”) ;
else
printf (“Sorry”);

5. for int x = 66 and y = 65 find →


a. printf ( “x > y ? %d : %c”, x);
b. printf ( “%d”, x < y ? x : y);
c. printf ( x = = y ? “%d” : “%c”, y);
Module-1 20

1. e. The go – to statement.

C supports the go to statement to branch unconditional from one point to another in the
program.

Syntax: Back word jump Syntax: For word jump

goto label ; label :


… … statements ;
… … … …
label : … …
statements ; goto label ;

The goto requires a label in order to identify the place where the branch is to be made. A label
is any valid variable name, which must be followed by a colon (:). The label is placed
immediately before the statement where the control is to be transferred.
Label can be any where in the program, either before or after the goto.

File Name: goto.c

/* Write a program to validate the age for learning license.


(consider age should be greater than 18 and les than 90) */

main ( )
{
int age ;

AGAIN :
printf ( “Enter Age :”) ;
scanf(“%d”, &age);

if ( (age < 18) || (age > 90) )


{
printf (“** Wrong Age Entered, Accept Again ** \n”) ;
goto AGAIN ;
}

printf (“You are qualified for learning License.”) ;


}
Module-1 21

Loop Constructs.

1. while loop.

The while loop is used to execute a statement (or block of statements) multiple times. It is the
simplest of all looping constructs.

Syntax: Flowchart:
while ( test-condition) False
{ Test Next statement
body of while-loop ;
} True
Body of while loop

The test-condition is evaluated first. If the condition is TRUE then only the body of loop is
executed. After the execution of body, the test-condition is once again evaluated and if it is
true, that body is executed once again. This process is repeated until the test-condition finally
becomes false and the control is transferred out of the loop.
The while loop is more powerful when ‘the number of times the loop is to be executed is not
known in advance’.

File Name: while1.c

/* Write a program to print sum of 1st 10 numbers . */

main ( )
{
int sum = 0, i ;
i = 1; /* Assignment */
while ( i <= 10 ) /* Condition */
{
sum += i ;
i ++ ; /* Increment */
}

printf (“The Sum is : %d ”, sum) ;


}
Module-1 22

File Name: while2.c


/* Display total of two numbers. Enter ‘y’ to continue. */

main ( )
{
int a, b, result ;
char ch = ‘y’ ; // initialization.

while ( ch = = ‘y’ )
{
printf ( “Enter Two Numbers \n”) ;
scanf(“%d %d”, &a, &b);

result = a + b ;
printf ( “Total of %d and %d is %d \n”, a, b, result) ;

printf ( “Do you want to continue :- ”) ;


fflush (stdin);
scanf (“%c”, &ch);
}

Why to use fflush(stdin) :

Buffer is a temporary memory. When a c program begins execution the following data streams
will automatically opened.
1. stdin: standard input device (opened for input).
2. stdout: standard output device(opened for output).

Both the streams are termed as buffers. The output of the function like printf goes to stdout.
Input through keyboard will be buffered in stdin, which will be read by functions like scanf,
getch, gets etc.
In the above example for statement: scanf(“%d %d”, &a, &b); we have to input two integer
values and then we have to press enter key(Return key). Here in tern we are entering a new line
i.e. ‘\n’ character by pressing a enter key in following order.
12 6 ‘\n’
scanf will scan 12 into ‘a’ variable and 6 into ‘b’ variable. Whereas ‘\n’ character still remains
in the input buffer. Next statement scanf (“%c”, &ch); will scan that ‘\n’ character instead of
scanning entered character. Hence to clear the input buffer from such a characters before
scanning fflush function is used in the above example. fflush clears the buffer.
Module-1 23

2. do - while loop.

The Statements within do - while loop will be executed at least once. The do–
while loop is called as bottom tested loop.

Syntax: Flowchart:
do
{
body of do-loop ; Body of do-while
}
while ( test-condition); False
True Test Next statement

File Name: dowhile.c


/* Display total of two numbers. Enter ‘y’ to continue. */

main ( )
{
int a, b, result ;
char ch ; // No need of initialization.

do
{
printf ( “Enter Two Numbers ”) ;
scanf(“%d %d”, &a, &b);

result = a + b ;
printf ( “Total of %d and %d is %d \n”, a, b, result) ;

printf ( “Do you want to continue :- ”) ;


flushall();
scanf(“%c”, &ch);
}
while ( ch = = ‘y’ );
}
Module-1 24

What is the difference between while and do-while loop.

Sr.
while loop. do – while loop.
No
while loop is ‘Top tested’ loop. do - while loop is ‘Bottom tested’
1.
loop.
If the test condition is false at the Even if the condition is false at the
2. first test, then body of while loop first test, body of do-while
never executes. executes at least once.
This loop is also termed as This loop is also termed as
3.
“Entry controlled” loop. “Exit controlled” loop.
Syntax: Syntax:
while (condition) do
{ {
4.
body of while; body of while;
} }
while (condition);
No semicolon after while Semicolon should be given at the
5.
condition. end of do-while condition.
Flowchart: Flowchart:

False
Test Next statement Body of do-while
6.
True False
True Test
Body of while loop Next statement

Example: Example:

a=1; a=1;
While (a <= 10) do
{ {
7.
sum += a; sum += a;
a ++ ; a ++ ;
} }
While (a < 10);
Module-1 25

3. for loop.

When we in advance exactly how many times we want to execute the statements in a loop, in
such case, the for loop can be used.
Syntax:
for ( loop initialization ; test-condition ; increment )
{
body of loop;
}

The for loop has three parts:


1. Loop Initialization:
Initialization of control variables is done first, using assignment statements such as i = 1,
count = 0.
Variables i, count are said loop control variables.
2. Test-condition :
Test condition consists of a test expression which will decide whether the loop has to
execute or not by returning true or false.
Basically test-condition are represented by the relation operators as <, >, <=, >=, !=, etc.
3. Increment :
When the body of loop is executed, the control is transferred back to the last statement in
the loop. In last part basically control variables are incremented using assignment operators
as i = i + 1, i ++ , count -- etc.
After the last statements are evaluated, the control is transferred back to for loop to check
the test condition.

Tell whether following loops are valid or invalid:


• for ( ; ; )
• for ( a = 0, b = a ; ; a + b)
• for ( count = 0 ; count < 10 ; count ++ )
• for ( count ; 1 ; a )
• for ( a = 0 ; a < 10)
• for ( a = 0 ; b = a ; ; a + b)
• for ( count = 0 , count < 10 , count ++ )
Module-1 26

• Write a program to find the factorial of N.

File Name: fact.c


/* program to find the factorial */

main ( )
{
int N, i, fact = 1 ;

printf ( “Enter value to get factorial :”) ;


scanf (“%d”, &N);

for ( i = N ; i > 0 ; i - -)
fact = fact * i ;

printf (“Factorial = %d”, fact);


}

• Write a program to find the number is prime or not.


File Name: prime.c

/* program to find the Prime number */

main ( )
{
int N, i ;

printf ( “Enter value to find it is prime or not :”) ;


scanf (“%d”, &N);

for ( i = 2 ; i <= N ; i++)


{
if ( N % i = = 0)
{
printf (“%d is Not Prime”, N); getch();
exit (0);
}
}
printf (“%d is Prime number ”, N);
}
Module-1 27

What is the difference purpose of break, continue and exit.?


Differentiate between them.

1. break statement:
The break statement terminates the execution of the loop and the control is transferred
to the statement immediately following the loop.

2. continue statement:
A continue statement does not terminate the loop but skips the remaining statements of
that loop and control transfers at the beginning.

3. exit statement:
A exit( ) function terminates the process. Program suddenly stops the execution as soon
as it encounters exit.

/* Program to illustrate the break, continue and exit.*/


void main()
{
for( i = 0 ; i < 5 ; i ++)
{
if ( i = = 3)
break;

printf(“%d \t”, i);


continue;
printf(“After Continue\n”);
}
printf(“\n Before Exit \n”);
exit (0);
printf(“\n After Exit \n”);
}

Output:
012
Before Exit

In above example The statement continue will skip the statement printf (“After Continue\n”)
and transfers the control back to the condition statement. As if condition satisfies for i = 3 the
statement break terminates the loop by transferring the control to the next statement followed
by loop. Control will never reach the last statement printf (“After Exit\n”) as the exit
statement will terminate the program.
Module-1 28

What is nested for loop?


Writing one for loop within another loop is called as nested loops.
The inner loop is completely repeated for each repetition of the out side loop.

For example : OutPut :

for( I = 0 ; I < 3 ; I++ ) 000


{ 111
for( J = 0 ; J < 3 ; J++ ) 222
{
printf(“%d ”, i );
}
printf (“\n”);
}

Write a program to output the following pyramid:


1 1 *
22 12 **
333 123 ***
4444 1234 ****
55555 12345 *****

main () main () main ()


{ int i, J; { int i, J; { int i, J;
for( i = 1 ; i < 5 ; i ++ ) for( i = 1 ; i < 5 ; i ++ ) for( i = 1 ; i < 5 ; i ++ )
{ { {
for(J = 1; J <= i ;J ++) for(J = 1; J <= i ;J ++) for(J = 1; J <= i ;J ++)
{ { {
printf(“%d ”, i ); printf(“%d ”, J ); printf( “*” );
} } }
printf(“\n” ); printf(“\n” ); printf(“\n” );
} } }
} } }

What is the difference between = and == symbols?


‘=’ is a assignment operator which is used to assign the values to the variables.
‘= =’ is a Relational operator which is used to compare two values for equality.
Consider a example: Consider a example:
int x = 5 ; int x = 5 ;
if (x = 6 ) if (x = = 6 )
printf(“TRUE”); printf(“TRUE”);
else else
printf(“FALSE”); printf(“FALSE”);

The above example will output always: TRUE even the initial value of x is 5. The reason is we
are not comparing x with 6, In fact assigns the value 6 to variable x in if condition which
executes successfully. If statement in if executes successfully, compiler return 1 which makes
the condition true. In other case output is FALSE.
Module-1 29

Array

• Types of array:
1. One dimensional (1D)
2. Two dimensional (2D)
3. Multi dimensional (nD)

1.1. One dimensional Array (1-D array)

Define array/ what is n array? --2 marks

• Definition:
- It is collection of similar data type elements. All Elements of array are stored in
contiguous memory locations.
• Syntax:

data-type name[size];

Where, data-type: tells kind of values it can store ( like int , char , float etc..), name: to
identify the array and size :indicate maximum number of values the array can hold

• Example:
int num[3];

• Memory representation:

Num 0 1 2  index
Foo ? ? ?
Base f00 f02 f04  address
pointer
Module-1 30

Explain initialization of 1-D array with example? --4 marks

• Array initialization

o Full initialization

int num[3] = {10, 20, 30}; /* with size */


int num[] = {10, 20, 30}; /* without size */

Array after initialization

Num 0 1 2  index
Foo 10 20 30
f00 f02 f04  address

o Partial initialization

int num[5] = {10, 20, 30}; /* with size */

Array after initialization: remaining elements are filled with zeros

Num 0 1 2 3 4
Foo 10 20 30 0 0
f00 f02 f04 f06 f08
• Reading and displaying Array values from user
void main()
{
int num[3] = {10, 20, 30}; /* Initialized array */
printf (“Displaying array :”); /* displaying Array */
for(i=0;i<3;i++)
printf(“%d”,num[i]);
}

• Reading and displaying Array values from user

void main()
{
int num[3];
printf (“Enter nos to array :”); /* reading Array */
for(i=0;i<3;i++)
scanf(“%d”,&num[i]);
printf (“Displaying array :”); /* displaying Array */
for(i=0;i<3;i++)
printf(“%d”,num[i]);
}
Module-1 31

1.2. Two dimensional Array (2-D array)


A two-dimensional array is used when you want to put values in a table format. A two-
dimensional array is really nothing more than an array of arrays. The most natural way
to store 2D Array would be to index locations by the row and column.
• Syntax:
data-type name[row][col];

Where,
data type: what kind of values it can store Ex: int , char , float etc..
Name: to identify the array
row: the maximum number of rows the array can hold
col: the maximum number of columns the array can hold

• Example:
int Num[3][3];

• 2-D Array initialization

int num[3][3] = { {10, 20, 30};


{4, 5, 6};
{50, 60, 70};
};

• Memory representation after initialization:

Num 0 1 2
. Num[0] . 0 10 20 30
Num[1] . 1 4 5 6
Num[2] . 2 50 60 70

• Reading and displaying Array values from user

void main()
{
int num[3][];
printf (“Enter 3x3 matrix :”); /* reading Array */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&num[i][j]);
printf (“Displaying array Matrix:”); /* displaying Array */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”, num[i][j]);
}
Module-1 32

• Passing Array to a function


- Arrays are always passed as call by reference.
- Whatever changes are made to the array in the function are reflected back in main.
• Example.

void display(char *); /* continued */


void main()
{ void change(char *arr)
int num[]= {10, 20, 30}; {
change(num); *(arr + 1) = 0
for(int i=0; i<3; i++) }
printf(“%d”, num[i]);
}
Output: 10 0 30 /* affects the array elements */

• Operations that can be performed on arrays

1. Traversal: acessing every element of array


2. Insertion : inserting a new element
3. Deletion: deleting existing element
4. Merging: merge 2 arrays
5. Search : search for a value in an array
6. Sorting : arrange the values in array in either ascending or descending order.
Module-1 33

Write a program to Search an element in an array using


a. Linear Search
b. binary search

void linearSearch(); /*Function Prototype*/


void binarySearch();
void main()
{
int choice;
while(1){
printf("\n\n--------Menu-----------\n");
printf("1. Linear Search\n");
printf("2. Binary Search\n");
printf("3. Exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d", &choice);
switch(choice)
{
case 1: linearSearch ( );
break;

case 2: binarySearch();
break;
case 3: exit(0);
break;
default: printf("\nInvalid choice:\n");
} /* end of switch */
}
}
void linearSearch ()
{ int a[10], size, key, i;
printf("Enter size :");
scanf("%d", &size);
printf("Enter Array Elements :");
for(i=0; i< size; i++)
scanf("%d", &a[i]);
printf ("Enter the search element : ");
scanf ("%d", &key);
for( i=0; i<size; i++)
{
if ( key == a[i] )
{
printf("Element found at position 5d", i+1); return;
}
}
printf ("\n..Element not found..\n"); getch();
}
Module-1 34

void binarySearch ( )
{
int a[10], size, mid, key, i, low, high;
printf("Enter size :");
scanf("%d", &size);
printf("Enter Array Elements :");
for(i=0; i< size; i++)
scanf("%d", &a[i]);
printf ("Enter the search element : ");
scanf ("%d", &key);
low = 0; high = size;
while (low < high)
{ mid = (low + high) / 2;
if ( key == a[mid] )
{
printf("Element found at position : %d", mid+1); return;
}
if( key < a[mid] )
high = mid-1;
else
low= mid+1;
}
printf("\n Element Not found .. \n");
}

/* Programs for practice */


1. C Program to Calculate Area and Circumference of Circle
2. Find greatest in 3 numbers
3. Check Whether Number is Perfect Or Not
4. C Program to Check Whether a Character is an Alphabet or not
5. C Program to Calculate the Sum of Natural Numbers
6. C Program to Find Factorial of a Number
7. Program to Generate Multiplication Table
8. C Program to Display Fibonacci Sequence
9. C Program to Find GCD of two Numbers
10. C Program to Find LCM of two Numbers
11. C Program to Display ASCII code of Character from A to Z Using Loop
12. C Program to Count Number of Digits of an Integer
13. C Program to Reverse a Number
14. C Program to Calculate the Power of a Number
15. C Program to Check Whether a Number is Palindrome or Not
16. C Program to Check Whether a Number is Prime or Not
17. C Program to Display Prime Numbers Between Two Intervals
18. C Program to Check Armstrong Number
19. C Program to Display Factors of a Number
20. C program to Find all Roots of a Quadratic equation
Module-1 35

21. C Program to Check Whether a Character is Vowel or Consonant


22. C Program to Check Leap Year
23. C Program to Check Whether a Character is an Alphabet or not
24. C Program to Calculate the Power of a Number
25. C Program to Convert Binary Number to Decimal and vice-versa
26. C Program to Convert Octal Number to Decimal and vice-versa
27. C Program to Convert Binary Number to Octal and vice-versa

Using Array do the following


28. Write function getMax() that return the Largest Element of an Array, Array and size is input to
function
29. Function addMatrix() to Add Two Matrix Using Two-dimensional Arrays
30. Function multiplyMatrix() to Multiply to Matrix Using Two-dimensional Arrays
31. C program to Find Transpose of a Matrix
32. C program to display the mean and mode of an array
33. Function getMode() that returns the mode of an array.

You might also like