Sunday 4 May 2014

Allocating Memory with malloc

Allocating Memory with malloc

[This section corresponds to parts of K&R Secs. 5.4, 5.6, 6.5, and 7.8.5]
A problem with many simple programs, including in particular little teaching programs such as we've been writing so far, is that they tend to use fixed-size arrays which may or may not be big enough. We have an array of 100 ints for the numbers which the user enters and wishes to find the average of--what if the user enters 101 numbers? We have an array of 100 chars which we pass to getline to receive the user's input--what if the user types a line of 200 characters? If we're lucky, the relevant parts of the program check how much of an array they've used, and print an error message or otherwise gracefully abort before overflowing the array. If we're not so lucky, a program may sail off the end of an array, overwriting other data and behaving quite badly. In either case, the user doesn't get his job done. How can we avoid the restrictions of fixed-size arrays?
The answers all involve the standard library function malloc. Very simply, malloc returns a pointer to n bytes of memory which we can do anything we want to with. If we didn't want to read a line of input into a fixed-size array, we could use malloc, instead. Here's the first step:
 #include <stdlib.h>

 char *line;
 int linelen = 100;
 line = malloc(linelen);
 /* incomplete -- malloc's return value not checked */
 getline(line, linelen);
malloc is declared in <stdlib.h>, so we #include that header in any program that calls malloc. A ``byte'' in C is, by definition, an amount of storage suitable for storing one character, so the above invocation ofmalloc gives us exactly as many chars as we ask for. We could illustrate the resulting pointer like this:

The 100 bytes of memory (not all of which are shown) pointed to by line are those allocated by malloc. (They are brand-new memory, conceptually a bit different from the memory which the compiler arranges to have allocated automatically for our conventional variables. The 100 boxes in the figure don't have a name next to them, because they're not storage for a variable we've declared.)

As a second example, we might have occasion to allocate a piece of memory, and to copy a string into it with strcpy:
 char *p = malloc(15);
 /* incomplete -- malloc's return value not checked */
 strcpy(p, "Hello, world!");

When copying strings, remember that all strings have a terminating \0 character. If you use strlen to count the characters in a string for you, that count will not include the trailing \0, so you must add one before callingmalloc:
 char *somestring, *copy;
 ...
 copy = malloc(strlen(somestring) + 1);  /* +1 for \0 */
 /* incomplete -- malloc's return value not checked */
 strcpy(copy, somestring);

What if we're not allocating characters, but integers? If we want to allocate 100 ints, how many bytes is that? If we know how big ints are on our machine (i.e. depending on whether we're using a 16- or 32-bit machine) we could try to compute it ourselves, but it's much safer and more portable to let C compute it for us. C has a sizeof operator, which computes the size, in bytes, of a variable or type. It's just what we need when callingmalloc. To allocate space for 100 ints, we could call
 int *ip = malloc(100 * sizeof(int));
The use of the sizeof operator tends to look like a function call, but it's really an operator, and it does its work at compile time.

Since we can use array indexing syntax on pointers, we can treat a pointer variable after a call to malloc almost exactly as if it were an array. In particular, after the above call to malloc initializes ip to point at storage for 100 ints, we can access ip[0]ip[1], ... up to ip[99]. This way, we can get the effect of an array even if we don't know until run time how big the ``array'' should be. (In a later section we'll see how we might deal with the case where we're not even sure at the point we begin using it how big an ``array'' will eventually have to be.)
Our examples so far have all had a significant omission: they have not checked malloc's return value. Obviously, no real computer has an infinite amount of memory available, so there is no guarantee that malloc will be able to give us as much memory as we ask for. If we call malloc(100000000), or if we call malloc(10) 10,000,000 times, we're probably going to run out of memory.
When malloc is unable to allocate the requested memory, it returns a null pointer. A null pointer, remember, points definitively nowhere. It's a ``not a pointer'' marker; it's not a pointer you can use. (As we said in section 9.4, a null pointer can be used as a failure return from a function that returns pointers, and malloc is a perfect example.) Therefore, whenever you call malloc, it's vital to check the returned pointer before using it! If you call malloc, and it returns a null pointer, and you go off and use that null pointer as if it pointed somewhere, your program probably won't last long. Instead, a program should immediately check for a null pointer, and if it receives one, it should at the very least print an error message and exit, or perhaps figure out some way of proceeding without the memory it asked for. But it cannot go on to use the null pointer it got back from malloc in any way, because that null pointer by definition points nowhere. (``It cannot use a null pointer in any way'' means that the program cannot use the * or [] operators on such a pointer value, or pass it to any function that expects a valid pointer.)
A call to malloc, with an error check, typically looks something like this:
 int *ip = malloc(100 * sizeof(int));
 if(ip == NULL)
  {
  printf("out of memory\n");
  exit or return
  }
