Thursday, 25 May 2023

Java Program to count the total number of characters in a string

 //Java Program to count the total number of characters in a string

import java.util.*;

public class CountChars

{

    public static void main(String args[])

    {

        Scanner in=new Scanner(System.in);

        String s; int i;

        System.out.println("Enter a String");

        s=in.nextLine();

        for(i=0;i<s.length();i++)

           if(s.charAt(i)=='\0')

              break;

        System.out.println("The String "+s+" has "+i+" characters");

    }

}


Output:

img

Java Program to count the total number of characters in a string

 //Java Program to count the total number of characters in a string

import java.util.*;

public class CountChars

{

    public static void main(String args[])

    {

        Scanner in=new Scanner(System.in);

        String s; int i;

        System.out.println("Enter a String");

        s=in.nextLine();

        for(i=0;i<s.length();i++)

           if(s.charAt(i)=='\0')

              break;

        System.out.println("The String "+s+" has "+i+" characters");

    }

}

Wednesday, 28 April 2021

C++ User Input

 You have already learned that cout is used to output (print) values. Now we will use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:

Example

int x; 
cout << "Type a number: "// Type a number and press enter
cin >> x; 
// Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value

Good To Know

cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)

cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)


Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by calculating (adding) the two numbers:

Example

int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;





Tuesday, 27 April 2021

C++ Variables

 Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • double - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • string - stores text, such as "Hello World". String values are surrounded by double quotes
  • bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax

type variable = value;

Where type is one of C++ types (such as int), and variable is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example

Create a variable called myNum of type int and assign it the value 15:

int myNum = 15;
cout << myNum;

You can also declare a variable without assigning the value, and assign the value later:

Example

int myNum;
myNum = 15;
cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example

int myNum = 15;  // myNum is 15
myNum = 10;  // Now myNum is 10
cout << myNum;  // Outputs 10


Other Types

A demonstration of other data types:

Example

int myNum = 5;               // Integer (whole number without decimals)
double myFloatNum = 5.99;    // Floating point number (with decimals)
char myLetter = 'D';         // Character
string myText = "Hello";     // String (text)
bool myBoolean = true;       // Boolean (true or false)

Display Variables

The cout object is used together with the << operator to display variables.

To combine both text and a variable, separate them with the << operator:

Example

int myAge = 35;
cout << "I am " << myAge << " years old.";


Add Variables Together

To add a variable to another variable, you can use the + operator:

Example

int x = 5;
int y = 6;
int sum = x + y;
cout << sum;

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:

Example

int x = 5, y = 6, z = 50;
cout << x + y + z;

C++ Identifiers

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

Example

// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is
int m = 60;


The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits and underscores
  • Names must begin with a letter or an underscore (_)
  • Names are case sensitive (myVar and myvar are different variables)
  • Names cannot contain whitespaces or special characters like !, #, %, etc.
  • Reserved words (like C++ keywords, such as int) cannot be used as names.

When you do not want others (or yourself) to override existing variable values, use the const keyword (this will declare the variable as "constant", which means unchangeable and read-only):

Example

const int myNum = 15;  // myNum will always be 15
myNum = 10;  // error: assignment of read-only variable 'myNum'

You should always declare the variable as constant when you have values that are unlikely to change:

Example

const int minutesPerHour = 60;
const float PI = 3.14;

Comments in C++

Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

Example

cout << "Hello World!"// This is a comment

C++ Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example

/* The code below will print the words Hello World!
to the screen, and it is amazing */

cout << "Hello World!";

Single or multi-line comments?

It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.

C++ Output (Print Text)

The cout object, together with the << (Stream insertion) operator, is used to output values/print text:

Example

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!";
  return 0;

}

You can add as many cout objects as you want. However, note that it does not insert a new line at the end of the output:

Example

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!";
  cout << "I am learning C++";
  return 0;
}
C++ New Lines

To insert a new line, you can use the \n character (escape sequence) :

Example

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World! \n";
  cout << "I am learning C++";
  return 0;
}
Tip: Two \n characters after each other will create a blank line

Example

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World! \n\n";
  cout << "I am learning C++";
  return 0;
}

Another way to insert a new line, is with the endl manipulator:

Example

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!" << endl;
  cout << "I am learning C++";
  return 0;
}
Both \n and endl are used to break lines. However, \n is used more often and is the preferred way.

C++ Syntax

 Let's break up the following code to understand it better:

Example

#include <iostream>
using namespace std;

int main() {
  cout << "Hello World!";
  return 0;
}

