Sunday, 3 December 2017

String - class 10

Strings are made up of characters.A character in a string can be refered by its position in the string.The index of the first character in a string is 0.String value cannot be changed.So string is immutable.
String functions:
1. charAt(index)
        It gives the character at the specified index.
        String s="Computer Application";
         char x=s.charAt(3);
        The answer is p,since index starts from 0.
2. indexOf(character)
        It gives the index of the first occurance of the given character.Its just opposite of charAt.
          String s="reading books";
           int x=s.indexOf('0');
           The answer will be  9,since space is also part of a string
3. lastIndexOf(character)
           It gives the index of the last occurance of the given character.
            String s="reading books";
            int x=s.lastIndexOf('0');
           The answer will be  10.
4. length()
           It gives the total characters in the string.It value statrs from 1 not 0.Therefore the length of "BCBS" is 4.It includes even the space. Remember the length of the array is length, whereas string is length().
5. toLowerCase()
          Converts the string to lowercase letters.
          String s="BORDER";
          String s1=s.toLowerCase();
          The answer will be computer.
6.toUpperCase()
            Converts the string to uppercase letters.
            String s="tension";
            String s1=s.toUpperCase();
            The answer will be TENSION.
7. equals()
          Compares two strings and return true if both are same else it will return false.
           String s="Boys";
            String s1="boys";
           s.equals(s1) will give you false.
8. equalsIgnoreCase()
          Returns true even if the strings are of different cases.
          String s="Boys";
            String s1="boys";
           s.equals(s1) will give you true since it is ignore case.
9.  compareTo()
          Compares two strings lexicographically.
          It gives 0 if both the strings are equal. value less than 0 if string1 lexicographically less than string2, value greater than 0 if string1 lexicographically greater than string2.
          String a="Computer";
          String b="Application";
          int n=a.compareTo(b);
          if a and b are same then  n=0,
          if a is greater than b then  n>0,
          if a is less than b then  n>0,  i am refering  a  always coz in the syntax i have given a first.
10. startsWith()
          The result is true if the given string begins with a specified string.
11.endsWith()
          The result is true if the given string ends with a specified string.
12. substring(int n )
        Removes the part of the string till the end of the string
13. substring(int start, int end)
        Removes the part of the string from starting from the index start upto character at the index end without including it.
  String s="something";
String s1=s.substring(2,5);
The answer will be met.
14. replace(char ch1,char ch2)
         It gives a new string obtained by replacing every occurance of character ch1 by character ch2.
             

StringBuffer:
You cannot change the size or the content once the strings are created.However, sometimes we need to have a dynamic string that can be modified.So we are using StringBuffer instead of string.
     To assign a value:
  StringBuffer s=new StringBuffer("Computer");
1. append(char ch)
          It adds a character to the end of the StringBuffer.
2. insert(int index, char ch)
          Inserts a character into the StringBuffer at the specified index.
3. setCharAt(int index,char c)
        It changes the character with ch in the specified location
4. reverse()
5. capacity()
       It gives the amount of memory space allocated.       
6. delete(index1,index2)
      It deletes the characters from index 1 to index2
Character Functions :
1. Character.isLetter()
      Checks whether the character is a letter or not.
2.Character.isDigit()
      Checks whether the character is a digit or not.
3. Character.isLetterOrDigit()
      Checks whether the character is a letter or digit.
4. Character.isWhiteSpace()
      Checks whether the character is a space or not.
5. Character.isUpperCase()
       It checks whether the character is a uppercase letter.There is a difference between toUpperCase and isUpperCase.refer string functions.
6. Character.isLowerCase()
       It checks whether the character is a uppercase letter.There is a difference between toLowerCase and isLowerCase.refer string functions.
7.Character.toUpperCase()
          Changes the character into uppercase letter.There is a string function also.This is only for a particular character.
8.Character.toLowerCase()
       Changes the character into lowercase letter.There is a string function also.This is only for a particular character.  
Converting string data type to other data types:

 String to integer
    i.  Integer.parseInt (string) or
        Integer.valueOf(string)
 same way you convert string into long,float double.Replace Integer with the corresponding data type.