After printing the error message, this code should return to its caller, or exit from the program entirely; it cannot proceed with the code that would have used ip.

Of course, in our examples so far, we've still limited ourselves to ``fixed size'' regions of memory, because we've been calling malloc with fixed arguments like 10 or 100. (Our call to getline is still limited to 100-character lines, or whatever number we set the linelen variable to; our ip variable still points at only 100 ints.) However, since the sizes are now values which can in principle be determined at run-time, we've at least moved beyond having to recompile the program (with a bigger array) to accommodate longer lines, and with a little more work, we could arrange that the ``arrays'' automatically grew to be as large as required. (For example, we could write something like getline which could read the longest input line actually seen.) We'll begin to explore this possibility in a later section.

Reading the Command Line


We've mentioned several times that a program is rarely useful if it does exactly the same thing every time you run it. Another way of giving a program some variable input to work on is by invoking it with command line arguments.
(We should probably admit that command line user interfaces are a bit old-fashioned, and currently somewhat out of favor. If you've used Unix or MS-DOS, you know what a command line is, but if your experience is confined to the Macintosh or Microsoft Windows or some other Graphical User Interface, you may never have seen a command line. In fact, if you're learning C on a Mac or under Windows, it can be tricky to give your program a command line at all. Think C for the Macintosh provides a way; I'm not sure about other compilers. If your compilation environment doesn't provide an easy way of simulating an old-fashioned command line, you may skip this chapter.)
C's model of the command line is that it consists of a sequence of words, typically separated by whitespace. Your main program can receive these words as an array of strings, one word per string. In fact, the C run-time startup code is always willing to pass you this array, and all you have to do to receive it is to declare main as accepting two parameters, like this:
 int main(int argc, char *argv[])
 {
 ...
 }
