Unit 3
Unit 3
Unit 3
ARRAY
An array is a collection of related data items sharing same name and same
data type.
Types of arrays:
1) One-dimensional array
2) Two-dimensional array
3) Multi-dimensional array
An array with one dimension or one index, with same name and same
type is called one dimensional array.
Syntax:
datatype array_name[size];
Here datatype is a type of data user wants to use. It may be int, char, float
etc.
Array Initialization
int A[5]={10,20,30,40,50};
10 20 30 40 50
0 1 2 3 4
To read
int A[5],i; for(i=0;i<5;i++)
scanf(“%d”,&A[i]);
To display
int A[5],i; for(i=0;i<5;i++)
printf(“%d”,A[i]);
#include<stdio.h>
#include<conio.h>
void main()
{
int A[50],i,n,SE,pos=-1;
clrscr();
printf("Enter the size of Array\n");
scanf("%d",&n);
printf("Enter the elements of Array\n");
for(i=0;i<n;i++)
scanf("%d",&A[i]);
printf("Enter the element to Search in Array\n");
scanf("%d",&SE);
for(i=0;i<n;i++)
{
if(A[i]==SE)
{
pos=i;
break;
}
}
if(pos>-1)
printf("Element found in %d Position",pos+1);
else
printf("Element not found");
getch();
}
Page 4 of 45
void main()
{
int A[100], n, i, j, temp;
clrscr();
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &A[i]);
getch();
}
Page 5 of 45
Two–dimensional Arrays:
An array having two dimensions or two indexes, with same name and same
type is called two-dimensional arrays.
Here datatype is a type of data user wants to use. It may be int, char, float
etc.
float x[2][6];
int A[2][2]={1,2,3,4};
Here A is two dimensional array which contains 2 rows and 2 columns and
the assignments would be
A[0][0]=1 A[0][1]=2
A[1][0]=3 A[1][1]=4
To read
int A[3][3],i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&A[i][j]);
To display
int A[3][3],i,j;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”,A[i][j]);
void main()
{
int i,j,m, n, A[10][10], B[10][10], C[10][10];
clrscr();
scanf("%d", &A[i][j]);
}
printf("\n");
}
getch();
void main()
{
int i,j,m, n, A[10][10], B[10][10], C[10][10];
clrscr();
printf("\n");
}
getch();
}
Page 9 of 45
#include <stdio.h>
#include<conio.h>
void main()
{
int m, n, p, q, i, j, k, sum = 0;
int A[10][10], B[10][10], C[10][10];
clrscr();
if ( n != p )
{
printf("Matrices multiplication is not possible\n");
printf("Column of first matirx should be same as row of second matrix\n");
}
else
{
printf("Enter the elements of first matrix\n");
C[i][j] = sum;
sum = 0;
}
}
getch();
}
Page 11 of 45
#include <stdio.h>
#include<conio.h>
#include <math.h>
void main ()
{
int A[10][10];
int i, j, n, sum = 0, trace=0;
float normal;
clrscr();
printf("Enter the order of the matrix\n");
scanf("%d",&n);
printf("Enter the n coefficients of the matrix \n");
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
scanf("%d", &A[i][j]);
sum = sum + A[i][j] * A[i][j];
}
}
normal = sqrt(sum);
printf("The normal of the given matrix is = %.2f\n", normal);
Multi-Dimensional Array
Collection of elements which shares same name and same data type of order
of N dimensions.
Syntax:
datatype arrayname[s1][s2][s3] ............ *sn+;
Example :
int A[10][10][10];
Page 12 of 45
STRING
Syntax:-
char array_name[size];
G K M V \0
str
0 1 2 3 4
Note:-
Array of String
void main()
{
char name[5][20];
int i;
clrscr();
printf("Enter 5 names \n");
Page 13 of 45
for(i=0;i<5;i++)
gets(name[i]);
printf("The 5 Names entered are :\n");
for(i=0;i<5;i++)
puts(name[i]);
printf("\n");
getch();
}
Output
Enter 5 names
VARSHA G
KALYAN
MOHITH G
KALYAN
EENCHARA
NISARGA
RAM KUMAR
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
V A R S H A G K A L Y A N \0
M O H I T H G K A L Y A N \0
E E N C H R A \0
N I S R A G A \0
R A M K U M A R \0
Multiple words or more than one word cannot be accepted using scanf()
function.
Reason
because scanf() function terminate the string when ever blank space is
Example-1
X=”VARSHA G KALYAN”
a) gets(X);
b) scanf(“%s”,X)
Answer
Example-2
str=”Computer Science”
What is the value stored in str with the following input statements.
a) gets(str);
b) scanf(“%s”,str)
Answer
gets( )
syntax
gets(string_name)
Example:-
char str[50];
gets(str);
puts( )
syntax
puts(string_name)
Example:-
char str[50];
puts(str);
a) gets( ) b) scanf( )
gets(str);
scanf(“%s”, str);
Page 16 of 45
a) puts( ) b) printf( )
puts(str);
printf(“%s”, str);
STRING FUNCTION
Also, at the top of any source file where we're using the standard library's
string-handling functions we must include the header file as shown below.
#include <string.h>
1. strlen( )
Syntax
variable = strlen(string_name);
Example-1:
int Len;
Len=strlen(“GKMV”);
output:
Len=4
Page 17 of 45
Example-2:
int Len;
Len=strlen(“MGK VGK”);
output:
2. strrev( )
the string.
Syntax
strrev(string_name);
Example-1:
strrev(“GKMV”);
output:
VMKG
Example-2:
strrev(“MGK VGK”);
output:
KGV KGM
3. strlwr( )
Syntax
strlwr(string_name);
Page 18 of 45
Example-1:
strlwr(“GKMV”);
output:
gkmv
Example-2:
strlwr(“gKmv”);
output:
gkmv
4. strupr( )
strupr( ) stands for string upper case function. strupr( ) is used to convert
the lower case characters in a string to the upper case characters.
Syntax
strupr(string_name);
Example-1:
strupr(“gkmv”);
output:
GKMV
Example-2:
strupr(“GKmv”);
output:
GKMV
5. strcpy( )
strcpy( ) stands for string copy function. strcpy( ) is used to copy the
contents from Source string to Destination string.
Page 19 of 45
Syntax
strcpy(string2, string1);
Example-1:
char str[5];
strcpy(str, “GKMV”);
output:
6. strcat( )
Syntax
strcat(string1, string2);
Example-1:
char str1[10]=”MGK”;
char str2[50]=”VGK”
strcat(str1, str2);
output:
7. strcmp( )
if both strings are equal strcmp returns 0. The value will be negative if
Page 20 of 45
Syntax
strcmp(string1, string2);
Example-1:
char str1[5]="GKMV";
char str2[5]="gkmv";
strcmp(str1,str2)
strcmp(str2,str1)
strcmp(str1,str1)
output:
-32
32
0
8. strcmpi( )
Syntax
strcmpi(string1, string2);
Example-1:
char str1[5]="GKMV";
char str2[5]="gkmv";
strcmpi(str1,str2)
output:
0
Page 21 of 45
OPERATIONS ON CHARACTER
Programs that work with characters and strings often need to classify a
character--is it alphabetic, is it a digit, is it whitespace, and so on--and
perform case conversion operations on characters.
The functions in the header file `ctype.h' are provided for this purpose.
At the top of any source file where we're using the standard library's
character handling functions we must include the line
#include <ctype.h>
1. isaplha( )
Example:
isalpha(„G‟)
Output: True(1)
isalpha(„4‟)
Output: False(0)
2. isdigit( )
Example:
isdigit(„5‟)
Output: True(1)
isdigit(„K‟)
Output: False(0)
3. islower( )
Example:
islower(„b‟)
Output: True(1)
islower(„B‟)
Output: False(0)
Page 22 of 45
4. isupper( )
Example:
isupper(„G‟)
Output: True(1)
isupper(„g‟)
Output: False(0)
5. isspace( )
Example:
isspace(„ „)
Output: True(1)
isspace(„H‟)
Output: False(0)
7. isalnum( )
Example:
isalnum(„5‟)
Output: True(1)
isalnum(„G‟)
Output: True(1)
isalnum(„g‟)
Output: True(1)
isalnum(„+‟)
Output: False(0)
Page 23 of 45
8. tolower( )
Example:
tolower(„A‟)
Output: a
tolower(„a‟)
Output: a
8. toupper( )
Example:
toupper(„G‟)
Output: G
toupper(„g‟)
Output: G
#include<ctype.h>
void main()
{
char str[100];
int i,vowels=0,consnts=0;
printf("Enter the Text\n");
gets(str);
for(i=0;str[i]!='\0';i++)
switch(toupper(str[i]))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U': vowels++;
Page 24 of 45
break;
default : consnts++;
}
printf("\n Number of Vowels = %d",vowels);
printf("\n Number of Consonants = %d",consnts);
}
#include<string.h>
void main()
{
char str[50],rstr[50];
clrscr();
puts("Enter the String");
gets(str); strcpy(rstr,str);
strrev(rstr);
if(strcmp(str,rstr)==0)
puts("String is Palindrome");
else
puts("String is not a Palindrome");
getch();
}
void main()
{
char str[50];
int i,len=0;
clrscr();
printf(“Enter a String “);
gets(str);
for(i=0;str[i]!='\0';i++)
len=len+1;
printf("lenght of string=%d",len);
getch();
}
Page 25 of 45
#include<ctype.h>
void main()
{
char ch;
clrscr();
printf("Enter a character \n");
ch=getchar();
if(isalpha(ch))
printf("Character is Alphabetic ");
else if(isdigit(ch))
printf("Character Numeric");
else
printf("Special character");
getch();
}
#include<ctype.h>
void main()
{
char str[50];
int i;
clrscr();
printf("Enter a string");
gets(str);
for(i=0;str[i]!='\0';i++)
{
if(isupper(str[i]))
str[i]=str[i]+32;
else if (islower(str[i]))
str[i]=str[i]-32;
}
printf("Converted String is ");
puts(str);
getch();
}
Page 26 of 45
void main()
{
char s[50][50], t[50];
int i,j,n;
clrscr();
printf("How many names do you like to enter\n");
scanf("%d",&n);
printf("Enter %d names:\n",n);
for (i=0;i<n;i++)
scanf("%s",&s[i]);
getch();
}
Page 27 of 45
FUNCTIONS
Properties of functions:
□ Every function has a unique name. This name is used to call function
from main().
□ A function is independent and it can perform its task without
interfering with other parts of the program.
□ A function can be called from within another function.
□ A function performs a specific task.
□ Function can return only one value to the calling function via return.
□ It is easy to use.
□ Debugging is more suitable for programs.
□ It reduces the size of a program.
□ It is easy to understand the actual logic of a program.
□ Highly suited in case of large programs.
□ By using functions in a program, it is possible to construct modular
and structured programs.
Types of functions:
User-Defined functions:
Function Prototype(declaration)
Every function in C programming should be declared before they are used. These
type of declaration are also called function prototype. Function prototype gives
compiler information about function name, type of arguments to be passed and
return type.
int addgk(int a, int b); is a function prototype which provides following information
to the compiler:
Function prototype are not needed if user-definition function is written before main()
function.
Page 29 of 45
Function call
Control of the program cannot be transferred to user-defined function unless it is
called invoked.
Function definition
Function definition contains programming codes to perform specific task.
1. Function declarator
Function declarator is the first line of function definition. When a function is
called, control of the program is transferred to function declarator.
Syntax of function declaration and declarator are almost same except, there is
no semicolon at the end of declarator and function declarator is followed by
function body.
2. Function body
Arguments that are passed in function call and arguments that are accepted in
function definition should have same data type. For example:
If argument num1 was of int type and num2 was of float type then, argument
variable a should be of type int and b should be of type float,
i.e., type of argument during function call and function definition should be
same.
Return Statement
Return statement is used for returning a value from function definition to
calling function.
return (expression);
Page 31 of 45
For example:
return a;
return (a+b);
In above example, value of variable add in add() function is returned and that
value is stored in variable sum in main() function. The data type of expression
in return statement should also match the return type of function.
Function Parameter:
Function parameters are the means of communication between the calling and
the called functions.
Actual parameters are specified in the function call often known as arguments.
Formal parameters are the parameters given in the function declaration and
function definitions.
Scope:
Scope of a variable can be defined as the region over which the variable is
visible or valid.
Local variable, which are declared inside the function and restricted to the
function in which they are declared.
Global variable, which are declared outside all the functions and can be
accessed by all the functions.
Example
Output:
X=10 b=5
X=10 a=2
Page 33 of 45
In the above example a and b are called local variable, since they cannot be
accessed out their function. x is global variable, since it is accessed in main()
and gkmv() function.
When a function has no arguments, it does not receive any data from the
calling function. Similarly, when it does not return a value, the calling function
does not receive any data from the called function. So, there is no data
transfer between the calling function and the called function.
void main()
{
printf("Hello\n");
gkmv( );
printf("I am fine\n");
}
void gkmv( )
{
printf("How are you?\n");
}
Page 34 of 45
Output:
Hello
How are you?
I am Fine
In this category, there is data transfer from the calling function to the called
function using the arguments. But, there is no data transfer from the called
function to the calling function. When arguments are passed, the function can
receive values from the calling function. When the function does not return a
value, the calling function cannot receive any value from the called function.
void main()
{
void gkadd(int, int)
int a=10,b=5;
gkadd(a, b);
}
{
printf(“Sum=%d”,a+b);
}
Page 35 of 45
Output
Sum=15
In this category, there is no data transfer from the calling function to the
called function. But, there is data transfer from called function to the calling
function. When no parameters are there, the function cannot receive any
values from the calling function. When the function returns a value, the
calling function receives one value from the called function.
void main()
{
int gkadd();
printf(“Sum=%d”,gkadd());
}
int gkadd()
{
int a=10,b=5;
return(a+b);
}
Page 36 of 45
Output
Sum=15
In this category, there is data transfer between the calling function and called
function. When parameters are passed, the called function can receive values
from the calling function. When the function returns a value, the calling
function can receive a value from the called function.
void main()
{
int gkadd(int, int)
int a=10,b=5;
printf(“Sum=%d”,gkadd(a,b));
}
{
return (a+b);
}
Output
Sum=15
Page 37 of 45
Write a program to compute the sum of even numbers and the sum
of odd numbers using a function.
int n,i,osum,esum;
void main()
{
int gkodd(int);
int gkeven(int);
clrscr();
printf("Enter the value for n \n");
scanf("%d",&n);
printf("\n Sum of ODD number= %d ",gkodd(n));
printf("\n Sum of EVEN number= %d ",gkeven(n));
getch();
}
int gkodd(int n)
{
int osum=0;
for(i=1;i<=n;i+=2)
osum=osum+i;
return(osum);
}
int gkeven(int n)
{
int esum=0;
for(i=2;i<=n;i+=2)
esum=esum+i;
return(esum);
}
Page 38 of 45
While passing arrays to the argument, the name of the array is passed as an
argument(,i.e, starting address of memory area is passed as argument).
#include <stdio.h>
#include<conio.h>
void main()
{
int sum, A[]={23, 55, 42, 15, 64, 18};
clrscr();
sum=sumofarray(A); /* Only name of array is passed as
argument.*/
printf("Sum=%d",sum);
getch();
}
Recursions:
A function that calls itself is known as recursive function and this technique is
known as recursion in C programming.
void main()
{
int
gksum(int);
int n;
printf("Enter the
number\n");
scanf("%d",&n);
printf("Sum of the first %d natural numbers is %d\n",n,gksum(n));
getch();
}
int gksum(int n)
{
if(n==0)
return 0;
else
return (n+gksum(n-1));
}
void main()
{
long int gkfact(int);
int n;
printf("Enter the number\n");
scanf("%d",&n);
int gkfib(int);
void main()
{
int n,i;
clrscr();
printf("Enter the value of n \n");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( i = 1 ; i <= n ; i++ )
{
printf("%d\n", gkfib(i));
}
getch();
}
int gkfib(int n)
{
if ( n == 0 || n == 1)
return 0;
else if ( n == 2 )
return 1;
else
return ( gkfib(n-1) + gkfib(n-2) );
}
Page 42 of 45
#include<stdio.h>
#include<conio.h>
long gkfact(int);
long gkncr(int, int);
void main()
{
int n, r;
long ncr;
clrscr();
printf("Enter the value of n and r\n");
scanf("%d%d",&n,&r);
printf("NCR = %ld", gkncr(n, r));
getch();
}
long gkfact(int n)
{
int i;
long fact = 1;
for( i = 1 ; i <= n ; i++ )
{
fact = fact*i;
}
return (fact);
}
Page 43 of 45
Storage Class
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of variable whether it is character or integer or
floating-point value etc. And storage class determines how long it stays in
existence.
auto
register
static
external
a) auto
auto is the default storage class for all local variables.
Variables declared inside the function body are automatic by default. These
variable are also known as local variables as they are local to the function and
doesn't have meaning outside that function.
Since, variable inside a function is automatic by default, keyword auto are
rarely used.
Example: auto int x;
Default value of auto variables is garbage value. auto variables are stored in
the memory.
b) register
register is used to define local variables that should be stored in
a register instead of RAM. This means that the variable has a maximum size
equal to the register size (usually one word) and can‟t have the unary '&'
operator applied to it (as it does not have a memory location).
Register should only be used for variables that require quick access - such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a
register - depending on hardware and implementation restrictions.
Example: register int p;
Page 44 of 45
c) static
A variable for which memory remains allocated throughout the execution
of the entire program is called static variable. ie, the value of the static
variables continue until the end of the program.
Example: static int b;
#include <stdio.h>
void Check();
void main()
{
checkgk();
checkgk();
checkgk();
}
void checkgk()
{
static int a=0;
printf("%d\t",a);
a=a+5;
}
The output is
0 5 10
d) external
External variable can be accessed by any function. They are also known
as global variables. Variables declared outside every function are external
variables.
By default, all the global variables are external variables. We may also
use the keyword extern to declare external variables explicitly.
Example: extern int a;
Default value of external storage class is zero. External variables are
stored in the memory.
Page 45 of 45
#include <stdio.h>
void extergk();
int a=5; /* a is global variable because it is outside every function */
void main( )
{
a+=4;
extergk ();
}
void extergk ( )
{
++a;
printf("a=%d",a);
}
The Output is
a=10