Thanks to visit codestin.com
Credit goes to www.scribd.com

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

CPP Unit 2 N 3 Bcom

This document summarizes formatted and unformatted input/output functions in C, as well as control statements including decision statements (if, switch) and loops (while, for). Formatted functions like scanf and printf allow input/output with format specifiers, while unformatted functions handle single inputs/outputs. Control statements determine program flow. Decision statements like if/else and switch evaluate conditions to execute certain code blocks. Loops like while and for repeat code execution.

Uploaded by

Srinivas Boini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views35 pages

CPP Unit 2 N 3 Bcom

This document summarizes formatted and unformatted input/output functions in C, as well as control statements including decision statements (if, switch) and loops (while, for). Formatted functions like scanf and printf allow input/output with format specifiers, while unformatted functions handle single inputs/outputs. Control statements determine program flow. Decision statements like if/else and switch evaluate conditions to execute certain code blocks. Loops like while and for repeat code execution.

Uploaded by

Srinivas Boini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

2.1.

1 Formatted input/output functions

Formatted console input/output functions are used to take one or more inputs from the user at
console and it also allows us to display one or multiple values in the output to the user at the
console.

Functions Description

This function is used to read one or multiple inputs


scanf()
from the user at the console.

This function is used to display one or


printf() multiple values in the output to the user at the
console.

This function is used to read the characters from a


sscanf()
string and stores them in variables.

This function is used to read the values stored in


sprintf()
different variables and store these values in a
character array.

Why these functions are called  formatted  console input/output functions?

While calling any of the formatted console input/output functions, we must use a


specific format specifiers in them, which allow us to read or display any value of a specific
primitive data type. Let's see what are these format specifiers.

a) %d for integer (decimal) b) %c for character


C) %f for floating point d) %s for string

2.1.2Unformatted input/output functions


Unformatted console input/output functions are used to read a single input from the user at
console and it also allows us to display the value in the output to the user at the console.

Some of the most important formatted console input/output functions are -


Functions Description

Reads a single character from the user at the


getch()
console, without echoing it.

Reads a single character from the user at the


getche()
console, and echoing it.

Reads a single character from the user at the


getchar() console, and echoing it, but needs an Enter key to be
pressed at the end.

Reads a single string entered by the user at the


gets()
console.

puts() Displays a single string's value at the console.

putch() Displays a single character value at the console.

putchar()
Displays a single character value at the console.

2.2 Control statemetns in C language


Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to
perform tasks repeatedly or to jump from one section of code to another.

Below figure 2 shows types of control statements in C:


figure 2 control statements in c

2.2.1. DECISION STATEMENTS / SELECTION STATEMENTS:


Decision making statements are the statements that are used to verify a given condition and
decides whether a block of statements gets executed or not based on the condition result.

In c programming language, there are two decision making statements they are as follows...

1. if statement
2. switch statement

2.2.2 if statement in c:In c, if statement is used to make decisions based on a condition.


The if statement verifies the given condition and decides whether a block of statements
are executed or not based on the condition result. In c, if statement is classified into four
types as follows...

1. Simple if statement 3. Nested if statement


2. if - else statement 4. if-else-if statement (if-else ladder)

Simple if statement

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

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

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

if ( n> 0 ) }
printf("Given number is natural number
") ; O/P: Enter any integer number: 4
getch(); Given number is natural number

if - else statement

The if - else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and execution
flow of the if-else statement is as follows...
The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).

Example Program | Test whether given number is even or odd.

#include <stdio.h>
#include<conio.h>
void main(){
int year ;
clrscr() ;
printf("Enter year: ") ;
scanf("%d", &year) ;
if ( year%4 == 0 ) }
printf("Given year is leap year\n") ; Output :
else
printf("Given year is not leap year\n") ; Enter year: 2017
Given year is not leap year

Nested if statement

Writing a if statement inside another if statement is called nested if statement. The general
syntax of the nested if statement is as follows..
Like the name indicate, nested else if contains if statement inside an if statement. If we want to
check a condition even a condition is hold, then we use nested if.