When main is called, argc will be a count of the number of command-line arguments, and argv will be an array (``vector'') of the arguments themselves. Since each word is a string which is represented as a pointer-to-charargv is an array-of-pointers-to-char. Since we are not defining the argv array, but merely declaring a parameter which references an array somewhere else (namely, in main's caller, the run-time startup code), we do not have to supply an array dimension for argv. (Actually, since functions never receive arrays as parameters in C, argv can also be thought of as a pointer-to-pointer-to-char, or char **. But multidimensional arrays and pointers to pointers can be confusing, and we haven't covered them, so we'll talk about argv as if it were an array.) (Also, there's nothing magic about the names argc and argv. You can give main's two parameters any names you like, as long as they have the appropriate types. The names argc and argv are traditional.)

The first program to write when playing with argc and argv is one which simply prints its arguments:
#include <stdio.h>

main(int argc, char *argv[])
{
int i;

for(i = 0; i < argc; i++)
 printf("arg %d: %s\n", i, argv[i]);
return 0;
}
(This program is essentially the Unix or MS-DOS echo command.)

If you run this program, you'll discover that the set of ``words'' making up the command line includes the command you typed to invoke your program (that is, the name of your program). In other words, argv[0] typically points to the name of your program, and argv[1] is the first argument.
There are no hard-and-fast rules for how a program should interpret its command line. There is one set of conventions for Unix, another for MS-DOS, another for VMS. Typically you'll loop over the arguments, perhaps treating some as option flags and others as actual arguments (input files, etc.), interpreting or acting on each one. Since each argument is a string, you'll have to use strcmp or the like to match arguments against any patterns you might be looking for. Remember that argc contains the number of words on the command line, and that argv[0] is the command name, so if argc is 1, there are no arguments to inspect. (You'll never want to look atargv[i], for i >= argc, because it will be a null or invalid pointer.)
As another example, also illustrating fopen and the file I/O techniques of the previous chapter, here is a program which copies one or more input files to its standard output. Since ``standard output'' is usually the screen by default, this is therefore a useful program for displaying files. (It's analogous to the obscurely-named Unix cat command, and to the MS-DOS type command.) You might also want to compare this program to the character-copying program of section 6.2.
#include <stdio.h>

main(int argc, char *argv[])
{
int i;
FILE *fp;
int c;

for(i = 1; i < argc; i++)
 {
 fp = fopen(argv[i], "r");
 if(fp == NULL)
  {
  fprintf(stderr, "cat: can't open %s\n", argv[i]);
  continue;
  }

 while((c = getc(fp)) != EOF)
  putchar(c);

 fclose(fp);
 }

return 0;
}
As a historical note, the Unix cat program is so named because it can be used to concatenate two files together, like this:
 cat a b > c
This illustrates why it's a good idea to print error messages to stderr, so that they don't get redirected. The ``can't open file'' message in this example also includes the name of the program as well as the name of the file.

Yet another piece of information which it's usually appropriate to include in error messages is the reason why the operation failed, if known. For operating system problems, such as inability to open a file, a code indicating the error is often stored in the global variable errno. The standard library function strerror will convert an errno value to a human-readable error message string. Therefore, an even more informative error message printout would be
 fp = fopen(argv[i], "r");
 if(fp == NULL)
  fprintf(stderr, "cat: can't open %s: %s\n",
    argv[i], strerror(errno));
If you use code like this, you can #include <errno.h> to get the declaration for errno, and <string.h> to get the declaration for strerror().

Friday 2 May 2014

Point 3D Java

class Point3d extends Point2d {
 private double z;

 public Point3d( int px, int py, int pz) {
    super (px, py);

    z = pz;
   }

 public Point3d () {
    super ();
    z = 0;

    // perhaps a better method would be to replace the above code with
    //     this (0, 0, 0);
   }

 public Point3d(Point3d pt) {
    super ((Point2d) pt);
    z = pt.getZ();

    // perhaps a better method would be to replace the above code with
    //     this (pt.getX(), pt.getY(), pt.getZ());
   }

 public void setZ(double pz) {
    dprint("setZ(): Changing value of z from " + z + " to " + pz);
    z = pz;
   }

 public double getZ () {
    return z;
   }

 public void setXYZ(double px, double py, double pz) {
    setXY(px, py);
    setZ(pz);
   }

 public double distanceFrom (Point3d pt) {
    double xyDistance = super.distanceFrom ((Point2d) pt);
    double dz = Math.abs (z - pt.getZ()); 
    dprint ("distanceFrom(): deltaZ = " + dz);

    return Math.sqrt((xyDistance * xyDistance) + (dz * dz));
   }

 public double distanceFromOrigin () {
    return distanceFrom (new Point3d ( ));
   }

 public String toStringForZ() {
    String str =  ", " + z;
    return str;
   }

 public String toString() {
    String str = toStringForXY() + toStringForZ() + ")";
    return str;
   }

 
 public static void main (String[] args) {
    Point3d pt1 = new Point3d ();
    System.out.println ("pt1 = " + pt1);

    Point3d pt2 = new Point3d (1,2,3);
    System.out.println ("pt2 = " + pt2);

    pt1.setDebug(true);  // turn on debugging statements
    // for pt1
    System.out.println ("Distance from " + pt2 + " to " + pt1 +
   " is " + pt2.distanceFrom(pt1));

    System.out.println ("Distance from " + pt1 + " to the origin (0, 0) is " +
   pt1.distanceFromOrigin());

    System.out.println ("Distance from " + pt2 + " to the origin (0, 0) is " +
   pt2.distanceFromOrigin());

    pt1.setXYZ(3, 5, 7);
    System.out.println ("pt1 = " + pt1);

    pt2.setXYZ(-3, -5, -7);
    System.out.println ("pt2 = " + pt2);

    System.out.println ("Distance from " + pt1 + " to " + pt2 +
   " is " + pt1.distanceFrom(pt2));

    System.out.println ("Distance from " + pt2 + " to " + pt1 +
   " is " + pt2.distanceFrom(pt1));

    pt1.setDebug(false);    // turning off debugging 
       // statements for pt1

    System.out.println ("Distance from " + pt1 + " to the origin (0, 0) is " +
   pt1.distanceFromOrigin());

    System.out.println ("Distance from " + pt2 + " to the origin (0, 0) is " +
   pt2.distanceFromOrigin());


   }
}

Divide By Zero Exception in Java

import java.io.*;

// This program shows a stack track that occurs when java
// encounters a terminal error when running a program.

public class DivBy0
{

 public static void funct1 ()
 {
  System.out.println ("Inside funct1()");

  funct2();
 }

 public static void main (String[] args)
 {
  int val;

  System.out.println ("Inside main()");

  funct1();

 }

 public static void funct2 ()
 {
  System.out.println ("Inside funct2()");
  int i, j, k;

  i = 10;
  j = 0;

  k = i/j;
 }

}

My File Reader

import java.io.*;
import java.util.*;

public class MyFileReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new FileReader ("MyFileReader.txt"));

  s1 = br.readLine();

  System.out.println ("The line is " + s1);
  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}

Keyboard Reader Java

import java.io.*;
import java.util.*;

public class KeyboardReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  double num1, num2, product;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
   System.in));

  System.out.println ("Enter a line of input");

  s1 = br.readLine();

  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}

