In this C++ program, we will take an input from the user and check whether the number is prime or not.

 

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.   int n, i, m=0, flag=0;  
  6.   cout << "Enter the Number to check Prime: ";  
  7.   cin >> n;  
  8.   m=n/2;  
  9.   for(i = 2; i <= m; i++)  
  10.   {  
  11.       if(n % i == 0)  
  12.       {  
  13.           cout<<"Number is not Prime."<<endl;  
  14.           flag=1;  
  15.           break;  
  16.       }  
  17.   }  
  18.   if (flag==0)  
  19.       cout << "Number is Prime."<<endl;  
  20.   return 0;  

Program to find average of N Numbers

#include<stdio.h>

int main()
{
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));
    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Program to find Armstrong Number between 1 to 500

#include<stdio.h>
#include<math.h>

int main()
{
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
    int n,sum,i,t,a;
    printf("\n\n\nThe Armstrong numbers in between 1 to 500 are : \n\n\n");

    for(i = 1; i <= 500; i++)
    {
        t = i;  // as we need to retain the original number
        sum = 0;
        while(t != 0)
        {
            a = t%10;
            sum += a*a*a;
            t = t/10;
        }

        if(sum == i)
        printf("\n\t\t\t%d", i);
    }

    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Checking for Odd and Even Numbers using Bitwise Operator

#include<stdio.h>

int main()
{
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
    int x;
    for(x = 0; x <= 10; x++)
    {
        if(x&1) // if number is odd
            printf("\t\t\t%d is odd\n",x);
        else if(!(x&1)) // ! is used inside if to reverse the boolean value
            printf("\t\t\t%d is even\n",x);
    }

    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

GAUSS-QUADRATURE METHOD programe in FORTRAN77

!          GAUSS-QUADRATURE METHOD
           DIMENSION W(10),Z(10)
           WRITE(*,*)'GIVE THE LIMITS OF INTEGRATION'
           READ(*,*)TL,TU
           WRITE(*,*)'THE NUMBER POINTS USED FOR CALCULATION'
           READ(*,*)N
           P=(TU-TL)/2
           Q=(TU+TL)/2
           IF(N.EQ.2)THEN
           OPEN(2,FILE='GQUAD2.DAT',STATUS='OLD')
           DO I=1,N
           READ(2,10)W(I),Z(I)
10         FORMAT(5X,F7.5,5X,F8.5)
           WRITE(*,*)W(I),Z(I)
           END DO
           ELSE
            IF(N.EQ.3)THEN
            OPEN(3,FILE='GQUAD3.DAT',STATUS='OLD')
            DO I=1,N
            READ(3,10)W(I),Z(I)
            WRITE(*,*)W(I),Z(I)
            END DO
            ELSE
             IF(N.EQ.4)THEN
             OPEN(4,FILE='GQUAD4.DAT',STATUS='OLD')
             DO I=1,N
             READ(4,10)W(I),Z(I)
             WRITE(*,*)W(I),Z(I)
             END DO
             ELSE
              IF(N.EQ.5)THEN
              OPEN(5,FILE='GQUAD5.DAT',STATUS='OLD')
              DO I=1,N
              READ(5,10)W(I),Z(I)
              WRITE(*,*)W(I),Z(I)
              END DO
              ELSE
               IF(N.EQ.6)THEN
               OPEN(6,FILE='GQUAD6.DAT',STATUS='OLD')
               DO I=1,N
              READ(6,10)W(I),Z(I)
              WRITE(*,*)W(I),Z(I)
              END DO
              ELSE
              END IF
              END IF
              END IF
              END IF
              END IF
           SUM=0
           DO I=1,N
           SUM=SUM+W(I)*F(P*Z(I)+Q)
           WRITE(*,*)SUM
           END DO
           VALUE=(TU-TL)*SUM/2
           WRITE(*,*)TU,TL,VALUE
           STOP
           END
           
           
           FUNCTION F(X)
           F=X*EXP(2*X)
           RETURN
           END              
           

Arrays

Arrays can store a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Numbers(1)Numbers(2)Numbers(3)Numbers(4)
Arrays can be one- dimensional (like vectors), two-dimensional (like matrices) and Fortran allows you to create up to 7-dimensional arrays.

Declaring Arrays

Arrays are declared with the dimension attribute.
For example, to declare a one-dimensional array named number, of real numbers containing 5 elements, you write,
real, dimension(5) :: numbers
The individual elements of arrays are referenced by specifying their subscripts. The first element of an array has a subscript of one. The array numbers contains five real variables –numbers(1), numbers(2), numbers(3), numbers(4), and numbers(5).
To create a 5 x 5 two-dimensional array of integers named matrix, you write −
integer, dimension (5,5) :: matrix  
You can also declare an array with some explicit lower bound, for example −
real, dimension(2:6) :: numbers
integer, dimension (-3:2,0:4) :: matrix  

Assigning Values

You can either assign values to individual members, like,
numbers(1) = 2.0
or, you can use a loop,
do i  =1,5
   numbers(i) = i * 2.0
end do
One-dimensional array elements can be directly assigned values using a short hand symbol, called array constructor, like,
numbers = (/1.5, 3.2,4.5,0.9,7.2 /)
please note that there are no spaces allowed between the brackets ‘( ‘and the back slash ‘/’

Mixing variable types

Mixing variable types

Exercise 3.1

Copy   divide.f95 from Downloads
Make sure you understand the following program thoroughly!
  program divide
   implicit none
   integer  :: x
   real  :: y
   x  = 1
   y = x/3
   print  *, y
   end program divide
Run it. This program produces the following output:
  0.00000
Something odd is happening. The problem is the line:
  y=x/3
FORTRAN evaluates the right  hand side of the assignment first using integer arithmetic, because both x and 3 are integer. 1 divided by 3 cannot be stored as an integer, and so the value 0 is returned. The result, 0, is then converted to a real number and the assigned to y.
Replace the line in program divide
  
  x = 1       
by  
  
  x = 10
Your output should now be:
  3.00000
Can you see what is happening? FORTRAN is keeping the integer part of the answer and throwing the rest away.
To get over this problem, we have to signal to FORTRAN that we want it to calculate the right hand side of the expression using real arithmetic. If we want  to keep x as integer data type, we could re-write our expression as follows:
                y=x/3.0
The presence of a real number on the right hand side causes the right hand side of the expression to be evaluated using floating point arithmetic.
Actually, the problem is even more complicated! Where we have an expression like
                y=x * ((2**i)/3)
where x and y are real and i is integer, FORTRAN computes the result in stages:
First it calculates (2**i)/3 and evaluates it as an integer number, then multiplies the result by x and evaluates it as real.

Exercise 3.2

Copy check.f95 to your filestore.
    
  program check
    !Integer and real arithmetic
    implicit none
    real :: x,y
    integer i
    x=2.0
    i=2
    y=x*((2**i)/3)
    print *,y
    y=x*((2.0**i)/3)
    print *,y
    end program check 
   
… and examine its output. Make sure you understand why this is happening.

The do loop

Unless we are able to re-execute code, we might as well use a calculator… Now we start to take advantage of the power of the computer.

Exercise 3.3

Copy program loop.f95
      
  program  loop
  implicit none     
    integer  :: i
    do  i=0,20
     print  *,i
    end  do
    end  program loop
  
  
Run the program. It prints out the numbers from 0 to 20 in steps of 1.
Note:
  • is called a loop counter. In this example, it has a start value of zero.
  • All the statements within the do and end do are executed. In this example there is just the one statement, ie print.
  • Each time the statements are executed, the loop counter, i, is incremented by 1.
  • When the value of i is 20, the loop terminates, and the program resumes after the end do.
Change the do statement in program loop as follows:
  do i = 50,70,2
Run the program. What happens?
The third argument in the do statement, is the increment step.  If omitted, the value is taken as 1.
Loops can also decrement: try this
 
  do i = 5,-5,-2
 

Exercise 3.4

Using a do loop to generate integer values of x between –10 and 10 in steps of 1, write a program that constructs a table of values of
  y = 1.0/x 
What happened when x had the value zero? Use an if, end if to test for the condition that gives the incorrect value, and print out an appropriate message. Compare your result with divbyzero.f95.
Division by zero
is one of the commonest reasons for a program to fail

Nested Do Loops

We want to construct a table of values for z where
  z = xy           
for values of          x in the range 1 to 2 in steps of 0.5 and
y in the range 1 to 2 in steps of 0.5
Work through the next exercise which illustrates this:

Exercise 3.5

Copy program xytab.f95 to your filespace.
  program  xytab
    implicit none
    !constructs a table of z=x/y for values of x from 1 to 2 and 
    !y from 1 to 4 in  steps of .5
    real         ::   x, y, z 
    print *, '           x           y           z'
    do  x = 1,2
     do y = 1,4,0.5
      z = x/y
      print *, x,y,z
     end do
    end  do
    end  program xytab
  
Examine its output. Notice the use of the first print  to give a heading to the table.

Using loops to do summation

Earlier on, we discussed the idea of assignments.
  x = 1.0
means store the value 1.0 in the memory location called x.
If we had the following code:
  x = 1.0
  x = x +  1.0
  print *, x
        
Can you guess what value would be printed out for x?
The answer would be 2.0.
Really important!
Bearing in mind the definition of an assignment,  the statement
  x = x  + 1.0
        
means “add 1.0 to the value currently stored in memory location x and then store the result in memory location x”.

Exercise 3.6

Copy file increment.f95 to your file space and examine its output.
    program increment
    implicit none
    integer :: i
    real :: x
    x = 1.0
    do i=1,10
     x = x + 1.0
     print *, i,x
    end do
    end program increment
  • Note carefully that we have set the initial value of x outside of the do loop. Why have we done this? If you aren't sure – change the code to put the line x = 1.0 inside the loop – then examine the output.
  • It is important to understand that if we use constructions such as x = x + 1.0, then it is vital to initialise x to some value. If we don't, it is possible that the value might be set to any random number. Run the program, make a note of the final value of x then put an exclamation mark in front of the x = 1.0 statement and run the program again.

Exercise 3.7

Edit the line x = x + 1.0 in program increment.f95, and change it to x = x * i. Re-run the program and examine the output. What is significant mathematically about the sequence of numbers that has been generated?

OLDER POST

Head Constable (Ministerial)

Head Constable (Ministerial) Apply Now   Notification