Example explained

Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line 5). Header files add functionality to C++ programs.

Line 2: using namespace std means that we can use names for objects and variables from the standard library.

Don't worry if you don't understand how #include <iostream> and using namespace std works. Just think of it as something that (almost) always appears in your program.

Line 3: A blank line. C++ ignores white space.

Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed.

Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to output/print text. In our example it will output "Hello World".

Note: Every C++ statement ends with a semicolon ;.

Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }

Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.

Line 6: return 0 ends the main function.

Line 7: Do not forget to add the closing curly bracket } to actually end the main function.


Omitting Namespace

You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for some objects:

Example

#include <iostream>

int main() {
  std::cout << "Hello World!";
  return 0;

}

It is up to you if you want to include the standard namespace library or not.

Wednesday, 14 April 2021

Loops in Java

 In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions become true. There are three types of loops in Java.






Java For Loop vs While Loop vs Do While Loop

Comparisonfor loopwhile loopdo while loop
IntroductionThe Java for loop is a control flow statement that iterates a part of the programs multiple times.The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition.The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
When to useIf the number of iteration is fixed, it is recommended to use for loop.If the number of iteration is not fixed, it is recommended to use while loop.If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntax
for(init;condition;incr/decr){  
// code to be executed 
}
while(condition){  
//code to be executed 
}
do{  
//code to be executed  
}while(condition); 
Example
//for loop  
for(int i=1;i<=10;i++){  
System.out.println(i);  
}  
//while loop  
int i=1;  
while(i<=10){  
System.out.println(i);  
i++;  
}  
//do-while loop  
int i=1;  
do{  
System.out.println(i);  
i++;  
}while(i<=10); 
Syntax for infinitive loop
for(;;){  
//code to be executed  
}
while(true){  
//code to be executed  
}
do{  
//code to be executed  
}while(true);  

Sunday, 7 February 2021

WAP in C++ to find the sum of two compatible matrices.

 //To find the sum of two compatible matrices

#include<iostream>

using namespace std;

main()

{

    int r1,c1,r2,c2,i,j,sum[50][50];

    cout<<"Enter the order of the first matrix\n";

    cin>>r1>>c1;

    int arr1[r1][c1];

    cout<<"Enter the elements of the first matrix\n";

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

    {

        for(j=0;j<c1;j++)

        cin>>arr1[i][j];

    }

    

    cout<<"Enter the order of the second matrix\n";

    cin>>r2>>c2;

    int arr2[r2][c2];

    cout<<"Enter the elements of the second matrix\n";

    

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

    {

        for(j=0;j<c2;j++)

        cin>>arr2[i][j];

    }

    

    if(r1==r2&&c1==c2)

    {

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

    {

      for(j=0;j<c1;j++)

      sum[i][j]=arr1[i][j]+arr2[i][j];

    }

    cout<<"The resultant matrix is:\n";

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

    {

        for(j=0;j<c1;j++)

        cout<<sum[i][j]<<" ";

        cout<<"\n";

    }

    }

    else 

    cout<<"Matrices are not compatible …";

}

Friday, 5 February 2021

Program to find factorial of a number using class in C++

 #include<iostream>

using namespace std;

class Factorial

{

    public:

    int f=1,n,i;

    

   void Fact()

   {

       cout<<"Enter a Number\n";

       cin>>n;

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

       f*=i;

       cout<<"Factorial of "<<n<<" is "<<f;

   }

};

    main()

    {

        Factorial obj;

        obj.Fact();

    }

Program to find sum of 2 numbers using class in C++.

 #include<iostream>

using namespace std;

class Sum

{

    public:

    int a,b,c;

    

    void input()

    {

        cout<<"Enter 2 Numbers\n";

        cin>>a>>b;

    }

    

    void Calculate()

    {

        c=a+b;

    }

    

    void Display()

    {

        cout<<"Sum = "<<c;

    }

};

    main()

    {

        Sum obj;

        obj.input();

        obj.Calculate();

        obj. Display();

    }

Tuesday, 2 February 2021

PROGRAM FOR DEFINITION OF FUNCTION in C++

#include<iostream>

using namespace std;

main()

{

  int SUM(int,int);

  int a=10,b=20,sum;

  sum=SUM(a,b);

  cout<<"Sum of 2 numbers = "<<sum;

}

int SUM(int x,int y)

{

  return(x+y);

}


Thursday, 21 January 2021

Write a Program in C++ to add 2 matrices.

 //WAP TO ADD 2 MATRICES

#include<iostream>

using namespace std;

main()