Tuesday 22 April 2014

C Program to Find Largest Number Using Dynamic Memory Allocation

 Dynamic Memory Allocation

In this program, calloc() function is used to allocate the memory dynamically. Depending upon the number of elements, the required size is allocated which prevents the wastage of memory. If no memory is allocated, error is displayed and the program is terminated.


Source Code to Find Largest Element Using Dynamic Memory Allocation

#include <stdio.h>
#include <stdlib.h>
int main(){
    int i,n;
    float *data;
    printf("Enter total number of elements(1 to 100): ");
    scanf("%d",&n);
    data=(float*)calloc(n,sizeof(float));  /* Allocates the memory for 'n' elements */
    if(data==NULL)
    {
        printf("Error!!! memory not allocated.");
        exit(0);
    }
    printf("\n");
    for(i=0;i<n;++i)  /* Stores number entered by user. */
    {
       printf("Enter Number %d: ",i+1);
       scanf("%f",data+i);
    }
    for(i=1;i<n;++i)  /* Loop to store largest number at address data */
    {
       if(*data<*(data+i)) /* Change < to > if you want to find smallest number */
           *data=*(data+i);
    }
    printf("Largest element = %.2f",*data);
    return 0;
}


Output


Largest element of an array output

C Program to Find Size of int, float, double and char of Your System

The size of a character is always 1 byte but, size of int, float and double variables differs from system to system. This program will compute the size of int, float, double and char of you system using sizeof operator. The syntax of size of operator is:


temp = sizeof(operand);
/* Here, temp is a variable of type integer,i.e, sizeof() operator 
   returns integer value. */

Source Code

/* This program computes the size of variable using sizeof operator.*/

#include <stdio.h>
int main(){
    int a;
    float b;
    double c;
    char d;
    printf("Size of int: %d bytes\n",sizeof(a));
    printf("Size of float: %d bytes\n",sizeof(b));
    printf("Size of double: %d bytes\n",sizeof(c));
    printf("Size of char: %d byte\n",sizeof(d));
    return 0;
}
Output

Size of int: 4 bytes
Size of float: 4 bytes
Size of double: 8 bytes
Size of char: 1 byte
Note: You may get different output depending upon your system.

Explanation

In this program, 4 variables a, b, c and d are declared of type int, float, double and char respectively. Then, the size of these variables is computed using sizeof operator and displayed.

Wednesday 16 April 2014

Compare Strings in Java

Following example compares two strings by using st.compareTo (string) ,
str.compareToIgnoreCase(String) and str.compareTo(object string) of string
class and returns the ascii difference of first odd characters of compared
strings .

public class StringCompareEmp{
   public static void main(String args[]){
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;

  System.out.println( str.compareTo(anotherString) );
 System.out.println( str.compareToIgnoreCase(anotherString) );   
  System.out.println( str.compareTo(objStr.toString()));
   }
}

How do I present data in AVL grid in ABAP? If I have a list of table results from a SQL query, how do I show this data in AVL?



To display ALV LISTS the function module used are :


REUSE_ALV_LIST_DISPLAY "For Normal LIST


REUSE_ALV_HIERARCHICAL_LIST_DISPLAY "For Hierarchical LIST


To display ALV GRID the function module used are :


REUSE_ALV_GRID_DISPLAY . "For GRID display