Converting primitive data types to string :

Integer to string
  Integer.toString(integer);
 Now you can't do any mathematical operations with this number.
same way you convert long,float double to string.Replace Integer with the corresponding data type.

       

String

Points to remember : (Refer the String post)
1.  ASCII codes :
      A - Z   = 65 - 90
      a - z    = 97 - 122
The difference between a capital and its equivalent small letter is 32.
2. To input a character:
e.g :
char x =  (char)System.in.read( );
3. The difference between next() and nextLine( ) is
next( ) used to input a string without the space whereas
nextLine( ) used to input a line of text.
4. Difference between String and StringBuffer:
String : immutable i.e the characters that the string contains cannot be modified or changed.It has fixed length.
StringBuffer : mutable i.e the string can be changed. Flexible length.

Both are defined in java.lang, so it is available automatically.

5. Exception : unexpected situation encountered by the program.
throws: keyword to inform that an error has occured.
6. String array
 String name[] = new String[10];
10 is not the size of the string , it is the size of the array.
7. Static variable : It is also called class variable. A data member which is declared for a class, ans all the objects share this data member.
   Static method : function which uses static keyword as a modifier.
8. Group of logically related classes together are called Package.

Arrange the names in ascending order:

class sort
{
public static void main()
{
String name[]={........};------Assign names.
int l=name.length;------length of the array not string
int i,j;
String temp=" ";
for(i=0;i< l-1; i++)
{
for(j=0;j< l-i-1; j++)
{
if(name[j].compareTo(name[j+1])>0) ---comparing strings
  {
    temp=name[j];
    name[j]=name[j+1];
    name[j+1]=temp;
   }
  }
}
for(i=0;i<l;i++)
System.out.println(name[i]);
}
}
}

Binary search :
It is similar to numerical search except few changes. Assume there are 10 names and string n should be searched.
int u=9,l=0,mid=0, flag =-1;
while(l<=u)
{
mid=(l+u)/2;
if (n.compareTo(name[mid])==0)
{
flag=mid;
break;
}
else if  (n.compareTo(name[mid])>0)
{
l=mid+1;
}
else if (n.compareTo(name[mid])<0)
{
u=mid - 1;
}
}
if(flag== -1)
System.out.print("Not found in the list");
else
System.out.print("Name"+n+"is at"+flag+"index");
}

Array Sort

Sorting Arrays
  • Selection Sort
  • Bubble Sort
Before we go to sorting , learn how to swap two values.
let us take x=30 and y=20, now interchange these two in java.
we might write
        x=y;
        y=x;
Now the value of x will be 20 and y also will be 20, coz in the first line y is assigned to x.Therefore the value of x is 20.In the second line ,we assign 20 to y not 30.Therefore we need one more temporary variable.
       temp=x;
        x=y;
        y=temp;
temp takes the value 30, x becomes 20, and y becomes 30.
Bubble Sort:
import java.util.*;
class bubble{
public static void main()
   {
int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,j,l,temp; 
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++) -----------------------------------1
a[i]=s.nextInt();-----------------------------------2

for(i=0;i< l-1;i++)--------------------------------3
{
    for(j=i+1;j<l;j++)------------------------------4
      {
         if(a[i]>a[j])----------------------------------5
           {
              temp=a[i];
              a[i]=a[j];
               a[j]=temp;
           }
     }
}
System.out.println("The values after sorting");
  for(i=0;i<l;i++)
System.out.println(a[i]);
}
}

step 1 and 2  : input values
step 3 and 4 : There should be 2 loops,so that we compare the top most element with the least value.
step 4: If the top value is bigger(in case you want to sort in ascending order) the you should change it.Therefore swap the values.
Selection Sort :
import java.util.*;
class selection
{
public static void main()
   {
int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,j,l,temp,loc; 
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++) 

a[i]=s.nextInt();
for(i=0;i< l-1;i++)
{
      small=a[i];---------------------------------------1
      loc=i;---------------------------------------------2
    for(j=i+1;j<l;j++)
        {
            if(small > a[j])------------------------------3
              {
                 small=a[j];-------------------------------4
                 loc=j;
              }
        }
        temp=a[i];------------------------------------5
        a[i]=a[loc];
        a[loc]=temp;
    }
System.out.println("The values after sorting");
  for(i=0;i<l;i++)
System.out.println(a[i]);
}
}