Let us see with an example:

  
#include <stdio.h>       }
#include <stdlib.h> }
int main()
{ Output :
     int n1 = 30,n2 = 20 ,n3 = 10;       
     if(n1 > n2) Largest is 30
     { Here n1(30) is greater than n2(20), so again
       if(n1>n3) check with the value of n3(10). Then
         { decided a decision( printf("Largest is
           printf("Largest is %d",n1); %d",n1); )
         }

if - else - if statement (if-else ladder)

Writing a if statement inside else of a if statement is called if - else - if statement. The general
syntax of the if-else-if statement is as follows...
Example Program | Find the largest of three numbers.

#include <stdio.h>
#include<conio.h>
void main() {
int a, b, c ; clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>b && a>c)
printf("%d is the largest number", a) ;
else if (b>a && b>c)
printf("%d is the largest number", b) ; Output :
else if(c>a && c>b)
printf("%d is the largest number", c) ; Enter any three integer numbers: 55 60 20
} 60 is the largest number

2.2.3 Switch statement in C

Using switch statement, one can select only one option from more number of options very
easily. In switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches with the value associated with an option,
the execution starts from that option. In switch statement every option is defined as a case.

The switch statement contains one or more number of cases and each case has a value
associated with it. At first switch statement compares the first case value with the switchValue,
if it gets matched the execution starts from the first case. If it doesn't match the switch statement
compares the second case value with the switchValue and if it is matched the execution starts
from the second case. This process continues until it finds a match. If no case value matches
with the switchValue specified in the switch statement, then a special case called default is
executed.

When a case value matches with the switchValue, the execution starts from that particular case.
This execution flow continues with next case statements also. To avoid this, we use "break"
statement at the end of each case. That means the break statement is used to terminate the
switch statement. However it is optional.

syntax break;
case 3:
Switch(expression) block 3;
{ break;
case 1: ……………………
block 1; ……………………
break; default:
case 2: }
block 2; Switch program example :
#include<stdio.h> #include <conio.h> case 2: printf("Two");
int main() { break;
int nmbr; case 3: printf("Three");
printf("Enter a number: "); break;
scanf("%d",&nmbr) ; default: printf("Number is not 1,2 or
switch(nmbr) 3");
{ }
case 1: printf("One"); getch(); }
break;

2.3 Looping Statements/ Repetition statements / Loops

Loops provide a way to repeat a set of statements and control how many times they are
repeated.
C supports three looping statements.

They are while, do-while and for.

Both while and for statements are called as entry-controlled loops because they evaluate the
expression and based on the value of the expression they transfer the control of the program
to a particular set of statements.

Do-while is an example of exit-controlled loop as the body of the loop will be executed once
and then the expression is evaluated.

Loops are used to repeat a block of code.


.
2.3.1 While loop:
This is an entry controlled looping statement. It is used to repeat a block of statements until the
expression / condition becomes satisfied. Also called as Pre test loop.
Syntax: while ( x <= 10 )
{
while(expression/condition)
{
statements;
increment/decrement;
}
While Loop example program:
#include <stdio.h>
void main()
{
int x = 0; printf( "%d\n", x );
x++;
} }
getch(); o/p: 0 1 2 3 4 5 6 7 8 9 10

2.3.2 for loop:

 This is an entry controlled looping statement.


 In this loop structure, more than one variable can be initialized.
 One of the most important features of this loop is that the three actions can be taken at a
time like variable initialization, condition checking and increment/decrement.
 The for loop can be more concise and flexible than that of while and do-while loops.
 Syntax:
for(initialization; test-condition; increment/decrement)
{
statements;
}

In above syntax, the condition is checked first. If it is true, then the program control flow goes
inside the loop and executes the block of statements associated with it. At the end of loop
increment or decrement is done to change in variable value. This process continues until test
condition satisfies
For loop example program:
#include <stdio.h>
Void main()
{
int x;
for ( x = 0; x < =10; x++ )
{
printf( "%d\n", x );
}
getch();
}
o/p: 0 1 2 3 4 5 6 7 8 9 10

2.3.4 Do-While loop:


 This is an exit controlled looping statement. Also called as Pre test loop
 Sometimes, there is need to execute a block of statements first then to check condition.
At that time such type of a loop is used. In this, block of statements are executed first and
then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
} while (expression/condition);

 In above syntax, the first the block of statements are executed.


 At the end of loop, while statement is executed. If the expression is evaluated to nonzero
value then program control goes to evaluate the body of a loop once again.
 This process continues till expression evaluates to a zero. When it evaluates to zero, then
the loop terminates.

Do while example program:


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

2.4 Break and continue statements:


BREAK statement is used to terminate any type of loop such as while loop, do while loop and
for loop. C break statement terminates the loop body immediately and passes control to the next
statement after the loop.

Break program example:


#include<stdio.h>
#include<conio.h>
void main() {
int i;clrscr();
for(i=1; i<=100; i++)
{
printf("%d\t,i");
if(i==5) getch();
break; }
} o/p: 1 2 3 4 5
CONTINUE
continue is a keyword . the continue statement is used to skip over the rest of the current
iteration. After continue statement, the control returns to the top of the loop.

#include<stdio.h> #include<conio.h>
void main() {
int i; clrscr();
for(i=1; i<=10; i++)
{
if(i==5)
continue;
printf("%d",i);
}
getch();
}
o/p: 1 2 3 4 6 7 8 9 10
Example program for Continue :
2.5 Goto statement:
A goto statement is used to branch (transfer control) to another location in a program.

Syntax:

The label can be any valid identifier name and it should be included in the program followed by
a colon.
Example program
Output :
Hello World
Hope you are fine

Note : Break, continue ad goto statements are also called as jumping statements.

2.6 Nesting of Loops

A loop inside another loop is called nesting of loops. There can be any number of
loops inside one another with any of the three combinations depending on the
complexity of the given problem. Let us have a look at the different combinations.

Syntax
outer_loop
{
inner_loop
{
// Inner loop statement/s
}

// Outer loop statement/s


}

Nested for loop
for(initialization; condition; update)
{
// statements
for(initialization; condition; update)
{
// Inner loop statements
}
// statements
}
Nested while loop Nested do...while loop
while(condition) do
{ {
// statements // statements
while(condition) do
{ {
// Inner loop statements // Inner loop statements
} }
while(condition);
// statements
} // statements
}

Example: Print number 1 to 10, 5 times

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

C code

#include <stdio.h>
int main()
{
int i; //for outer loop counter
int j; //for inner loop counter

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


{
for( j=1; j<=10; j++)
{
printf("%d ",j);
}
printf("\n");
}
}
Points to remember for nested loops:

1. Till the inner loop condition fails the control iterates inside the inner loop, when inner
loop condition fails the control moves to the outer loop
2. When ever the control is moving from outer loop to inner loop the value

2.7.1 FUNCTIONS

Functions

Function means, a large program can be divided into a series of individual related
programs called modules. These modules are called functions.
function is set of program to perform some specific and well defined tasks.

2.7.2 Advantages of User Defined Functions :

a) Reusability: The function writes once and use many times is called Reusability.
b) Modular Program Approach: A large program is divided into smaller sub programs. so
that each sub program performs a specific task. This approach makes the program
development more manageable.
c) Efficiency: means by avoiding redundant instructions the size of program can be
reduced. Which increase efficiency of program.
d) Function sharing: A function can be shared by many programmers.
e) It is very easy to identify the logical errors and correct.
f) It is very easy to read and understand.