The most important component of the ALV is the FIELDCATALOG which is of


TYPE SLIS_T_FIEDLCAT_ALV

Tuesday 15 April 2014

Check the number positive or negative

#include <stdio.h>
int main()
{
    float num;
    printf("Enter a number: ");
    scanf("%f",&num);
    if (num<=0)
    {
        if (num==0)
          printf("You entered zero.");
        else
          printf("%.2f is negative.",num);
    }
    else
      printf("%.2f is positive.",num);
    return 0;
}

One Days To Go .. Yess You can Watch IPL Online For Free Live Streaming

Compute Square root Using Newtons Method

#include <iostream.h>
#include <math.h>

float asqrt (float x, float precision) {
  float guess;

  guess = 1.0;
  while (fabs(guess*guess-x) >= precision) {
    guess = 0.5 * (guess + (x / guess));
  }
  return (guess);
}

int main () {
  float x, precision; 
  cout << "Enter a real number and the precision: ";
  cin >> x >> precision;
  cout << "sqrt(" << x << ") is almost " << asqrt(x,precision) << endl;
  return(0);
}

Call By Valuse and Call By reference

#include <iostream.h>

int f1 (int, int, int);
int f2 (int&, int&, int&);
int f3 (int, int&, int);

void main () {
  int i, j, k;

  i=1;
  j=2;
  k=3;

  cout << endl;
  cout << "Initial values of i, j, and k are: " 
    << i << ", " << j << ", and " << k << endl << endl;
  cout << "f1(i,j,k) = " << f1(i,j,k) << endl;
  cout << "Values of i, j, and k after the call to f1 are: " 
    << i << ", " << j << ", and " << k << endl << endl;
  cout << "f2(i,j,k) = " << f2(i,j,k) << endl;
  cout << "Values of i, j, and k after the call to f2 are: " 
    << i << ", " << j << ", and " << k << endl << endl;
  cout << "f3(i,j,k) = " << f3(i,j,k) << endl;
  cout << "Values of i, j, and k after the call to f3 are: " 
    << i << ", " << j << ", and " << k << endl;
}

int f1 (int x, int y, int z) {
  x=x+5;
  y=y+5;
  z=z+5;
  return(x+y+z);
}

int f2 (int& x, int& y, int& z) {
  x=x+5;
  y=y+5;
  z=z+5;
  return(x+y+z);
}

int f3 (int x, int& y, int z) {
  x=x+5;
  y=y+5;
  z=z+5;
  return(x+y+z);
}

Calender

#include <iostream.h>
#include <stdlib.h>
#include <iomanip.h>

typedef int Bool;

// converts 0 to 'S', 1 to 'M', etc
char whatDay (int); 

// not very good check for leap years
Bool isLeapYear (int); 

// takes the number of the month, a flag saying whether year is leap 
int numOfDaysInMonth (int,Bool); 

void printHeader (int); 

// takes the number of the month, and the first day, prints, and updates
// the first day of the next month
void printMonth (int, int&); 

// prints the specified amount of spaces
void skip (int);

// prints leading spaces in monthly calendar
void skipToDay (int);

// terminates program in case of unrecoverable errors
void disaster (); 

void main () {

  int year, firstDayInCurrentMonth;
  Bool leap;
  int currentMonth = 1; // start at Jan
  int numDays;

  cout << "What year do you want a calendar for? ";
  cin >> year;
  cout << "What day of the week does January 1 fall on?" << endl;
  cout << "(Enter 0 for Sunday, 1 for Monday, etc.) ";
  cin >> firstDayInCurrentMonth;

  leap = isLeapYear(year);
  skip(9); cout << year << endl;

  while (currentMonth <= 12) {
    numDays = numOfDaysInMonth(currentMonth,leap);
    printHeader(currentMonth);
    printMonth(numDays, firstDayInCurrentMonth);
    cout << endl << endl << endl;
    currentMonth = currentMonth + 1;
  }
  cout << endl;
}

void disaster () {
  cout << "Disaster! Exiting ..." << endl;
  exit (-1);
}

void skip (int i) {
  while (i > 0) {
    cout << " ";
    i = i - 1;
  }
}