step 1 : Take the value in ith place as the small value.Initially the first value is small.So that we can compare it with other values.
step 2: Record the location of that value
step 3 :Compare the small value with the other values
step 4 :If small is bigger than the other value then assign that value to small.
step 5: Swap the values
 Write a program to pass an array to a function:
import java.util.*;
class arr2
{
void get(int a[], int l)
{   int i;
    for(i=0;i<l;i++)  
    System.out.println(a[i]);
}
public static void main()
   {
arr2 ob=new arr2();

int a[]=new int[10];
Scanner s=new Scanner(System.in);
int i,j,l,temp; 
l=a.length ;
System.out.println("Enter the values");
for(i=0;i<l;i++)  

a[i]=s.nextInt();
ob.get(a,l);
}
}

Class 10 - Arrays

Array is an interesting topic. Imagine a situation where you
want to input the names of students in your class along with
the roll no and 3 subjects marks. There are 50 boys in your
class. Then how many variables you need? There is no point
in writing a program. Array comes in handy in such a
situation .

An array is a collection of values of same data type. Each element in an array is refered by the array name with the subscript or index.It is enclosed in square bracket [ ], whereas methods use ( ).
  • Declaration
  • Memory allocation
  • Initialization
Declaration:
Like the normal declaration of variables, we need to declare the array also.
data type array name[];

int marks[];
Memory allocation:
data type array name[]=new datatype[size];

int a[]=new int[10];


How many values you are going to use should be mentioned where it is given size.The common mistake we make here is writing the variable name after new.

int a[]=new a[10]; is wrong

Initializing values

int a[]={10,20,30,40};

The place value of each element is called a subscript or an


index. The index value starts from zero, so the last

element index is one less than the size.

To find the length of an array use length.


int l=a.length;

No brackets after length.  It finds the length of the array 'a'


which is 4 and it is stored in a variable l;

To accept 10 values from the user.

Example 1: Blue J method
class ar1
{
public static void main(int a[])

Example 2: Scanner Method


import java.util.*;
class ar1
{
public static void main()
   {
int a[]=new int[10];--------------------------1


Scanner s=new Scanner(System.in);


int i,l,s=0;


l=a.length;------------------------------------2


System.out.println("Enter the values");


for(i=0;i<l;i++)------------------------------3


a[i]=s.nextInt();------------------------------4


for(i=0;i<l;i++)


s=s+a[i];-------------------------------------5
 

System.out.println(a[i]);

   }
}
Step 1 : an array a is created ,

Step 2 :finds the  Length

Step 3 : index starts from 0 and less than length l

Step 4 : The values are store in a.First value is stored in
a[0], second in a[1] and so on

Step 5: When i=0, a[0] value is added to s, when i=1 ,a[1] is added and so on..

Loop plays an important role in Arrays , whether it is for accepting values or printing it.

Accepting values :

  • System.out.println("Enter the values");

    for(i=0;i<l;i++)


    a[i]=s.nextInt();


    Printing :

    for(i=0;i<l;i++)


    System.out.println(a[i]);


Write the Java statements for the following:

  • Declare 5 integers in code.
            int code[] = new int[5];
  • Declare to store 10 names.
           String names[ ] = new String[10];
  • Assign the values 10.5, 20.5, 30.5, 40.5 to an array number.
           float number[ ] = { 10.5, 20.5, 30.5, 40.5};


Search 
  • Linear