{

  int i,j,n;

  cout<<"Enter the Size of the Matrix"<<endl;

  cin>>n;

  int a[n][n],b[n][n],c[n][n];

  cout<<"Enter the elements of the Matrix a"<<endl;

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

  {

  for(j=0;j<n;j++)

  cin>>a[i][j];

  }

  cout<<"Enter the elements of the Matrix b"<<endl;

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

  {

  for(j=0;j<n;j++)

  cin>>b[i][j];

  }

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

  {

  for(j=0;j<n;j++)

  c[i][j]=a[i][j]+b[i][j];

  }

  cout<<"The Sum of the Two Matrices:"<<endl;

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

  {

  for(j=0;j<n;j++)

  cout<<c[i][j]<<" ";

  cout<<endl;

  }

}

PROGRAM IN JAVA TO ADD 2 MATRICES [ DOUBLE DIMENSIONAL ARRAYS ]

 import java.util.*;

class DDA

{

  public static void main(String args[])

  {

  Scanner in=new Scanner(System.in); 

  int i,j,n;

  System.out.println("Enter the Size of the Matrix");

  n=in.nextInt();

  int a[][]=new int[n][n];

  System.out.println("Enter the elements of the Matrix");

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

  { 

  for(j=0;j<n;j++)

  a[i][j]=in.nextInt();

  }

  System.out.println("The Martix:");

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

  {

  for(j=0;j<n;j++)

  System.out.print(a[i][j]+" ");

  System.out.println();

  }

  }

}

PROGRAM IN C++ TO ADD 2 MATRICES [ DOUBLE DIMENSIONAL ARRAYS ]

 //WAP IN C++ TO ADD 2 MATRICES

#include<iostream>

using namespace std;

main()

{

  int a[10][10],i,j,n;

  cout<<"Enter the Size of the Matrix";

  cin>>n;

  cout<<"Enter the elements of the Matrix"<<endl;

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

  { 

  for(j=0;j<n;j++)

  cin>>a[i][j];

  }

  cout<<"The Martix:"<<endl;

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

  {

  for(j=0;j<n;j++)

  {

  cout<<a[i][j]<<" ";

  }

  cout<<endl;

  }

}

WAP in Java to read and display the sum of elements in a Single Dimensional array.

 import java.util.*;

class Sum_Array

{

  public static void main(String args[])

  {

  Scanner in=new Scanner(System.in);      

  int N,i,sum=0;

  System.out.println("Enter the size of the array");

  N=in.nextInt();

  int arr[]=new int[N];

  System.out.println("Enter "+N+" Numbers");

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

  {

  arr[i]=in.nextInt();

  sum=sum+arr[i];

  }

  System.out.println("The Sum of the elements of the array is: "+sum);

  }

}

Write a Program in C++ to find product of 2 matrices.

 //Program to find product of 2 matrices

#include<iostream>

using namespace std;

main()

{

  int A[10][10],B[10][10],C[10][10],i,j,k,n;

  cout<<"Enter the size of the Matrix\n";

  cin>>n;

  cout<<"Enter the elements of Matrix A\n";

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

  {

    for(j=0;j<n;j++)

    cin>>A[i][j];

  }

  cout<<"Enter the elements of Matrix B\n";

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

  {

    for(j=0;j<n;j++)

    cin>>B[i][j];

  }

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

   for(j=0;j<n;j++)

  {

     C[i][j]=0;

     for(k=0;k<n;k++)

     C[i][j]=C[i][j]+A[i][k]*B[k][j];

  }

  cout<<"The product of the 2 matrices :\n";

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

  {

    for(j=0;j<n;j++)

    cout<<C[i][j]<<" ";

    cout<<endl;

  }

}

Friday, 15 January 2021

WAP in C++ to read and display a Single Dimensional array.

#include <iostream>

using namespace std;

main()