char whatDay (int d) {
  if (d == 0) return('S');
  else if (d == 1) return('M');
  else if (d == 2) return('T');
  else if (d == 3) return('W');
  else if (d == 4) return('T');
  else if (d == 5) return('F');
  else if (d == 6) return('S');
  else disaster();
}

Bool isLeapYear (int y) {
  return ((y % 4) == 0); // simplified
}

void printHeader (int m) {

  if (m == 1) { skip(7); cout << "January" << endl; }
  else if (m == 2) { skip(7); cout << "February" << endl; } 
  else if (m == 3) { skip(7); cout << "March" << endl; }
  else if (m == 4) { skip(7); cout << "April" << endl; }
  else if (m == 5) { skip(7); cout << "May" << endl; }
  else if (m == 6) { skip(7); cout << "June" << endl; }
  else if (m == 7) { skip(7); cout << "July" << endl; }
  else if (m == 8) { skip(7); cout << "August" << endl; }
  else if (m == 9) { skip(7); cout << "September" << endl; }
  else if (m == 10) { skip(7); cout << "October" << endl; }
  else if (m == 11) { skip(7); cout << "November" << endl; }
  else if (m == 12) { skip(7); cout << "December" << endl; }
  else disaster();

  cout << " S  M  T  W  T  F  S" << endl;
  cout << "____________________" << endl;
}

int numOfDaysInMonth (int m, Bool leap) {
  if (m == 1) return(31);
  else if (m == 2) if (leap) return(29); else return(28);
  else if (m == 3) return(31);
  else if (m == 4) return(30);
  else if (m == 5) return(31);
  else if (m == 6) return(30);
  else if (m == 7) return(31);
  else if (m == 8) return(31);
  else if (m == 9) return(30);
  else if (m == 10) return(31);
  else if (m == 11) return(30);
  else if (m == 12) return(31);
  else disaster();
}

void skipToDay (int d) {
  skip(3*d);
}

void printMonth (int numDays, int& weekDay) {
  int day = 1;

  skipToDay(weekDay);
  while (day <= numDays) {
    cout << setw(2) << day << " ";
    if (weekDay == 6) {
      cout << endl;
      weekDay = 0;
    }
    else weekDay = weekDay + 1;
    day = day + 1;
  }
}

Grade

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

typedef int Bool;

const Bool TRUE = 1;
const Bool FALSE = 0;

char printableBool (Bool i) {
  if (i==FALSE) 
    return 'F';
  else return 'T';
}


int main () {

  ifstream f1, f2, f3check;
  ofstream f3;
  f1.open("exam");
  if (!f1) {
    cout << "Cannot open file exam" << endl;
    return 1;
  }
  f2.open("key");
  if (!f2) {
    cout << "Cannot open file key" << endl;
    return 1;
  }
  f3check.open("result");
  if (f3check) {
    cout << "File result already exists" << endl;
    return 1;
  }
  f3.open("result");
  if (!f3) {
    cout << "Cannot open file result" << endl;
    return 1;
  }

  int runningSum;
  int ans, key, score;

  runningSum = 0;

  f1 >> ans;
  if (!f1) {
    cout << "Error reading from file exam" << endl;
    return 1;
  }
  f2 >> key; 
  if (!f1) {
    cout << "Error reading from file key" << endl;
    return 1;
  }
  if (ans == key) {
    runningSum = runningSum + 25;
    score = TRUE;
  }
  else score = FALSE;
  f3 << printableBool(score) << endl;
  if (!f3) {
    cout << "Error writing to file result" << endl;
    return 1;
  }

  f1 >> ans;
  if (!f1) {
    cout << "Error reading from file exam" << endl;
    return 1;
  }
  f2 >> key; 
  if (!f1) {
    cout << "Error reading from file key" << endl;
    return 1;
  }
  if (ans == key) {
    runningSum = runningSum + 25;
    score = TRUE;
  }
  else score = FALSE;
  f3 << printableBool(score) << endl;
  if (!f3) {
    cout << "Error writing to file result" << endl;
    return 1;
  }

  f1 >> ans;
  if (!f1) {
    cout << "Error reading from file exam" << endl;
    return 1;
  }
  f2 >> key; 
  if (!f1) {
    cout << "Error reading from file key" << endl;
    return 1;
  }
  if (ans == key) {
    runningSum = runningSum + 25;
    score = TRUE;
  }
  else score = FALSE;
  f3 << printableBool(score) << endl;
  if (!f3) {
    cout << "Error writing to file result" << endl;
    return 1;
  }

  f1 >> ans;
  if (!f1) {
    cout << "Error reading from file exam" << endl;
    return 1;
  }
  f2 >> key; 
  if (!f1) {
    cout << "Error reading from file key" << endl;
    return 1;
  }
  if (ans == key) {
    runningSum = runningSum + 25;
    score = TRUE;
  }
  else score = FALSE;
  f3 << printableBool(score) << endl;
  if (!f3) {
    cout << "Error writing to file result" << endl;
    return 1;
  }

  f3 << endl << runningSum << endl;  
  
}

