Basic C Tutorials with Examples
11.Arrays.
Introduction of C
C is programming language developed in the at AT and Tee Bell
Laboratories of USA in 1972's. It was designed and developed
by man named Dennis Richte. C is so popular
because it reliable and simple and easy to use, with the help of C
language new languages are born known as C++, Java, C# and many other
languages.
Learning in C--( Alphabets, symbols ,digits)--(constant,
variables, keywords)--(Instructions)--(Progams)
|
Alphabets are : A,B,C..
Z.
Symbols:
~,@,#,$,%,^,&,*,(),_, etc. these are also called special symbols.
Digits:
1,2,3,4,5,6,7,8,9,0.
History Of C
Before using C we were using language which is known as B, now what is B: it was on Interpreter based and had performance drawbacks.
So Dennis Ritchie developed language known as C in 1972’s. And it was famous as Mother Language of the computer system. It was based on compiler.
Strong Point as compare to B : In C language Compiler (Translator) compiles the whole source code to Machine code where as interpreter read the source code line by line or step by step.
Features of C
1. C language is the structured programming language because it has some standards.
2. Code reusability means we can use the code from environment to other environment.
3. Built in type float, int etc expressions, operators.
4. Syntax for decision control.
5. It has some libraries which pre is defined.(preprocessors).
6. File organization (.c, .cpp etc)
Before using C we were using language which is known as B, now what is B: it was on Interpreter based and had performance drawbacks.
So Dennis Ritchie developed language known as C in 1972’s. And it was famous as Mother Language of the computer system. It was based on compiler.
Strong Point as compare to B : In C language Compiler (Translator) compiles the whole source code to Machine code where as interpreter read the source code line by line or step by step.
Features of C
1. C language is the structured programming language because it has some standards.
2. Code reusability means we can use the code from environment to other environment.
3. Built in type float, int etc expressions, operators.
4. Syntax for decision control.
5. It has some libraries which pre is defined.(preprocessors).
6. File organization (.c, .cpp etc)
A sample of C Program
#include <stdio.h> // Preprocessor
main () // main function
{ // opening the brackets
Printf(“Hello”);
} // close the brackets.
main () // main function
{ // opening the brackets
Printf(“Hello”);
} // close the brackets.
Advantages Of C
1. C is a small , efficient ,powerful and flexible language
2. C is close to computer H/W (architecture).
3. C is standardized, making it more portable compare to other languages.
4. It contains libraries.
5. Many other languages borrow from Csyntax for ex: Java, java script, perl.
6. UNIX was written in C.
Disadvantages of C
1. C is designed for professional users.
2. C was not able to automatic checking compare other languages.
3. C does not support modern concept like OOP’s and multithreading.
2. C is close to computer H/W (architecture).
3. C is standardized, making it more portable compare to other languages.
4. It contains libraries.
5. Many other languages borrow from Csyntax for ex: Java, java script, perl.
6. UNIX was written in C.
Disadvantages of C
1. C is designed for professional users.
2. C was not able to automatic checking compare other languages.
3. C does not support modern concept like OOP’s and multithreading.
Data Types In C
Mainly there are two types of data types:
1. Simple or primivitive.
2. Compound or structured or derived.
An primitive data is fundamental unit of information which cannot be broken down further.
Mainly there are two types of data types:
1. Simple or primivitive.
2. Compound or structured or derived.
An primitive data is fundamental unit of information which cannot be broken down further.
Simple:
integers, floats, characters, pointers.
Derived data is made up of one or more simple data items.
Derived data is made up of one or more simple data items.
Compound : arrays, structures, unions
. Integers in C
Integers stores numeric value without a decimal point in the system memory.
Integers stores numeric value without a decimal point in the system memory.
Types
Bytes required
Short int 2
Int 4
Long int 4
Short int 2
Int 4
Long int 4
Floats
in C
It stores numeric values with decimal point in the system memory.
It stores numeric values with decimal point in the system memory.
Types
Bytes required
Float 4
Double 8
Long double 8
Characters in C
Characters is data type which stores an element of machine character set.
The character set is used is usually ASCII set, it is denoted by char. It takes only one byte. Also singed and unsigned both occupy one byte having different ranges.
Float 4
Double 8
Long double 8
Characters in C
Characters is data type which stores an element of machine character set.
The character set is used is usually ASCII set, it is denoted by char. It takes only one byte. Also singed and unsigned both occupy one byte having different ranges.
The primary data type themselves could be of several types. for example
Character char could be Unsigned char. or Signed char.
The values stores in the given integer variables will
always be be positive. for example we can declare a variables to be
unsigned.
unsigned int num_student,
The range of integer values is -32768 to +32767 value s for a 16 bit OS to
range 0 to 65535.char ch =A; where ASCII value of A is 65.
Characters Types, Size in Bytes and Range
Type
Name
Bytes Range------------- 16 bit system -------------
char 1 -128 to 127
signed char 1 -128 to 127
unsigned char 1 0 to 255
short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
int 2 -32,768 to 32,767
unsigned int 2 0 to 65,535
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
float 4 3.4E+/-38 (7 digits)
double 8 1.7E+/-308 (15 digits)
long double 10 1.2E+/-4932 (19 digits)
------------- 32 bit system -------------
Type Name Bytes Range
char 1 -128 to 127
signed char 1 - 128 to 127
unsigned char 1 0 to 255
short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295
float 4 3.4E+/-38 (7 digits)
double 8 1.7E+/-308 (15 digits)
long double 10 1.2E+/-4932 (19 digits)
What is Variables?
A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer.
For ex:
A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer.
For ex:
int a
=10; // initialization
int a // declaration
int a // declaration
Operators in C
Operators are:
1. Arithmetical operators
2. Logical operators
3. Relational operators
4. Bitwise operator
5. Shift operators
1. Arithmetical operators
2. Logical operators
3. Relational operators
4. Bitwise operator
5. Shift operators
Arithmetic operators:
These operators
are used for the for mathematical expression like (Addition ‘+’, Subtraction
’-’ , Multiplication ‘*’ , Division ’/’, Modulus ‘%’)
addition is used to two or more than two expression, same as subtraction is
used to find the difference, etc. But there is difference between
division and modulo i.e., modulo always gives the remainder.
for
example: 7%2 then it gives modulo 1 because remainder is1.
Logical Operators:
&&-------------Logical And (a>b&& x==10)
||-------------logical OR (a<m||a<n)
!---------------Logical Not (! (x>=y) Not exp.evaluates values of x neither greater than or equal to y)
Assignment operator: (x=a+b;) means value of (a+b) is stores in x.
Bitwise operator: (a: 100101 ~a: 011010)
Shift operator: These are of two types –
a) Right shift(a>>L)
b) Left shift (a<<L)
Write a Program using the above the operators:
#include<stdio.h>
main()
{
int num1 ,num2;
printf(“enter two integers”);
scanf(“%d%d,&num1&num2”);
if (num1 ==num2)
printf(“%d is equalto %d”,num1,num2);
if (!num1 ==num2)
printf (“%d is not equals to %d”,num1,num2);
if(num1>num2)
printf(“”%d is greater than %d,num1,num2);
if (num1<num2)
printf(“”%d is less than %d,num1,num2);
if (num1<=num2)
printf(“”%d is less than equal to %d,num1,num2);
if (num1>=num2)
printf(“”%d is greater than equal to %d,num1,num2);
Return 0;
}
main()
{
int num1 ,num2;
printf(“enter two integers”);
scanf(“%d%d,&num1&num2”);
if (num1 ==num2)
printf(“%d is equalto %d”,num1,num2);
if (!num1 ==num2)
printf (“%d is not equals to %d”,num1,num2);
if(num1>num2)
printf(“”%d is greater than %d,num1,num2);
if (num1<num2)
printf(“”%d is less than %d,num1,num2);
if (num1<=num2)
printf(“”%d is less than equal to %d,num1,num2);
if (num1>=num2)
printf(“”%d is greater than equal to %d,num1,num2);
Return 0;
}
Different loops
1. for loop(int i=4;i<,=4;i++)
2. while loop
3. do while loop
a) all loops use same logical(true /false)
b) stop
While loop: while(something is true)
{
(body of program)
}
If the loop condition is
not true then at the beginning loop never executed
do while loop: do while loop is always executed once.do while loop statement allows you to execute code block in loop body at least one.
syntax:
do {
// statements
} while (expression);
// statements
} while (expression);
do{
// loop body
}
While loop(loop condition)
Void main {
do{
printf(“hello world”);
}
while (4<1);
While loop(loop condition)
Void main {
do{
printf(“hello world”);
}
while (4<1);
}
for example using do while loop statement
for example using do while loop statement
1. #include <stdio.h>
2. void main(){
3. int x = 5;
4. int i = 0;
5. // using do while loop
statement
6. do{
7. i++;
8. printf("%d\n",i);
9. }while(i < x);
10.
11. }
The program output
1
2
3
4
5
For loop:
The for loop is used to
implement any type of loop condition. It is based on numeric variables. There
are three parts which is separated by semi-colons in control block of the for loop.initialization_expression
is executed before execution of the loop starts.
The execution of the loop continues until the loop_condition is false
The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.
The execution of the loop continues until the loop_condition is false
The increment_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.
Example
of using for loop statement to print an integer five times
#include <stdio.h>
void main()
{
// using for loop statement
int max = 5;
int i = 0;
for(i = 0; i < max;i++){
printf("%d\n",i);
}
}
#include <stdio.h>
void main()
{
// using for loop statement
int max = 5;
int i = 0;
for(i = 0; i < max;i++){
printf("%d\n",i);
}
}
And the output is
1
2
3
4
5
For Loop Example Using C
For example: Void main()
{
int p,n,count;
float r, si;
for (count =3;count <=3;count=count ++ )
{
printf (“enter the value of p,n,r”);
scanf(“%d%d%f”,&p,&n,&r);
si =(p*n*r)/100;
printf(“simple interest =%f”,si);
}
getch();
}
nesting for loop: void main()
{
int r ,c,sum;
for(r =1;r<=3;r++)
{
for (c=1;c=2;c++)
{
sum =r+c;
printf(“r=%d,c=%d,sum=%d\n”,r,c,sum);
}
}
}
Continue Statement
Continue statement is
used to break current iteration. After continue statement the control returns
to the top of the loop test conditions.
Void main ()
{
int r ,c;
for(r=1;r<=10;r++)
{
if (r==5)
Continue;
else
printf(“r=%d,\n”,r);
}
getch();
}
Break statement:
Break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately.
Void main()
{
int a;
for (a=1;a<=10;a++)
{
if (j==5)
Break;
else
printf(“%d\n”,a);
}
Printf(“hello”) // control pass here
getch();
}
Switch statement
The switch statement
allows you to select from multiple choices based on a set of fixed values for a
given expression. Switch statement is used to switch the multiple
switch(expression){
case value1: /* execute unit of code 1 */
break;
case value2: /* execute unit of code 2 */
break;
...
default: /* execute default action */
break;
}
Syntax: switch (integer expression)
case 1:
do this;
case2:
do this; //default :do this;
}
case value1: /* execute unit of code 1 */
break;
case value2: /* execute unit of code 2 */
break;
...
default: /* execute default action */
break;
}
Syntax: switch (integer expression)
case 1:
do this;
case2:
do this; //default :do this;
}
Write a program for
calculator using do while loop
#include<stdio.h> // these are header files
#include<conio.h> // these are header files
void main()
// main function compiler read from main
{
int
a,b,C,R; // take a variables int type
char rep='y';
do{
printf("\nCalculator\n");
// printf is a function ,using for display a message
printf("1.addition\n");
printf("2.sutraction\n");
printf("3.multiplication\n");
printf("4.division\n");
printf("enter
the value of a");
scanf("%d",&a);
printf("enter
the value of b");
scanf("%d",&b);
printf("enter
your choice");
scanf("%d",&C);
switch(C){
case 1:R=a+b;
printf("\nresult
is%d",R);
break;
case
2:R=a-b;
printf("\nresult
is%d",R);
break;
case
3:R=a*b;
printf("\nresult is%d",R);
break;
case 4:R=a/b;
printf("\nresult is%d",R);
break; // if valid then then break
default:
printf("\ncondition is invalid");
}
printf("\ndo you want to
continue(y/n):");
scanf("%c",&rep);
}while(rep!='n'); //printf("do you want to
continue");
getch();
} //
scanf("%c",&rep);
Arrays
Array by definition is a
variable that hold multiple elements which has the same data type. Array is
variables that hold multiple elements which has same data type.
An array is a multi element box, uses an indexing system.
An array is a multi element box, uses an indexing system.
Declaring the array: We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name.
Name;
Type of array
Number of element "data type array name[size];"
There are some rules for
array declaration. The data type can be any
valid C data types including structure and union. The array name has to follow
the rule of variable and the size of array has to be a positive constant
integer. We can access array elements via indexes array_name[index]. Indexes of
array starts from 0 not 1 so the highest elements of an array is
array_name[size-1].
Initializing the array: It is like a variable, an array can be
initialized. To initialize an array, you provide initializing values which are
enclosed within curly braces in the declaration and placed following an equals
sign after the array name.
int list[5]={2,3,4,5,6} OR int list[5] = {2,1,3,7,8};
int list[5]={2,3,4,5,6} OR int list[5] = {2,1,3,7,8};
Character
arrays:
char string1[]=”first”;, "Here ,we using char string and its array
size is six."
char string[]={‘f’,’g’,’t’,’y’,’u’,’I’,’\0’}; // \0 null character terminating the string.
char string[]={‘f’,’g’,’t’,’y’,’u’,’I’,’\0’}; // \0 null character terminating the string.
Passing
the array To pass an array argument in a function
specifies the name of array to pass without any bracket.
int myarray[24];
myfunction(my array,24).
int myarray[24];
myfunction(my array,24).
•
array usually pass to the function
• array using call by reference
• function knows where the array stored
• array using call by reference
• function knows where the array stored
passing
array element:
• using call by value
• pass subscripted name (ex: myarray[5]) to function.
Function prototype: void modify array (int b[],int array size);
Parameter name may be optional.
int b[] may be int[]
int array size may be int
• using call by value
• pass subscripted name (ex: myarray[5]) to function.
Function prototype: void modify array (int b[],int array size);
Parameter name may be optional.
int b[] may be int[]
int array size may be int
Multidimensional Array:
An array with more than one index value
is called a multidimensional array. All the array above is called single-dimensional
array. To declare a multidimensional array you can do follow syntax
data_type array_name[][][];
The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows:
1. int matrix[3][3];
data_type array_name[][][];
The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows:
1. int matrix[3][3];
Initializing
Multidimensional Arrays
You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array:
1. int matrix[3][3] =
2. {
3. {11,12,13},
4. {21,22,23},
5. {32,31,33},
6. };
You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array:
1. int matrix[3][3] =
2. {
3. {11,12,13},
4. {21,22,23},
5. {32,31,33},
6. };
Two dimensional
arrays
Multidimensional array have two or more than indexes values which specify the element in the array. i.e., multi[i][j].
Where [i] specify row and [j] specify column
Declaration and calculation:
int a[10][10];
int b[2][2]; // int b [2][2]={{0,1},{2,3}}
Sum = a[10][10]+b[2][2]
Array
and Pointer
Each array element occupies consecutive memory locations and array name is a pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array. This program helps you visualize the memory address each array elements and how to access array element using pointer.
#include <stdio.h>
void main()
{
const int size = 5;
int list[size] = {2,1,3,7,8};
int* plist = list;
// print memory address of array elements
for(int i = 0; i < size;i++)
{
printf("list[%d] is in %d\n",i,&list[i]);
}
// accessing array elements using pointer
for(i = 0; i < size;i++)
{
printf("list[%d] = %d\n",i,*plist);
/* increase memory address of pointer so it go to the next
element of the array */
plist++;
. } }
Here is the output
list[0] is in 1310568
list[1] is in 1310572
list[2] is in 1310576
list[3] is in 1310580
list[4] is in 1310584
list[0] = 2
list[1] = 1
list[2] = 3
list[3] = 7
list[4] = 8
You can store pointers in an array and in this case we have an array of
pointers. " int *ap[10];"
void main()
{
const int size = 5;
int list[size] = {2,1,3,7,8};
int* plist = list;
// print memory address of array elements
for(int i = 0; i < size;i++)
{
printf("list[%d] is in %d\n",i,&list[i]);
}
// accessing array elements using pointer
for(i = 0; i < size;i++)
{
printf("list[%d] = %d\n",i,*plist);
/* increase memory address of pointer so it go to the next
element of the array */
plist++;
. } }
Here is the output
list[0] is in 1310568
list[1] is in 1310572
list[2] is in 1310576
list[3] is in 1310580
list[4] is in 1310584
list[0] = 2
list[1] = 1
list[2] = 3
list[3] = 7
list[4] = 8
You can store pointers in an array and in this case we have an array of
pointers. " int *ap[10];"
What
is function?
A fuction is a self contained block of statement that perform a coherent taskof some kind.
main()
{
message();
printf(“hi”)
}
message()
{
printf(“smile ”)
}
A fuction is a self contained block of statement that perform a coherent taskof some kind.
main()
{
message();
printf(“hi”)
}
message()
{
printf(“smile ”)
}
Write Any C
program using at least one function
If a program
contain only one function , it must be main()
If a program contain more than one function then these can be contain in main().
There is no limit on number that might be present in a C program
Each function in a program is called sequence specified by the function calls in
If a program contain more than one function then these can be contain in main().
There is no limit on number that might be present in a C program
Each function in a program is called sequence specified by the function calls in
main().
A function can be called from other function but can not be defined in the other
A function can be called from other function but can not be defined in the other
function.
There are two types of function :
a) library function(printf() ,scanf()).
b) User defined (my() ).
a) library function(printf() ,scanf()).
b) User defined (my() ).
Passing the values between the function :
main()
{
int a ,b,c,sum;
printf(“enter the values ”);
scanlf(“%d%d%d”,%a,%b,%c);
sum=calsum(a,b,c); // actual argu./calling function
printf(“\nsum=%d”,sum);
}
Callsum(x,y,z) // called function
int x,y,z;
{
Int d;
D=x+y+z;
return(d);
} // a function can be return only one value at a time
main()
{
int a ,b,c,sum;
printf(“enter the values ”);
scanlf(“%d%d%d”,%a,%b,%c);
sum=calsum(a,b,c); // actual argu./calling function
printf(“\nsum=%d”,sum);
}
Callsum(x,y,z) // called function
int x,y,z;
{
Int d;
D=x+y+z;
return(d);
} // a function can be return only one value at a time
No comments:
Post a Comment