2.7.3 The functions can be classified into two categories. Or types of functions

1 : Built in Functions (OR) Library Functions or Predefined functions


2 : User-defined Functions.

1 : Built-in Functions (OR) Library Functions : The standard C library is a collection of


various types of functions which perform some standared and predefined tasks. These function
which part of the C compiler that have been written for general purpose are called library
functions. They are also called built-in functions.
Examples :
1 : The function sqrt() is used for to find square root of a given number.
2 : The function scanf() is used to read data from the keyboard.
3 : The function printf() is used to print the result on the display.

Advantages :
1 : The programmer’s job is made easier because the functions are already available.
2 : The library functions can be used whenever required.

Disadvantages : The standared library functions are limited, programmes can not completely
on these library functions. The programmer has to write his own programs.

2 : User Defined Functions : These functions which are written by the programmer to do some
specific tasks are called User Defined Functions.

2.7.4 ELEMENTS OF USER-DEFINED FUNCTINS : In order to write an efficient user


defined function, the programmer must familiar with the following three elements.
1 : Function Declaration. (Function Prototype).
2 : Function Call.
3 : Function Definition

1 : Function Declaration (Function Prototype) : Like variable, all functions in a C program


must be declared, before they are invoked(call). The declaration of each function should end
with semicolon. Ths is called function prototype or function declaration.
The function declaration/prototype tells the compiler about the return type, the name
of the function and type of parameters which will be called and defined later in the program.