Merge Sort In C

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

int main () {
  ifstream f1, f2;
  ofstream f3;
  int i,j;

  f1.open("n1");
  f2.open("n2");
  f3.open("n1n2");
  
  f1 >> i;
  f2 >> j;
  while (f1 && f2) {
    if (i < j) {
      while (i < j && f1 && f3) {
 f3 << i << endl;
 f1 >> i;
      }
    }
    else {
      while (j <= i && f2 && f3) {
 f3 << j << endl;
 f2 >> j;
      }
    }
  }
  while (f1) {
    f3 << i << endl;
    f1 >> i;
  }
  while (f2) {
    f3 << j << endl;
    f2 >> j;
  }
  return (0);
}

Monday 14 April 2014

Average Of Two Numbers in C++

#include <fstream.h>

void main () {

ifstream f1;
ofstream f2;
f1.open("scores.96");
f2.open("final.96");

int s1, s2, s3;
float w1, w2, w3;

f1 >> s1 >> w1;
f1 >> s2 >> w2;
f1 >> s3 >> w3;
f2 << (s1*w1+s2*w2+s3*w3);

}

You Can See Live Streaming Of IPL here :

Decimal to binary conversion

Decimal to binary conversion

C program to convert decimal to binary: c language code to convert an integer from decimal number system(base-10) to binary number system(base-2). Size of integer is assumed to be 32 bits. We use bitwise operators to perform the desired task. We right shift the original number by 31, 30, 29, ..., 1, 0 bits using a loop and bitwise AND the number obtained with 1(one), if the result is 1 then that bit is 1 otherwise it is 0(zero).

C programming code

#include <stdio.h>

int main()
{
  int n, c, k;

  printf("Enter an integer in decimal number system\n");
  scanf("%d", &n);

  printf("%d in binary number system is:\n", n);

  for (c = 31; c >= 0; c--)
  {
    k = n >> c;

    if (k & 1)
      printf("1");
    else
      printf("0");
  }

  printf("\n");

  return 0;
}

OutPut Of Program:
Decimal to binary c program

Sunday 13 April 2014

programing in c - 1


Introduction to c programing and data structure programming




#include <stdio.h>

int main()
{
  int n, i,  c, a = 1;

  printf("Enter the number of rows of Floyd's triangle to print\n");
  scanf("%d", &n);

  for (i = 1; i <= n; i++)
  {
    for (c = 1; c <= i; c++)
    {
      printf("%d ",a);
      a++;
    }
    printf("\n");
  }

  return 0;
}












Pascle Triangle

public class Pascal
{
int i,j,k,l=1;
void PrintPascal(int n)
{
for (i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(k=0;k<i;k++)
{
System.out.print(i +" " );
}
System.out.println();
}
}
public static void main (String[] args)
{
Pascal p=new Pascal();
p.PrintPascal(5);
}
}
OUTPUT :  

    1
   2 2
  3 3 3
 4 4 4 4
5 5 5 5 5

Batting and Bowling statistics

BATTING STATISTICS

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

     
     
     
     
     

BOWLING STATISTICS



2013 STANDINGS

TeamMatWonLostTiedN/RNet RRForAgainstPts
CSK16115000.532461/303.52310/305.122
MI16115000.4412514/318.12350/315.022
RR16106000.3222405/310.52326/313.420
SH16106000.0032166/308.52206/314.420
RCB1697000.4572571/301.02451/303.118
KXIP1688000.2262428/305.22417/312.516
KKR1661000-0.0952290/313.42316/313.112
PWI1641200-1.0062262/318.42519/310.58
DD1631300-0.8482234/314.52436/306.46

Comment

Comment Box is loading comments...