C++

count number of characters and lines in a file

#include <iostream.h>
#include <fstream.h>

int main () {
  ifstream f1;
  char c;
  int numchars, numlines;

  f1.open("test");

  numchars = 0;
  numlines = 0;
  f1.get(c);
  while (f1) {
    while (f1 && c != '\n') {
      numchars = numchars + 1;
      f1.get(c);
    }
    numlines = numlines + 1;
    f1.get(c);
  }
  cout << "The file has " << numlines << " lines and " 
    << numchars << " characters" << endl;
  return(0);
} 

better algorithm for multiplication

 
#include <iostream.h>

// Idea of the Russian Peasant Method (as old as 1700 B.C.)
// x * n = 2x * (n/2) if n even
//       = x + x * (n-1) if n odd

int fastmult (int x, int y) {
  int result;
  result = 0;
  while (y != 0) {
    if (y % 2 == 0) {
      x = 2*x;
      y = y/2;
    }
    else {
      result = result + x;
      y = y-1;
    }
  }
  return(result);
}

int main () {
  int x, y;
  cout << "Enter two natural numbers: ";
  cin >> x >> y;
  cout << x << " * " << y << " = " << fastmult(x,y) << endl;
  return(0);
}

 

 

Multiplication Using Addition

#include <iostream.h>

int mult (int x, int y) {
  int result;
  result = 0;
  while (y != 0) {
    result = result + x;
   y = y - 1;
  }
  return(result);
}

int main () {
  int x, y;
  cout << "Enter two natural numbers: ";
  cin >> x >> y;
  cout << x << " * " << y << " = " << mult(x,y) << endl;
  return(0);
}


A Program to Calculate Factorial of a Number

#include <iostream.h>

int fact (int i) {
  int result = 1;
  while (i > 0) {
    result = result * i;
    i = i-1;
  }
  return(result);
}

int main () {
  int n;
  cout << "Enter a natural number: ";
  cin >> n;
  while (n < 0) {
    cout << "Please re-enter: ";
    cin >> n;
  }
  cout << n << "! = " << fact(n) << endl;
  return(0);
}

No comments:

Comment

Comment Box is loading comments...