  • Binary

import java.util.*;
class linear{
public static void main()
   {
int a[]=new int[10];


Scanner s=new Scanner(System.in);


int i,l,n,flag=0;


l=a.length ;


System.out.println("Enter the values");


for(i=0;i<l;i++)


a[i]=s.nextInt();


System.out.println("Enter the number to be searched");

n=s.nextInt();


for(i=0;i<l;i++)
{
   if(a[i]==n)
     {
       flag=1;
        break;
    }
}


if(flag==1)


System.out.print(n+"found");


else


System.out.print(n+"not found");


  }
}

Initially flag is 0, if the number is found the flag value will change to 1.


Binary Search

This might look little complicated,but if you understand how it works,it is a cake walk.

The prerequisite is that the array elements should be arranged in some order either in ascending or descending.

In the boards generally the question will not ask you to sort
 and search in the same program.

The linear search takes more time since it has to check each
 and every element sequentially.It is a good idea but not a great one.

So, here in binary search the idea is divide the array and discard whatever not necessary.

Step 1: we are going to divide the array into  two parts.
           
              For that we should find the middle value.

Step 2: Compare the number  to be searched say 'n' with                   the middle value say 'm'.If both are same,  Bingo.

Step 3: If the n is smaller than m, then you would find n in 

the first half ,if the array  is arranged in ascending order.Then 

you dont want the second part anymore.discard it. So the

length changes after you discard the second part.Lower index 

value remains the same that is 0, but upper limit becomes

middle value - 1.Then step 2 will be repeated.

If the n is bigger than m, then you would find n in the second

half ,if the array  is arranged in ascending order.Then you

dont want the first part anymore.discard it. So the length

changes after you discard the second part.Upper index value

remains the same, but lower limit becomes middle value +

1.Then step 2 will be repeated.

Example :

The array is
 14 ,  23,  28, 36,  69,  88
The number to be searched is 23.

Step 1:
Middle value = (lower index +Upper index)/2
                      = (0+5)/2
                      = 2.5
Either round off or truncate it. Let us take 3.So the middle value is 36.
Step 2 :
Compare 23 and 3 rd element 36.Both are not same.
Step 3 :
23 is smaller than 36, that means 23 will not be there after 36.

so discard second half, that is elements after 36.Lower index is still 0, and upper index becomes the value before the middle value , i.e 28.

Checking will go on till it finds the value.

If the value to be searched is 88 then,

88 is bigger than 36, therefore 88 will not be in the list

before 36.

so discard first half, that is elements before 36.upper

index remains the same and lower index becomes the

value after the middle value.

 Checking will go on till it finds the value. Otherwise  it will print the nmber not in the list.

class binary
{
public static void main(int a[],int n)---------------------------1
{
int l,i,mid,place,flag=0;


l=a.length;--------------------------------------------------------2


int low=0,up= l -1;----------------------------------------------3


while(low <= upp)----------------------------------------------4


{
      mid = (low+up)/2;------------------------------------------5


      if(a[mid]==n)
         {
              flag=1;------------------------------------------------6


              place=mid;--------------------------------------------7


              break;-------------------------------------------------8


         }
      else if(a[mid] < n)-----------------------------------------9


            low=mid+1;
      else
            upp=mid - 1;
}


if(flag==1)


System.out.print(n+"is found at+(place+1));-----------------10
else


System.out.print(n+"is not found ");


}
}
step 1: input the array, number to be searched

step 2: find the length of the array


step 3:initialize the values for lower and upper index. l-1 coz, index starts from 0.


step 4:the loop should continue as long as lower limit is less than upper limit.


step 5:find the middle value.common mistake here is 
(a[low]+a[upp])/2


step 6:there is some variable with some intial value so that when we find the number, change that value.If the value is not changed then it means the number is not found,coz you would not have gone to step 6.


step 7: if you want to find exactly where the number occurs in the array,then assign the mid index, not mid value.It is not a[mid].


step 8:Once we found the number,come out. no more searching.


step 9:check the number with middle value , change the low or upper index accordingly.


Isn't that easy.


Friday, 1 December 2017

Class 8 - Revision C++ Programming


 1. Identify the valid and invalid variables:

