Array Initialization: Datatype Arrayname (Size) (List of Value of Same Type)
Array Initialization: Datatype Arrayname (Size) (List of Value of Same Type)
array element contain Garbage. There are two types of array initialization.
1.
2.
When we declare the array then compiler automatically assigns the garbage values to the
array elements.
-as the ordinary variable. Use following syntax to initialize array directly at declaration
datatype arrayname [size] ={list of value of same type};
When we initialize the array directly then we can skip the size of array.
datatype arrayname [] = {list of value of same type};
In this case compiler will automatically count the values and will set the size of array.
Ex1.
3
15
4
7
4
0
Ex2.
1
0
2
0
Ex3.
1 2
7
0
3
0
4
0
b
5
float f[5]={0.0,15.75,-7.5};
0
4
1
0.0 0.0
Ex4. At initialization, if the size of array is smaller then the count of initializes values, then
in this case compiler give us error.
int a[3] = {5,7,10,15,9}; error
size
count =5
Run time initialization: - If initialize the array after its declaration, then it is called run
time initialization. Basically in run time initialization we replace garbage value with new
values.
Ex1.
0
5
1 2
3
10 11 -10
4
20
}
Q. Initialize the array with five numbers and find the sum ?
void main()
{
int a[]={2,5,2,1,3};
int i,sum=0;
clrscr();
for(i=0;i<5;i++)
{
sum=sum+a[i];
}
printf(%d, sum);
getch();
}
Array
Single
Dimension
Two
Dimension
Multi
Dimension
2
5
1
3
4
2
4
3
3
int a[3][4];
0
0
1
2
3
to use this element we write a[1][3]
Index no.
int a[3][4];
Size = 3*4*2
=24bytes
* Memory contains many location of one byte each. Each memory location has an address.
* C creates a group of locations according to the data type of array and assign an index
number.
Data Type
int
char
float
double
long
long double
etc.
Group Contains
2 locations
1
4
8
4
10
* In the case of double dimension array C assign two-level index number to each element
like a[0][1].
Initialization of two dimension array:- As single dimension array the double dimension
array can be initialized at compile time and run time.
Compile Time/early/static initialization :- When we initialize the array at declaration
then it is called compile time initialization . In compile time initialization we can skip the
sizes.
Case 1 :
1
0
2
0
Remaining elements are set to zero
1 5
10 0
2
The inner curly braces represent rows. The number of columns in each row always be
equal to length of largest row.
Case 2:
0
a 0 5
1
8
1 10 20
2
9
30
Case 3 :
1
8
1 10 20
50 60
2
9
30
0
Case 4 :
Remaining element
Case 7:
0
1
2
3
2
1
0
0
1
2
3
0
0
1
In this example it contains 3(three) two dimension array.
3D Array :- Group of two dimension array.
2D array :- Group of one dimension array.
1D array :- Group of elements.
Function
A large no of program is sub-divided into number of smaller programs or sub-programs
.The each sub program specifies one or more actions to be performed for the larger
program. Such sub-programs are called functions.
A function is a small piece of big program that performs a particular action for program. It
works like an independent unit. Every unit in also known as module and this kind of
programming is called modular programming.
A function groups together statements into a named unit. These unites can be invoked from
other part of program like main function.
The function main() invokes other functions. System starts the execution by calling the
main() function, so other function should be linked directly or indirectly with main()
function.
Every function of program can invoke or call other functions one or more times. So it
reduces repetition of code and complexity of program.
Dividing a program into functions is one major step towords structured
programming.
Types of functions : There are two types of functions C supports.
1. Library function.
2. User Defined Function.
The above categories may contain following types of functions
a) Function with some return type and one or more arguments/parameters.
Arguments
Function
Return the result
Function
It takes the value for processing but it does not return any result.
d) Function with no return type and zero argument or parameter.
It does not take value for processing and also it does not return any result to caller
program.
Function
Note : Zero argument/parameter and no return type are represented by keyword
void. It is a specific type that represents Nothing.
e) Function that return multiple value:- Well see in pointer
<math.h>
<graphics.h>
<conio.h>
<dos.h>
<io.h>
<ctype.h>
<stdlib.h>
<malloc.h>
<string.h>
<alloc.h>
<dir.h>
<time.h>
<bios.h>
etc.
C provides around 41 built-in libraries. It is very easy to use defined function of these
libraries.
1) <stdio.h> :- It provide functions for standard input and output devices(keyboard and
monitor) like to take input from keyboard, display output on monitor etc.
The following functions of this library are commonly used.
getchar() :- It is used to take one character input from standard input device keyboard. It
return inputted character as integer code(ASCII code).
Ex.
char ch;
printf(enter the character);
ch = getchar();
it is similar to scanf(%c,&ch);
variable to contain
inputted char
putchar(ch) :- It displays the specified character on monitor. It returns code of character,
that has displayed.
Ex.
main()
{
char ch = A;
int n;
n= putchar(ch);
printf(\n the return value of putchar =%d,n);
}
8
o/p
A
65(ASCII code of A)
Note :- It is not necessary to hold return value of putchar in a variable.
Ex.
char ch =A;
putchar(ch); It is similar to printf(%cch);
o/p
A
scanf(format string, &var1,&var2,.) :- It takes variable number of parameters.
It is used to take input from standard input device keyboard. It returns the count of
successful inputs taken by it.
LValue :- A variable that is used to hold return value of function.
Ex.
Lvalue
int a,b,c,n;
printf(enter the three numbers);
n= scanf(%d%d%d,&a,&b,&c);
printf(the return value of scanf function = %d,n);
o/p
enter the three numbers 10 20
30
- 2 character
- 3 character
- 3 character
- 1 character
- 1 character
- 1 character
11
9
fflush(stdin) :- It is used to clear the buffer to take next successful input. When we take
a character input after number input then system does not ask for character input.
Ex.
main()
{
int a;
char ch;
printf(Enter the number);
scanf(%d,&a);
printf(Enter the character);
ch=getchar();
printf(The number = %d and character = %d,a,ch);
}
o/p
Enter the number 199
\n will be assigned to ch
Enter the character
The number = 199 and character = 10 ASCII code of \n
To solve above problem we use fflush(stdin) after the scanf().
If we take character input before number then it will work properly.
Ex.
main()
{
int a;
char ch;
printf(Enter the number);
scanf(%d,&a);
fflush(stdin);
printf(Enter the character);
ch=getchar();
printf(The number = %d and character = %d,a,ch);
}
o/p
Enter the number 199
Enter the character A
The number = 199 and character = 65 ASCII code of A
10
sqrt
square root
2. pow(x,y) :- It finds x
pow(2,0) = 1
pow(-2,0)=1
pow(10,0)=1
pow(2,4)= 16
pow(-2,4)=16
pow(-2,3)=-8
pow(2,-2)=0.25
(20)
(-20)
(100)
(24)
(-24)
(-23) (-2*-2*-2)
(2-2) =1/22 = =0.25
abs(1.999) = 1
abs(0) = 0
abs(-0) = 0
4. pow10(x) :- It finds 10x
pow10 (2) = 100
pow10 (3.14) = 1000
pow10 (3.99) = 1000
102
103
103
sin(x)
cos(x)
tan(x)
asin(x)
acos(x)
atan(x)
sinh(x)
cosh(x)
log(x)
log10(x)
exp(x)
sin-1x
cos-1x
tan-1 x
hyperbolic sin x
logex
log10x
ex
12
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch;
printf("enter the character");
ch = getchar();
if(isalpha(ch))
{
printf("Alphabet");
}
else
{
printf("not alphabet");
}
}
O/P
Enter the character A
Alphabet
2.
3.
4.
5.
6.
7.
8.
isdigit(ch)
isspace(ch)
isalnum(ch)
islower(ch)
isupper(ch)
ispunct(ch)
isascii(ch) : 0 to 127 are ASCII
128 to 255 are non ASCII
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
main()
{
char ch=154;
if(isascii(ch))
{
printf("ASCII");
}
else
{
printf("non ASCII");
}
13
}
O/P :- non ASCII
9. tolower(ch) : It converts the given upper case into lower case letter. It ignores the
character if it is not an upper case letter.
void main()
{
char ch1,ch2;
printf("enter the character");
ch1=getchar();
ch2=tolower(ch1);
printf("%c",ch2);
}
O/P 1 :
Enter the character A
a
10. toupper(ch) :- It converts lower case into upper case letter.
void main()
{
char ch1,ch2;
printf("enter the character");
ch1=getchar();
ch2=toupper(ch1);
printf("%c",ch2);
}
O/P
Enter the character a
A
<conio.h> :- It contains functions for device like keyboard, monitor , mouse etc.
1. clrscr() :- It is used to clear the screen.
2. getch():- It wait for key press and return ASCII code of key
main()
{
char ch;
printf("enter the character");
ch=getch();
printf("The character = %c\t%d",ch,ch);
}
O/P :- Enter the character A
The character = A
65
main()
{
char ch;
printf("enter the character");
ch=getche();
printf("The character = %c\t%d",ch,ch);
}
O/P :- Enter the character A
A Echo
The character = A
65
(0,0)
(30,0)
(0,25)
(80,25)
15
Function
User Defined Function C allows us to create our own function in program
The user defined function works like a pre defined function. Every C program must
contain user defined function main (). The other user defined function main ( ). The other
user defined function should be called in main () function, because system executes only
the main function.
main()
{
---------------fun1();
------------fun2();
------------fun1();
R
e
t
u
r
n
R
e
t
u
r
n
C
a
l
l
}
Fun1()
{
Call
C
a
l
l
R
e
t
u
r
n
Fun3();
}
Fun2()
{
R
e
t
u
r
n
------------}
Fun3()
{
C
a
l
l
------------}
o
o
o
o
16
o When we write calling statement for function, then this call is automatically linked
with the function definition. After the completion of function control come-back to
the calling place.
o The function definition is also known as called function.
Calling function
main()
{
----function1();
----}
Return
Function1()
{
---------------}
Call
The function can be placed either before or after the calling function.
funciton1()
{
---------}
Return
call
main()
{
------funciton1();
---}
A called function can call other functions.
17
main()
{
--------function1();
-------
R
e
t
u
r
n
R
e
t
u
r
n
c
a
l
l
function1()
{
--------Function2();
}
Function2()
{
------------}
call
Elements of user defined function To create user defined we need to establish three
elements that are related to function.
1. Function declaration
2. Function call
3. Function definition
Note It is necessary to define or declare the function before its first call.
Function declaration / prototype: - It shows the following information about user defined
function.
1. The name of function to be used.
2. Data types of arguments that are received by called function.
18
3. Number of arguments.
4. What kind of value return by function
5. Sequence of arguments.
The function declaration is also known as prototype of function .We can declare a function
at both inside and outside of main function.
Use following syntax to declare a user defined function
returntype function_name(datatypes of arguments);
Ex.
int add(int,int);
Or
Int add(int a,int b); here argument name (a,b) are optional.
We need to write data type of each argument separately. If function is not returning any
value then use void as return type.
optional
void add(int,int);
or
void add(int a,int b);
If function does not have argument then we can use void as argument to shows zero
argument.
int add(void);/ int add();
void add(void);/ void add();
The void keyword is optional. Do not use it in Linux.
Function call :- System executes only the main function so we need to call user defined
function in main function. Use following syntax to call a user defined function.
1 If function is returning value then call it as
variablename = functionname (arguments);
Ex.
int a=5, b=7, ans;
ans = add(a,b);
do not specify datatype
Note- Argument of function call is also known as Actual arguments.
2. If function is not returning any value then call it as functionname (arguments);
19
Ex.
int a=5, b= 7;
add(a,b);
Called function /function definition It represent the definition function. When we call
any function then system automatically create a link between function call and function
definition and after that system transfer control to function definition. After the
completion of function definition .The control come back to the calling statement removes
the link.
Use following syntax to define a function
Function body
Ex.
Not Allowed
The above function is receiving two integer arguments and returning an integer value.
Ex 1. Function with return type and arguments.
#include<stdio.h>
#include<conio.h>
int add(int ,int);
void main()
{
int a,b,t;
printf("enter the two numbers");
scanf("%d%d",&a,&b);
t=add(a,b);
printf("the sum of %d and %d=%d",a,b,t);
}
Call a,b
main
add
Return
integer
ans = x+y;
return ans;
}
Note : The arguments in called function are treated as local variable of functions. They can
not be accessed outside of function and other function.
#include<stdio.h>
#include<conio.h>
void add(int ,int);
void main()
{
clrscr();
int a,b;
printf("enter the two numbers");
scanf("%d%d",&a,&b);
add(a,b);
getch();
}
Call with
two
integer
main
main
add
add
Return no
value
main
Call zero
perameter
add
Return
No value
void add(void)
{
int a,b,c;
printf("enter the two numbers");
21
scanf("%d%d",&a,&b);
c = a+b;
printf("the total = %d",c);
}
#include<stdio.h>
#include<conio.h>
int add(void);
void main()
{
int x;
clrscr();
x=add();
printf("the total =%d",x);
getch();
Call
main
Zero parameter
add
Return
Integer value
}
int add(void)
{
int a,b,c;
printf("enter the two numbers");
scanf("%d%d",&a,&b);
c = a+b;
return c;
}
}
int main()
{
int num, ans;
clrscr();
printf("enter the number");
scanf("%d",&num);
if(num<0)
{
num = num*(-1);
}
ans = sum_of_digits(num);
printf("the result = %d",ans);
getch();
return 0;
}
23
STRING
It is a set of character; the set may contain any character like alphabets, digits, special
symbols. Basically it is a sequence of character that is treated as a single data item.
Any group of character that is enclosed within double quotation is called string.
ABC
This is a computer
If you want to include double quotes in string then use \ escape character.
Ex.1
Ex.2
The character strings are used to create more interactive, meaningful and readable
programs. The following common operations we can perform on string.
Using string: - The string is a set of character that is arranged in a sequence. C does not
provide data type string, so, to store the string we use character array.
It means that string variable is nothing but a simple character array. The general
form of string declaration is
char string _name [size];
The size represents maximum character may be stored in string.
Ex.
char name [20];
char name [30];
24
\o
name
0 1
R A
2 3
M \0
4
\0
5
\0
6 7
\0 \0
8
\0
9
\0
C automatically initializes all the remaining elements of character array with null character
array with null character array with null character (\o)
C also allows to initialize character array without specifying the size. C automatically
determines the size from the set of initialized values.
char name[] = RAM;
or
char name[]={R, A, M, \0};
name
0 1
A
2 3
M \0
If we write
char str[4] = computer;
Then it is known as illegal initialization because length of string is greater than size of str
array.
String assignments :- The string is create only at declaration or compile time . After
declaration of character array we cant assign any string constant to it
Ex- char str[10];
Str= abc ;
Ex
char a1[10]=computer
Char a2[10];
a2=a1; compile time error
25
The array name cant be used as left operand of = operator. In simple words array name
cant be Lvalue .
Operator : - C does not allows to apply operators on strings . Operators like arithmetic,
Relational, logical, bitwise, increment /decrement etc.
Char a [ ] = VGT;
Char b [ ] =KOTA;
Char c [ ] =a+b; compile time error
Reading the string: - C provides following ways to read string from standard input
char name[20];
scanf (%s, name);
If you enter VGT KOTA, then it will read only VGT in array name.
Note: - The & (ampersand sign) is optional in the case of character input.
0
V
1
G
2
T
3
\0
19
Garbage
It we want to read complete VGT KOTA string then we need to take two string input .
char a1[10], a2[10];
scanf(%s%s,a1,a2);
It read VGT in a1 and KOTA in a2.
scanf with %ws :- we can also specify the number of character to be read from input
string .
scanf(%ws, name);
26
ws width in integer
1. If width w > = number of characters typed in , then the entire string will be
stored in name.
2. w< number of character typed in , then the excess character will be truncated .
3. Input automatically terminated at occurrence of blank space.
char name[10];
scanf(%2s,name);
0
1
G
2
\0
3
?
scanf with %[------] :% [A-Z]:- To read capital letters form A-Z only.
% [a-z]:- To read small letters from a-z only.
% [A-Z, a-z]:- both small and capital letters only.
% [A-Z, a-z, blank space]:- capital letter, small letter and blank space.
In this way we can specify any pattern for input.
The following scanf () separately for input VGT KOTA
Ex1.
Ex2.
1
?
3
?
4
19
?
2
T
3
\0
4
19
?
scanf(%[A-Z],name);
0
V
Ex3.
2
?
1
G
5
O
6
T
7
A
8
\0
9
?
19
Scanf with %[^------]:% [^\n] :- Read until new line will occur.
% [^A]:- Read until A will occur.
[^ character]
27
Terminator character
Test following scanf statement separately for input.
Vgt Kota
char name[10];
scanf(%s, name);
0
V
1
G
2
T
3
\0
9
?
1
G
2
\0
3
?
4
9
?
scanf(%[^ t],name);
0
V
scanf(%[^ \n],name);
V
G
0 1
T
2
K
4
O
5
T
6
A
7
\0
8
?
9
Character level input using getchar() :- The getchar() function is used to take
single character input.
If enclose the getchar() in loop then it can read complete string.
int i=0;
char name[10],ch;
while((ch==getchar())!='\n') code of enter key
{
name[i]=ch;
i++;
}
name[i]='\0';
we have to assign null character after reading, because c does not assign null character in
this situation.
The function gets ( ):- It takes a line input. It is automatically terminated at occurrence
of new line (\n);
char name[10];
28
gets (name);
If enter vgt kota then it reads the complete line into name array .
V
G
0 1
T
2
K
4
O
5
T
6
A
7
\0
8
?
9
29