Syntax : type function-name(parameter list);


type function-name();

Ex : int add(int a,int b);


int add();
Where
type : is the return type of function.
function-name : is the name of the function.
parameter-list : Parameter list declares the variables that will receive the data sent by the
calling program.

2 : Function Call : The function can be called by simply using the function name.

Syntax : function-name();
function-name(parameters);
return value = function-name(parameters);

Ex : add(); // function without arguments


add(a,b); // function with arguments.
c=fun(a,b); // function with arguments and return values

3 : Function Definition : The program module that is written to achieve a specific task is called
function definition.

Syntax : type function-name(parameter list) // function header.


{
declaration of variables;
body of function; // Function body
return statement;
}
Where
type : return type can be int ,float,double,void etc. This is the type of the value that the function
is expected to return. If the function is not returning any value, then we need to specify the
return types as void.
function-name : is the name of the function.
parameter-list : Parameter list declares the variables that will receive the data sent by the
calling program.
Example of User Defined Function :

#include<stdio.h>
void add(); //function declaration/prototype
void main()
{
add(); //Function call
}
void add() // function definition
{ printf(“Enter the values of a and b”);
int a,b,c; scanf(“%d%d”,&a,&b);
c=a+b; Enter the values of a and b
printf(“the sum is %d”,c); 5
} 5
the sum is 10
output :

How to Execute the program.


1 : Excution of the program starts from main().
2 : The function add() is invoked.
3 : Control is transferred from function main() to function add().
4 : The function add() accepts two numbers, adds those numbers and print the result.
5 : Then control is transferrd from function add() to function main().
6 : in the function main(), there is no other function/ statement to be executed and hence
execution of the function main() is terminated.

2.7.5 PARAMETERS : parameters provides the data communication between the calling
function and called function.
They are two types of parametes 1 : Actual parameters. 2 : Formal
parameters.
1 : Actual Parameters : These are the parameters transferred from the calling function
(main program) to the called function (function).
2 : Formal Parameters :These are the parameters transferred into the calling function (main
program) from the called function(function).

Ex : main()
{
fun1( a , b ); //Calling function / main fun
}
fun1( x, y ) //called function / user def fun
{
..... .
}
Where
a, b are the Actual Parameters
x, y are the Formal Parameters

Difference between Actual Parameters and Formal Parameters

Actual Parameters Formal Parameters


1 : Actual parameters are used in 1 : Formal parameters are used in the
calling function when a function is function header of a called function.
invoked. Ex : int add(int m,int n);
Ex : c=add(a,b); Here m,n are called formal
Here a,b are actual parameters. parameters.
2 : Actual parameters can be 2 : Formal parametes should be only
constants, variables or expression. variable. Expression and constants
Ex : c=add(a,b) //variable are not allowed.
c=add(a+5,b); //expression. Ex : int add(int m,n);
c=add(10,20); //constants. //CORRECT
int add(int m+n,int n)
//WRONG
int add(int m,10);
//WRONG
3 : Actual parameters sends values to 3 : Formal parametes receive values
the formal parameters. from the actual parametes.
Ex : c=add(4,5); Ex : int add(int m,int n);
Here m will have the value 4 and n
will have the value 5.
4 : Address of actual parameters can 4 : if formal parameters contains
be sent to formal parameters address, they should be declared as
pointers.

2.7.6 FUNCTION VARIABLES : They are two types of variables.

1 : Local Variable. 2 : Global Variable.

1 : Local Variable : The local variables are defined within the body of the function or
block. These variables can access by that function only, other functions can not access these
ariables.

Ex : fun1(int a,int b)
{
int c,d; // Here c and d are the Local variable
}
2 : Global Variable : Global variables are defined outside the main() function and multiple
functions can use these variables.

Ex : int m=5, n=10; //Global Variable


main()
{
int a,b;
}
Here the variables ‘m’ and ‘n’ are defined outside the main() function. Hence they are global
variables.