{

  int N,i;

  cout<<"Enter the size of the array\n";

  cin>>N;

  int arr[N];

  cout<<"Enter "<<N<<" Numbers\n";

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

  cin>>arr[i];

  cout<<"The elements of the array are:\n";

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

  cout<<arr[i]<<"\n";

WAP in Java to read and display a Single Dimensional array.

import java.util.*;

public class Main

{

  public static void main(String args[])

  {

  Scanner in=new Scanner(System.in); 

  int N,i;

  System.out.println("Enter the size of the array");

  N=in.nextInt();

  int arr[]=new int[N];

  System.out.println("Enter "+N+" Numbers");

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

  arr[i]=in.nextInt();

  System.out.println("The elements of the array are:");

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

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

  }

}

WAP in C++ to read and display the sum of elements in a Single Dimensional array.

#include <iostream>

using namespace std;

main()

{

  int N,i,sum=0;

  cout<<"Enter the size of the array\n";

  cin>>N;

  int arr[N];

  cout<<"Enter "<<N<<" Numbers\n";

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

  {

  cin>>arr[i];

  sum=sum+arr[i];

  }

  cout<<"The Sum of the elements of the array is: "<<sum;

}

Sunday, 10 January 2021

Java Program to accept a letter and check Whether a character is Vowel or Consonant.

 import java.util.*;

public class Main

{

    public static void main(String args[])

    {

    Scanner in=new Scanner(System.in);    

    char ch;

    System.out.println("Enter a Character to check whether it is a vowel or a Constant");

    ch=in.next().charAt(0);

    if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')

    System.out.println(ch+" is a Vowel.");

    else 

    System.out.println(ch+" is a Constant.");

    }

}

C++ Program to Check Whether a character is Vowel or Consonant.

 //C++ Program to accept a letter and check Whether a character is Vowel or Consonant.

#include<iostream>

using namespace std;

main()

{

    char ch;

    cout<<"Enter a Character to check whether it is a vowel or a Constant\n";

    cin>>ch;

    if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')

    cout<<ch<<" is a Vowel.";

    else 

    cout<<ch<<" is a Constant.";

}

Write a Program in C++ to find Sum of 2 Numbers using assignment statement.

 //Write a Program in C++ to find Sum of 2 Numbers using assignment statement.

#include<iostream>

using namespace std;

main()

{

    int a=10,b=20,sum;

    sum=a+b;

    cout<<"Sum= "<<sum;

}

Write a Program in Java to find Sum of 2 Numbers using assignment statement.

 public class Sum

{

    public static void main(String args[])

    {

        int a=10,b=20,sum;

        sum=a+b;

        System.out.println("Sum= "+sum);

    }

}

Sunday, 27 December 2020

Write a Program in C++ to input 3 Numbers and display the smallest number. Hint: Use min()

 #include<iostream>

#include<cmath>

using namespace std;

main()

    {

        int a,b,c,Min;

        cout<<"Enter 3 Numbers\n";

        cin>>a>>b>>c;

        Min=min(a,b);

        Min=min(Min,c);

        cout<<"Smallest Number= "<<Min;

    }

Saturday, 26 December 2020

Write a Program in Java to input 3 Numbers and display the smallest number. Hint: Use Math.min()

 import java.util.*;

class Min

{

    public static void main(String args[])

    {

        Scanner in=new Scanner(System.in);

        int a,b,c,min;

        System.out.println("Enter 3 Numbers");

        a=in.nextInt();

        b=in.nextInt();

        c=in.nextInt();

        min=Math.min(a,b);

        min=Math.min(min,c);

        System.out.println("Smallest Number= "+min);

    }

}

Write a Program in C++ to find out the Diagonal of a Square taking side of a Square as Input.

 #include<iostream>

#include<cmath>

using namespace std;

main()

    {

        double a,d;

        cout<<"Enter the side of the Square\n";

        cin>>a;

        d=sqrt(2)*a;

        cout<<"Side of the Square= "<<a<<"\n";

        cout<<"Diagonal of the Square= "<<d<<"\n";

    }

Write a Program in Java to find out the Diagonal of a Square taking side of a Square as Input.

import java.util.*;

class Diagonal

{

    public static void main(String args[])

    {

        Scanner in=new Scanner(System.in);

        double a,d;

        System.out.println("Enter the side of the Square");

        a=in.nextInt();

        d=Math.sqrt(2)*a;

        System.out.println("Side of the Square= "+a);

        System.out.println("Diagonal of the Square= "+d);

    }

}

/* Question: The final velocity of a vehicle can be calculated by using the formula:

V2=u2+2as;

where u= initial velocity, a=acceleration, s=distance covered

Write a Program in C++ to calculate and Display the final velocity by taking initial velocity, acceleration and the distance covered as inputs. */

#include<iostream>

#include<cmath>

using namespace std;

main()

    {

        int u,a,s;

        double v;

        cout<<"Enter the initial Velocity, acceleration and distance covered\n";

        cin>>u>>a>>s;

        v=sqrt((u*u)+(2*a*s));

        cout<<"Final Velocity = "<<v;

    }

Java Program to count the total number of characters in a string

 //Java Program to count the total number of characters in a string import java.util.*; public class CountChars {     public static void mai...