            i.       Bond007 – Valid
           ii.       where?    - invalid ( Special character ? not allowed)
          iii.       Prove them wrong – Invalid(Special character space)
          iv.        int – Invalid(keywords not allowed)
           v.        Plug&Play – Invalid(Special character & not allowed)
          vi.        a123 – Valid
         vii.       10DowningStreet – Invalid(Starts with a number)

  2. Correct the  following statements:
    i.       cin>>”a”;
   ii.       cout<<The answer=>>total;
  iii.       Character a=’x’;
  iv.        k=100

                i.   cin>>a;
       The variable should  not be within quotation.      
ii. cout<<”The answer=”<<total;
     The answer =  is just a message ,not a variable          Therefore it should be within quotations. and << is used          with cout.
                iii.      char a=’x’;
      The data type is char.
                iv.       k=100;
      Most of the statements are terminated by ;


   3.  Write the c++ expression for the following :
                             i.   r2
                  = r * r
                            ii.   a3/6
                 = (a*a*a)/6
Here the multiplication ,division symbols should be written correctly.

   4. Evaluate :
                   i.            (10 >100) && (4>0)
                  ii.            !(25 < 20)
                 iii.            (1+2 <6)

Here the answer will be either true or false.The statements use logical and relational operators.
         in question i.  
           10 is not greater than 100 so it is false . But 4 is greater than 0 , so it is true . Remember in AND operation both the statements should be true to get the answer True.
           Therefor the answer is False.
        in question ii.
            25 is greater than 20  so it is False, but because of the NOT(!) operator  the    answer is True.      
                                
A program in C++ involves 4 basic steps.

1.Declaration
2. Assignment / Input
3. Calculation
4. Output

In step 1 , we declare a variable ( data type and a variable name).
In step 2 , we either give values to variables or accept values from                     the user.
In step 3 , Calculation, if any.
In step 4 , Print the answer.

Simple.
Step 1:
Declaration 
The data types of the variables should be mentioned before we use them.
We need to specify whether the number we are going to use is a whole number(int) or a decimal number(float),
or  we are going to use a single letter(char) or group of characters(String).


Step 3
If we have any calculation to do, we do it in step 3.
Step 4
Finally we print the output(answer).

Program 1:

Assign your class and sec and display them .
#include<iostream.h> ------------------------ 1
#include<conio.h>      ------------------------ 2
void main()                 ------------------------- 3
{
clrscr();                       ------------------------- 4
int c;                           ------------------------- 5
char s;                         ------------------------- 6
c=8;                            ------------------------- 7
s=’G’;                         ------------------------- 8
cout<<c<<s; ------------------------- 9
getch();                      
}




In line nos 1 and 2, we have  header files.It contains pre defined functions. iostream conatains functions for cin and cout.
conio has some functions like clrscr which is clear screen .
In line nos 5,6 we mention the data types(declaration).
In line nos  7,8 we assign the values to the variables. and in line 10 , we print the answer.

Program 2:

Accept 3 numbers and find its average.
#include<iostream.h> 
#include<conio.h>      
void main()                
{
clrscr();                      
int a,b,c,tot;                ------------------------- 1
float avg;                    ------------------------- 2
cout<<"Enter first number:";     
cin>>a;                           -------------------------3
cout<<"\n Enter second number:";        
cin>>b;                                    -------------------------4
cout<<"\n Enter third number:";        
cin>>c;                                    -------------------------5       

tot=a+b+c;                 

avg=tot/3;
cout<<"\n Total="<<tot;
cout<<"\n Average="<<avg;
getch();
}

Here we are accepting 3 numbers from the user, they could be anything. Line numbers 3,4,5 could be written in a single line like this cin>>a>>b>>c;
\n is used to take the cursor to the next line while printing, otherwise everything will be in the same line.

Program 3
Accept the side of the square from the user and calculate its area.
Area of square = side x side


#include<iostream.h> 

#include<conio.h>      
void main()                

{
clrscr();                      
int side,area;                

cout<<"Enter the side:";        
cin>>side;                                     

area=side * side;
cout<<"\n Area ="<<area;
getch();
}