Return Statement : The return statement may or may not send back any values to the calling
function(main program).
Syntax : return; // does not return any value
or
return(exp); // the specified exp value to calling function.
A function can contain more than one return statements, when the return value can return values
based on certain condition.
If a function can return some values other than int type, then we must specify the data
type to be return.

2.7.7 CATEGORY OF FUNCTIONS / TYPES OF USER DEFINED FUNCTIONS : A


function, depending on whether arguments are present or not and whether a value is returned or
not. The following are the function prototypes.
1 : Functions with no Parameters and no Return Values.
2 : Functions with no Parameters and Return Values.
3 : Functions with Parameters and no Return Values.
4 : Functions with Parameters and Return Values.

1 : Functions with no Parameters and no Return Values :

1 : In this category, there is no data transfer between the calling function and called function.
2 : But there is flow of control from calling function to the called function.
3 : When no parameters are there , the function cannot receive any value from the calling
function.
4: When the function does not return a value, the calling function cannot receive any value from
the called function.
Ex #include<stdio.h>
#include<conio.h>
void sum();
void main()
{
sum();
getch();
}
void sum() int a,b,c;
{
printf("enter the values of
a and b");
scanf("%d%d",&a,&b); Output :
c=a+b; enter the values of a and b
printf("sum=%d",c); 5
} 5
sum= 10

2 : Functions with no Parameters and Return Values.

1 : In this category, there is no data transfer between the calling function and called function.
2 : But there is data transfer from called function to the calling function.
3 : When no parameters are there , the function cannot receive any values from the calling
function.
4: When the function returns a value, the calling function receives one value from the called
function.

Ex : #include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int c;
clrscr();
c=sum();
printf("sum=%d",c);
getch();
}
int sum()
{
int a,b,c;
printf("enter the values of a Output :
and b”); enter the values of a and b
scanf("%d%d",&a,&b); 5
c=a+b; 5
return c; sum= 10
}

3 : Functions with Parameters and no Return Values.


1 : In this category, there is data transfer from the calling function to the called function using
parameters.
2 : But there is no data transfer from called function to the calling function.
3 : When parameters are there , the function can receive any values from the calling function.
4: When the function does not return a value, the calling function cannot receive any value from
the called function.

Ex : #include<stdio.h>
#include<conio.h>
void sum(int a,int b);
void main()
{
int m,n;
clrscr();
printf("Enter m and n values:");
scanf("%d%d",&m,&n);
sum(m,n);
getch();
}

void sum(int a,int b) Output :


{ enter the values of a and b
int c; 5
c=a+b; 5
printf("sum=%d",c); sum= 10
}

4 : Functions with Parameters and Return Values.

1 : In this category, there is data transfer from the calling function to the called function using
parameters.
2 : But there is no data transfer from called function to the calling function.
3 : When parameters are there , the function can receive any values from the calling function.
4: When the function returns a value, the calling function receive a value from the called
function.

