Unit-II PPS
Unit-II PPS
Unit-II PPS
Unit-2: Conditional Control -Statements :Simple if, if...else - Conditional Statements: else if
and nested if - Conditional Statements: Switch case - Un-conditional Control Statements:
break, continue, goto - Looping Control Statements:for, while, do..while - Looping Control
Statements: nested for, nested while - Introduction to Arrays -One Dimensional (1D) Array
Declaration and initialization - Accessing, Indexing and operations with 1D Arrays - Array
Programs - 1D - Initializing and Accessing 2D Array, Array Programs -2D-Pointer and address-
of operators -Pointer Declaration and dereferencing, Void Pointers, Null pointers Pointer based
Array manipulation
CONTROL STATEMENTS
Control Structures or control statements specifies the logical flow of control in programs. Types
of control statements are:
• Sequence Statements
• Selection or Conditional or Decision-Making Statements
o if, if-else, if-else if-else, switch-case
• Iteration or Repetitive or Looping Statements
o for loop, while loop, do-while loop
• Unconditional Control Statements
o break, continue, goto
Sequence control structure refers to the sequential (line-by-line) execution of statements, in the
same order in which they appear in the program.
• Simple if
• if … else
• else if
• nested if
• switch case
The if Statement
/* Absolute Number*/
#include <stdio.h>
int main() {
int number;
printf("Enter the number:");
scanf("%d",&number);
if(number < 0)
{
number = -number;
}
printf("\nAbsolute value is %d",number);
return 0;
}
Output:
Enter the number:-75
Absolute value is 75
if (expression)
program statement 1
else
program statement 2
The if-else is actually just an extension of the general format of the if statement. If the result of
the evaluation of expression is TRUE, program statement 1, which immediately follows, is
executed; otherwise, program statement 2 is executed. In either case, either program statement
1 or program statement 2 is executed, but not both.
// Program to determine if a number is even or odd
#include <stdio.h>
int main ()
{
int number_to_test, remainder;
printf ("Enter your number to be tested: ");
scanf ("%d", &number_to_test);
remainder = number_to_test % 2;
if (remainder == 0)
printf ("The number is even.\n");
else
printf ("The number is odd.\n");
return 0;
}
Nested if Statements
The else if offers the most efficient implementation for processing mutually exclusive clauses.
When one clause evaluates to TRUE, all subsequent clauses are ignored.
if (expression 1)
program statement 1
else if (expression 2)
program statement 2
…
else if (expression n)
program statement n
else
default program statement
int main ()
{
int marks;
printf("Enter your marks between 0-100\n");
scanf("%d", &marks);
/* Using if else ladder statement to print Grade of a Student */
if(marks >= 90){
/* Marks between 90-100 */
printf("YOUR GRADE : A\n");
} else if (marks >= 70){
/* Marks between 70-89 */
printf("YOUR GRADE : B\n");
switch (expression)
{
case value1:
program statements
...
break;
case value2:
program statements
...
break;
...
case valuen:
program statements
...
break;
default:
program statements...
break;
}
• The expression enclosed within parentheses is successively compared against the values
value1, value2, ..., valuen, which must be simple constants or constant expressions. It
must be an integer or character.
• If a case is found whose value is equal to the value of expression, the program
statements that follow the case are executed. Note that when more than one such
program statement is included, they do not have to be enclosed within braces.
• The break statement signals the end of a particular case and causes execution of the
switch statement to be terminated. Remember to include the break statement at the end
of every case. Forgetting to do so for a particular case causes program execution to
continue into the next case whenever that case gets executed.
• The special optional case called default is executed if the value of expression does not
match any of the case values.
else if switch
Both are used for selecting or deciding among mutually exclusive options.
It tests expressions based on range of values It tests expressions which have discrete
or conditions. integer or character constant values.
It is more suitable when number of options It is more suitable when number of options
are less. are more.
Looping Statements
The looping statements enable you to develop concise programs containing repetitive processes
that could otherwise require thousands or even millions of program statements to perform. The
C programming language contains three different program statements for program looping.
They are known as the for statement, the while statement, and the do while statement.
int main() {
while (expression)
program statement
The expression specified inside the parentheses is evaluated. If the result of the expression
evaluation is TRUE, the program statement that immediately follows is executed. After
execution of this statement (or statements if enclosed in braces), the expression is once again
evaluated. If the result of the evaluation is TRUE, the program statement is once again
executed. This process continues until the expression finally evaluates as FALSE, at which
point the loop is terminated. Execution of the program then continues with the statement that
follows the program statement.
scanf("%d",&num);
number = num;
while(number > 0) {
remainder = number % 10;
reverseOfNumber = reverseOfNumber*10 + remainder;
number = number/10;
}
if(num == reverseOfNumber)
printf("The given number %d is a palindrome",num);
else
printf("The given number %d is not a palindrome",num);
return 0;
}
When developing programs, it sometimes becomes desirable to have the test made at the end
of the loop rather than at the beginning. Naturally, the C language provides a special language
construct to handle such a situation. This looping statement is known as the do statement. The
syntax of this statement is as follows:
do {
program statements
} while (loop_expression);
Execution of the do statement proceeds as follows: the program statement is executed first.
Next, the loop_expression inside the parentheses is evaluated. If the result of evaluating the
loop_expression is TRUE, the loop continues and the program statement is once again
executed. As long as evaluation of the loop_expression continues to be TRUE, the program
statement is repeatedly executed. When evaluation of the expression proves FALSE, the loop
is terminated, and the next statement in the program is executed in the normal sequential
manner.
The do statement is simply a transposition of the while statement, with the looping conditions
placed at the end of the loop rather than at the beginning.
Remember that, unlike the for and while loops, the do statement guarantees that the body of
the loop is executed at least once.
/*Summation of 12+32+52+…+n2* using Do-While*/
#include<stdio.h>
int main()
{
int i=1,sum=0,n;
printf("\nEnter the value of n:");
scanf("%d",&n);
do
{
sum=sum+(i*i);
i+=2;
}
while(i<=n);
printf("Sum of the series=%d\n",sum);
return(0);
}
Note:
• Avoid do…while and prefer while or for statements for looping capabilities. The
do…while construct is avoided due to readability issues and to prevent errors.
• But there are cases when it is useful. For example, let’s say you want to write a loop
where you are prompting the user for input and depending on input execute some code.
You would want this to execute at least once and then ask the user whether he wants
continue. In such cases, do…while loop results in lesser and cleaner code compared to
a while loop.
A break statement causes the innermost enclosing loop or switch to be exited immediately. It
skips whatever follows it in the loop body. breaks can be useful because they are sometimes
the simplest and best way to end a loop. But you might want to avoid using too many, because
they can also make the code a little harder to read.
/*Example: Print from 0 to 5 using break*/
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 6) {
break;
}
printf("%d\n", i);
}
return 0;
}
The continue statement causes the next iteration of the enclosing for, while, or do loop to begin.
The continue statement in while and do loops takes the control to the loop's test-condition
immediately, whereas in the for loop it takes the control to the increment step of the loop. The
continue statement applies only to loops, not to switch.
/* Sum of all numbers except numbers divisible by 5 till 20*/
#include <stdio.h>
int main()
{
int i, sum = 0;
for (i = 1; i <= 20; i++)
{
if (i % 5 == 0)
continue;
sum += i;
}
printf("Sum = %d", sum);
}
A goto statement provides an unconditional jump from the goto to a labeled statement in the
same function.
goto label;
.. .
label: statement;
Note: The 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.
ARRAYS
An array is a collection of data items, all of the same type, accessed using a common name. 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, though specific implementations may.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
❖ Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows:
❖ Initializing Arrays
One can assign initial values to the elements of an array. Values in the list are separated by
commas and the entire list is enclosed in a pair of braces. The statement
int integers[5] = { 0, 1, 2, 3, 4 };
sets the value of integers[0] to 0, integers[1] to 1, integers[2] to 2, and so on.
It is not necessary to completely initialize an entire array. If fewer initial values are specified,
only an equal number of elements are initialized. The remaining values in the array are set to
zero. So the declaration
float sample_data[500] = { 100.0, 300.0, 500.5 };
initializes the first three values of sample_data to 100.0, 300.0, and 500.5, and sets the
remaining 497 elements to zero.
• By enclosing an element number in a pair of brackets, specific array elements can be
initialized in any order. For example,
float sample_data[500] = { [2] = 500.5, [1] = 300.0, [0] = 100.0 };
initializes the sample_data array to the same values as shown in the previous example.
int main(){
int a[10] = {47, 22, 19, 29, 85, 72, 56, 67, 32, 25};
int sum, i;
for(i=0; i<10; i++) {
sum = sum + a[i];
}
printf(“Sum = %d”, sum);
}
❖ Multidimensional Arrays
• Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets
after the variable name in the declaration statement.
• One dimensional arrays do not require the dimension to be given if the array is to be
completely initialized. By analogy, multi-dimensional arrays do not require the
first dimension to be given if the array is to be completely initialized. All dimensions after
the first must be given in any case.
• For two dimensional arrays, the first dimension is commonly considered to be the number
of rows, and the second dimension the number of columns.
/*MATRIX MULTIPLICATION*/
#include <stdio.h>
int main()
{
int a[10][10],b[10][10],result[10][10];
int i,j,k,row1,col1,row2,col2,sum;
printf("\nEnter the size of the row and column of Matrix 1:\n");
scanf("%d%d",&row1,&col1);
if(col1 != row2) {
printf("Matrices with entered orders can't be multiplied
with each other.\n");
return 0;
}
}
}
printf("\n\tRESULT MATRIX\n");
for(i=0;i<row1;i++,printf("\n"))
for(j=0;j<col2;j++)
printf("%d\t",result[i][j]);
return(0);
}
POINTERS
❖ Example:
int a = 108;
int *ptr = &a; //Pointer Declaration
a ptr
108 6400
6400 5400
Examples:
int a[10] = {11,22,33,44,55,66,77,88,99,110};
int *ptr = &a[3]; //6006
ptr++; //6008 or &a[4]
❖ Null Pointer
A pointer can be assigned the value 0 to explicitly represent that it does not currently have
a pointee. Having a standard representation for "no current pointee" turns out to be very
handy when using pointers. The constant NULL is defined to be 0 and is typically used
when setting a pointer to NULL. Since it is just 0, a NULL pointer will behave like a
boolean false when used in a boolean context. Dereferencing a NULL pointer is an error
which, if you are lucky, the computer will detect at runtime -- whether the computer detects
this depends on the operating system.
Syntax
int *ptr = NULL;
int *ptr = 0
❖ Void Pointer
A void pointer is a pointer that has no associated data type with it. A void pointer can hold
an address of any type and can be typecasted to any type.
int a = 10;
char b = 'x';
• Advantage of void pointers: malloc() and calloc() return void * type and this allows
these functions to be used to allocate memory of any data type (just because of void *).
int main(void)
{
// Note that malloc() returns void * which can be
// typecasted to any type like int *, char *, ..
int *x = malloc(sizeof(int) * n);
}
• void pointers cannot be dereferenced. For example, the following program doesn’t
compile.
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
return 0;
}
Output:
Compiler Error: 'void*' is not a pointer-to-object type
Output:
10