Ex : #include<stdio.h>
#include<conio.h>
int sum(int a,int b);
void main()
{
int m,n,c;
clrscr();
printf("Enter m and n values");
scanf("%d%d",&m,&n);
c=sum(m,n);

printf("sum=%d",c); }
getch();
} Output :
int sum(int a,int b) enter the values of a and b
{ 5
int c; 5
c=a+b; sum= 10
return c;

2.8 Recursion

A function that calls itself is known as a recursive function. And, this technique is known as
recursion.

Syntax : Recursion is the process of repeating items in a self-similar way. In programming


languages, if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.

void main()
{
recursion();
}

void recursion()
{
recursion(); /* function calls itself */
}

The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number

Example program on recursion to find factorial of a given number using recursion:

#include<stdio.h>
int factorial(int);
int main()
{
int factorial(int n);
int fact;
clrscr();
printf(“enter the number”);
scanf(“%d”,&n);
fact=factoria(n);
printf("factorial of a given number is %d",fact);
getch();

int factorial(n)
{
int fact;
if(n==1)
return 1;
else
fact=n*factorial(n-1);
return fact;
}

o/p: Enter the number 5 : factorial of a given number is 120

2.8.1 Recursion Limitations :

When ever we are using recursive functions in our programming there are some limitiations
1.The recursive functions may involve extensive overhead because they use function calls
repeatidly.
2.Whenever we make a call we need to use some separate memory allocations
3.If the program has a large number of recursive calls then we need to run the program may be
out of memory..

2.8.2 Advantages of recursion


1. Using recursion, the length of the program can be reduced.
2. The recursion is very flexible in data structure like stacks, queues, linked list and quick
sort.
3. Using recursion we can avoid unnecessary calling of functions.
4. Recursion is used to divide the problem into same problem of subtypes and hence
replaces complex nesting code.
5. Through Recursion one can solve problems in easy way while its iterative solution is very
big and complex.

Disadvantages (Limitations) of recursion


1. It requires extra storage space. The recursive calls and automatic variables are stored on
the stack. For every recursive calls separate memory is allocated to automatic variables
with the same name.
2. Too many recursive functions there may be confusion in the code.
3. The recursion function is not efficient in execution speed and time.
4. Recursive solution is always logical and it is very difficult to trace. (Debug and
understand). Recursion takes a lot of stack space.

2.9 ARRAYS
Definition:
C supports a derived data type known as array that can be used to handle large amounts
of data (multiple values) at a time.

 An array is a collection of elements of the same data type, which share a common name.
 Array elements are always stored in contiguous memory locations.
 Each element in the group is referred by its position called index.
 The first element in the array is numbered 0, so the last element is one less than the size
of the array.
 Before using an array its type and dimension must be declared, so that the compiler will
know what kind of an array and how large an array.

2.9.1 Declaration of an Array / Defining an array


Arrays must be declared before they can be used in the program. Standard array declaration is
as:
Datatype variable_name[lengthofarray];
Here type specifies the variable type of the element which is going to be stored in the array.
Ex: int height[10];
float width[20];

2.9.2 Initializing Arrays :


The following is an example which declares and initializes an array of nine elements of type int.
Array can also be initialized after declaration.
int scores[9]={23,45,12,67,95,45,56,34,83};

We have different types of arrays based on its dimension.


1. One-dimensional arrays / Single-dimensional arrays
2. Two-dimensional arrays / Double-dimensional arrays
3. Multi-dimensional arrays

2.9.3 One – Dimensional arrays:-

A list of items can be given one variable name using only one subscript and such a
variable is called one-dimensional array or single-dimensional variable.

Syntax: The general form of array declaration is:

datatype array-name[size];

The data-type specifies the type of elements such as int, float or char. And the size indicates the
maximum number of elements that can be stored in that array.
Eg:
int a[5] ; here a is an array containing 5 integer elements.
float height[10]; here height is array containing 10 real elements.
char name[20]; here name is an array containing 20 characters.

Note: C language character strings are as simple as array of characters. And every string
should be terminated by null character (‘\0’).

Initialization of one-dimensional arrays:-

After an array is declared its elements must be initialized. Otherwise they will contain
garbage values. An array can be initialized at either of the following stages.
At compile time
At run time

Compile time initialization:-


We can initialize the elements of arrays in the same way as the ordinary variables when
they are declared. The values in the list must and should be separated by comma.

i.e data-type array-name [ size ] = { list of values };

Eg:
 int a [ 6 ] = { 3, 5, 23, 28, 6, 11 }; will initialize the given values to array a.

2.9.4 Two - Dimensional Arrays:-

C allows us to define the data in the form of table of items by using two-dimensional
arrays.

Syntax: syntax to declare two dimensional array


data-type array-name [ row size ] [ column size ];

Eg: int a [ 3] [ 4 ] ; Here a is two dimensional array with row size 3 and column size 4.,
and the total elements we can store in this array a is 12 (i.e. 3 * 4 ).

Each dimension of the array is indexed from zero to its maximum size minus one; the
first index selects the row and the second index selects the column with in that row. Two
dimensional arrays are stored in memory as follows:

Eg:

[0] [0] [0][1] [0][2] [0][3]

[1] [0] [1][1] [1][2] [1][3]

[2][0] [2][1] [2][2] [2][3]

******Representation of two dimensional array in memory******

Example program on 1 dimmensional array


Accessing an array elements
#include<stdio.h>
void main()
{
int i;
int arr[3] = {12, 3, 34}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}

o/p: 12 3 34

Read and write an array or Runtime Array initialization


An array can also be initialized at runtime using scanf() function.
Example:
#include<stdio.h>
void main()
{
int arr[4];
int i, j;
printf("Enter array element");
for(i = 0; i < 4; i++)
{
scanf("%d", &arr[i]); //Run time array initialization
}
for(j = 0; j < 4; j++)
{
printf("%d\n", arr[j]);
}
}

2.9.5 Two dimensional Arrays or multi dimmesional array


C language supports multidimensional arrays also. The simplest form of a multidimensional
array is the two-dimensional array. Both the row's and column's index begins from 0.
Two-dimensional arrays are declared as follows,
data-type array-name[row-size][column-size]
/* Example */
Int a[3][4];

Example for two dimensional Array / multi dimensional array


#include<stdio.h>

void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}

example program on arrays :

#include<stdio.h>
void main()
{
int i;
int arr[3] = {2, 3, 4}; // Compile time array initialization
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}

o/p: 2 3 4

Run time array initialization example


#include<stdio.h>
void main()
{
int i;
int arr[3] ;
printf(“Enter array elements “); // //Run time array initialization
scanf("%d %d %d \t",&arr[0],&arr[1],&arr[2]);
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}

o/p : Enter array elements 1 2 3


the elements are : 1 2 3

o/p: 2 3 4

STRINGS: or character arrays


A string is an array of characters. (Or) A string is a one-dimensional array of characters terminated by a null
character (‘\0’).

Each character of the string occupies one-byte of memory. The characters of the string are stored in contiguous
memory locations.

Declaration of Strings:-

Syntax: char string-name [size];


Eg: char city [20];
Initialization of Strings
We can initialize a character array as total string at a time.

char city [10] = “HYDERABAD”;

Reading Strings:

 The input function scanf ( ) can be used with %s format specification to read a string.
Eg: char name[30];
scanf(“%s”, name);
 The scanf() function to read single word.
 So multi word strings can’t read by using scanf() function.

Eg: char city[30];


scanf(“%s”, city);
If the input string is “NEW DELHI”, then the variable city can store only “NEW”, it ignores the rest because
white space is occurred after NEW.
 To read multi word strings, we can use gets( ) function or getchar( ) function repeatedly.
Eg: char city[20];
gets(city);
Writing or printing of strings to screen:-
 The printf() function with %s specification is used to print strings to the screen.
Eg: printf(”%s”,city);
We can also print strings by using puts () function and putchar () function repeatedly.
Eg: puts(name)

/* PROGRAM TO READ A STRING AND PRINT IT */ string ex prog


#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}

Enter name: Dennis Ritchie


Your name is Dennis.

Note : check notes for more programs on strings.

String handling functions:- or string manipulation functions or string.h functions

Operators can’t work with strings directly. So to manipulate strings we have a large number of string handling
functions in C standard library and the responsible header file is “string.h”. Some of those functions are:
strcpy ( ), strcmp ( ), strcat ( ), strlen ( ), strrev ( ) etc.

Library functions for strings Library Description


Function
strcpy(s1, s2) string.h Copies the value of s2 into s1

strncpy(s1, s2, n) string.h Copies n characters of s2 into


s1. Does not add a null.

strcat(s1, s2) string.h Appends s2 to the end of s1

strncat(s1, s2, n) string.h Appends n characters of s2


onto the end of s1
strcmp(s1, s2) string.h Compared s1 and s2
alphabetically; returns a
negative value if s1 should be
first, a zero if they are equal,
or a positive value if s2 sbould
be first

strncmp(s1, s2) string.h Compares the first n characters


of s1 and s2 in the same
manner as strcmp

strlen(s1) string.h Returns the number of


characters in s1 not counting
the null

strcpy( ):- It is to copy one string into another, and it returns the resultant string.
Syntax: strcpy ( string1, string2);
String2 is copied into string1.
Eg: char city1[10] = “HYDERABAD”;
char city2[12] = “BANGLORE”;
strcpy (city1, city2);
Here city2 is copied into city1. So city1=“ HYDERABAD”andcity2=”BANGLORE”. The size of the array
city1 should be large enough to receive the contents of city2

strcmp( ):- It is to compare two strings to check their equality. If they are equal it returns zero, otherwise it
returns the numeric difference between the first non matching characters in the strings. (i.e. +ve if first one is
greater, -ve if first one is lesser).
Syntax: strcmp (string1, string2);
Eg: char city1[10] = “HYDERABAD”;
char city2[12] = “BANGLORE”;
strcmp (city1, city2);
Here city1 and city2 are compared, and returns the numeric difference between ASCII value of ‘H’ and ASCII
value of ‘B’ as they are not equal.
Strcmp(“RAM”,ROM”);  It returns some –ve value.
Strcmp(“RAM”,RAM”):  It returns 0 as they are equal.

strcat ( ):- This function is used to join two strings together, and it returns the resultant string.
Syntax: strcat ( string1, string2);
String1 is appended with string2 by removing the null character of string1 and string2 remains unchanged. The
resultant string is stored in string1.
Eg: char city1[10] = “HELLO”;
char city2[12] = “WORLD”;
strcat (city1, city2);
Here city2 is appended to city1. So city1= “HELLOWORLD” and city2=”WORLD”.
strlen( ):- It is to find out the length of the given string and it returns an integer value, that is the number of
characters in the given string. It takes only one parameter
Syntax: strlen ( string1);
It gives the length of string1.
Eg: char city[10] = “HYDERABAD”;
strlen (city);  it gives the value 9.

strrev ( ):- This function is to find out the reverse of a given string.
Syntax: strrev (string);
Eg: char city[10] = “HYDERABAD”;
strrev (city);  it give the string “DABAREDYH”

Built in functions :
C <ctype.h> header or C type functions or character type functions in c

The functions that operate on single-byte characters are defined in ctype.h header file

Header file <ctype.h> includes numerous standard library functions to handle characters (especially test
characters).
You will find various library functions defined under <ctype.h> for character handling

All C inbuilt functions which are declared in ctype.h header file are given below.

Function Description

C isalnum() checks alphanumeric character

C isalpha() checks whether a character is an alphabet or not

C isdigit() checks numeric character

C islower() checks lowercase alphabet

C isspace() check white-space character

C isupper() checks uppercase alphabet

C tolower() converts alphabet to lowercase

C toupper() converts to lowercase alphabet


Math.h
The standard math library, math.h, contains a large number of mathematical tools. This includes
trigonometry (sine, cosine, tangent, etc.), exponential functions, logarithmic functions, absolute
values, square roots, etc. We've included a table for reference, but let's look at a few commonly
used functions.

Function description example


sqrt(x) square root of x sqrt(4.0) is 2.0

ceil(x) rounds x to smallest ceil(9.2) is 10.0


integer not less than x ceil(-9.2) is -9.0
floor(x) rounds x to largest integer floor(9.2) is 9.0
not greater than x floor(-9.2) is -10.0
pow(x,y) x raised to power y (xy) pow(2,2) is 4.0
sin(x) sine of x (x in radian) sin(0.0) is 0.0
cos(x) cosine of x (x in radian) cos(0.0) is 1.0

Date functions in c
Time functions in C are used to interact with system time routine and formatted time outputs are
displayed. Example programs for the time functions are given below.

Function Description

setdate() This function used to modify the system date

getdate() This function is used to get the CPU time

clock() This function is used to get current system time

This function is used to get current system time as


time() structure

This function is used to get the difference between two


difftime() given times

strftime() This function is used to modify the actual time format

mktime() This function interprets tm structure as calendar time

localtime() This function shares the tm structure that contains date


and time informations

This function shares the tm structure that contains date


gmtime() and time informations

This function is used to return string that contains date


ctime() and time informations

Tm structure contents are interpreted by this function


asctime() as calendar time. This time is converted into string.

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

// Print current date and time in C

int main(void)

// variables to store date and time components

int hours, minutes, seconds, day, month, year;

// time_t is arithmetic time type

time_t now;

// Obtain current time

// time() returns the current time of the system as a time_t value

time(&now);

// Convert to local time format and print to stdout

printf("Today is : %s", ctime(&now));


}

#include<stdio.h>

#include<time.h>

int main()

time_t t; // not a primitive datatype

time(&t);

printf("\nThe current date and time is: %s", ctime(&t));

You might also like