How to Waste Your Time While Programming


Fun ways to kill off coding productivity:

  • Use lots of spaces.
  • Align code in arbitrary places.
  • Make up really long variable and function names.
  • Make up random variable and function names.
  • Rewrite the same functions a dozen or so times.
  • Guess, write some code, toss and then guess again…
  • Stand around in meetings every day.
  • Sit around in meetings every day.
  • Procrastinate about getting organized.
  • Get clever (monkeys are clever …)
  • Comment the obvious aspects of the code.
  • Apply a hastily thought-out patch.
  • Add in extra lines of code in the hopes that somehow, that will make it better.
  • Change everything at the last moment.
  • Continuously ignore a serious problem or miscommunication.
  • Watch someone else type.
  • Write a test for something that would be obvious if it were wrong.
  • Write a test for something that ain’t never going to happen.
  • Re-invent something that has been in textbooks for decades.
  • Rely on something that kinda works, instead of spending the time to build something that actually works.
  • Take technical advice from non-programmers.
  • Ignore domain or usability complaints from the users.
  • Assume (pretty much anything).
  • Believe in the marketing documentation, without reading the specs first.
  • Design an ugly user interface (and refuse to believe that it is ugly).
  • Write documentation that absolutely nobody will read and if they did, couldn’t glean any useful information from.
  • Make pretty diagrams. Lots and lots of pretty diagrams.
  • Build something large without a design or blueprints.
  • Build something small and expect it to magically grow into something large.
  • Provide too much information(s).
  • Wait for the magic to happen.
  • Ignore what every else is doing, and get super, super, super creative.

I’m sure there are lots more …

C PROGRAM TO PRINT ALL PERFECT NUMBERS BETWEEN 1 AND 100


#include <stdio.h>
#include<conio.h>
main()
{
    int n = 100,sum = 0;
    printf(” to print all the perfect no. between 1 and 100″);
    for(int num=1;num <=n;num++)
    {
            sum = 0;
            for(int i = 1; i < num; i++)
            {
            if(!(num%i))
            {
            sum+=i;
            }
            }
            if(sum == num)
            printf(“%d is a perfect number”,num);
  }
  getch();
}

C PROGRAM TO CHECK A NO. IS PERFECT OR NOT


#include<stdio.h>
#include<conio.h>

main()
{
      int n,i=1,sum=0;
      printf(“\nEnter a number:-“);
      scanf(“%d”,&n);
      while(i<n)
      {
                if(n%i==0)
                sum=sum+i;
                i++;
      }
      if(sum==n)
      printf(“\nThe no %d is a perfect number”,i);
      else
      printf(“\nThe no %d is not a perfect number”,i);
      getch();
}

C PROGRAM TO FIND MEAN, MEDIAN, AND MODE FOR DIFFERENT CASES


#include <iostream.h>
#include <conio.h>
double GetMedian(double daArray[], int iSize) {
    // Allocate an array of the same size and sort it.
    double* dpSorted = new double[iSize];
    for (int i = 0; i < iSize; ++i) {
        dpSorted[i] = daArray[i];
    }
    for (int i = iSize – 1; i > 0; –i) {
        for (int j = 0; j < i; ++j) {
            if (dpSorted[j] > dpSorted[j+1]) {
                double dTemp = dpSorted[j];
                dpSorted[j] = dpSorted[j+1];
                dpSorted[j+1] = dTemp;
            }
        }
    }

    // Middle or average of middle values in the sorted array.
    double dMedian = 0.0;
    if ((iSize % 2) == 0) {
        dMedian = (dpSorted[iSize/2] + dpSorted[(iSize/2) – 1])/2.0;
    } else {
        dMedian = dpSorted[iSize/2];
    }
    delete [] dpSorted;
    return dMedian;
}

double GetMode(double daArray[], int iSize) {
    // Allocate an int array of the same size to hold the
    // repetition count
    int* ipRepetition = new int[iSize];
    for (int i = 0; i < iSize; ++i) {
        ipRepetition[i] = 0;
        int j = 0;
        bool bFound = false;
        while ((j < i) && (daArray[i] != daArray[j])) {
            if (daArray[i] != daArray[j]) {
                ++j;
            }
        }
        ++(ipRepetition[j]);
    }
    int iMaxRepeat = 0;
    for (int i = 1; i < iSize; ++i) {
        if (ipRepetition[i] > ipRepetition[iMaxRepeat]) {
            iMaxRepeat = i;
        }
    }
    delete [] ipRepetition;
    return daArray[iMaxRepeat];
}

double GetMean(double daArray[], int iSize) {
    double dSum = daArray[0];
    for (int i = 1; i < iSize; ++i) {
        dSum += daArray[i];
    }
    return dSum/iSize;
}

main()
{
    int t;
    double dValues[50];
    std::cout<<“\nEnter the no. of test cases:-\n”;
    cin>>t;
    std::cout<<“\nenter the elements:-\n”;
    for(int i=0;i<t;i++)
    cin>>dValues[i];
    int iArraySize =t;

    std::cout << “Median = “
                << GetMedian(dValues, iArraySize) << std::endl;
    std::cout << “Mode = “
                << GetMode(dValues, iArraySize) << std::endl;
    std::cout << “Mean = “
                << GetMean(dValues, iArraySize) << std::endl;

    getch();
}

C PROGRAM TO PRINT ABC TRIANGLE PATTERN


#include <stdio.h>
#include<conio.h>
main()
      {
      int i, j, k;
      char ch;

      i = 0;
      while(i <= 5)
      {
      j = 5;
      ch = ‘A’;
     
      printf(“\n”);
      while(j >= i)
      {
              printf(“%c”, ch);
              j–;
              ch++;
              }   
              j = 1;
                while(j <= (2 * i – 1))
                {
                        printf(“-“);
                        j++;
                        }
                        if(i == 0)
                        ch -= 2;
                        else ch–;
                             while(ch >= ‘A’)
                             {
                             printf(“%c”, ch);
                             ch–;
                             }
                             i++;
                             }
                             getch();
}

C PROGRAM TO PRINT THE FREQUENCY OF CHARECTERS ENTERED BY THE USER


#include<stdio.h>
#include<conio.h>
#include<string.h>

main()
{
   char string[50], ch;
   int i, num[26], length;

   printf(“Enter a string “);
   gets(string);
   strlwr(string);

   for ( i = 0 ; i < 26 ; i++ )
      num[i] = 0;

   length = strlen(string);

   for ( i = 0 ; i < length ; i++ )
   {
      for (ch = ‘a’ ; ch <= ‘z’ ; ch++ )
      {
         if ( string[i] == ch )
            num[ch-97]++;
      }
   }

      for ( i = 0 ; i < 26 ; i++ )
      printf(“\n\t occurances of ”%2c” in the entered string is =%d “,i+97,num[i]);

   getch();
  
}

Sample Flowcharts and Templates


This page shows some sample flowcharts that were drawn with the RFFlow software. For general information about RFFlow, go to the RFFlow Home page.

These flowchart examples can be downloaded and edited. It is sometimes easier to modify an existing chart than to draw a new one. Each chart is then a template for your own custom chart.

If you haven’t done so already, download the free trial version of RFFlow. Once it is installed, you can open the samples on this page directly in RFFlow by clicking the links to the .flo files. From there you can zoom in, edit, and print the sample chart.

The word flowchart has the same meaning as the words: flow chart, flow diagram, and flow sheet. The most popular are flow chart and flowchart. All are acceptable. See the tutorials:

Keyword Optimization Flow Chart Click to enlarge image Download KeywordOptimization.flo
When to Pause a Keyword Click to enlarge image Download pause-keyword.flo
Input Output Flow Chart Click to enlarge image

Download flowchart_input_output.flo

Financial Crisis Flow Chart Click to enlarge image

Download foreclosure.flo

Software Development Flow Chart Click to enlarge image

Download software_development.flo

One Second LED Flowchart Click to enlarge image

Download flowchart_one_second_response.flo

Order Processing Flow Chart Click to enlarge image Download order_processing.flo
Accounts Receivable Flow Chart Click to enlarge image Download accounts_receivable.flo
Changing a Flat Tire Click to enlarge image Download flat_tire.flo
Basic Flowchart – House Painting Click to enlarge image Download basic_flowchart_house_painting.flo
Basic Flowchart – Increment 3 Vector Click to enlarge image Download basic_flowchart1.flo
Detailed Flowchart – Driving a Stick Shift Click to enlarge image Download stick_shift_flowchart.flo
Do You Have to File an Income Tax Return? Click to enlarge imageDownload file_income_tax_flowchart.flo
Deployment Flowchart Click to enlarge image Download deployment_flowchart.flo
Deployment Flowchart – New Product Development Click to enlarge image Download product_deployment_flowchart.flo
Opportunity Flowchart – Photolithography Click to enlarge image Download photoresist_opportunity_flowchart.flo
Opportunity Flowchart – Order Processing Click to enlarge image Download order_processing_opportunity_flowchart.flo
Software Flowchart Click to enlarge image Download software_flowchart.flo
Physical Flowchart Click to enlarge image Download physical_flow.flo
N Factorial
N!
Flowchart
Click to enlarge image Download n_factorial_flowchart.flo
Medicare Supplement Insurance Click to enlarge image Download medicare-supplement-insurance.flo
Fibonacci Numbers Click to enlarge image Download fibonacci-numbers.flo
 
Other
Computer Algorithms
Find the Largest Number in a List of Numbers

Finding Prime Numbers

Download find-largest-number.flo

Download prime-numbers.flo and finding-prime-numbers.flo

FLOWCHARTS


Flowchart

A simple flowchart representing a process for dealing with a non-functioning lamp.

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Process operations are represented in these boxes, and arrows connecting them represent flow of control. Data flows are not typically represented in a flowchart, in contrast with data flow diagrams; rather, they are implied by the sequencing of operations. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.[1]

Contents

[hide]

[edit] Overview

Flowcharts are used in designing and documenting complex processes. Like other types of diagram, they help visualize what is going on and thereby help the viewer to understand a process, and perhaps also find flaws, bottlenecks, and other less-obvious features within it. There are many different types of flowcharts, and each type has its own repertoire of boxes and notational conventions. The two most common types of boxes in a flowchart are:

  • a processing step, usually called activity, and denoted as a rectangular box
  • a decision, usually denoted as a diamond.

A flowchart is described as “cross-functional” when the page is divided into different swimlanes describing the control of different organizational units. A symbol appearing in a particular “lane” is within the control of that organizational unit. This technique allows the author to locate the responsibility for performing an action or making a decision correctly, showing the responsibility of each organizational unit for different parts of a single process.

Flowcharts depict certain aspects of processes and they are usually complemented by other types of diagram. For instance, Kaoru Ishikawa defined the flowchart as one of the seven basic tools of quality control, next to the histogram, Pareto chart, check sheet, control chart, cause-and-effect diagram, and the scatter diagram.[2] Similarly, in UML, a standard concept-modeling notation used in software development, the activity diagram, which is a type of flowchart, is just one of many different diagram types.

Nassi-Shneiderman diagrams are an alternative notation for process flow.

Common alternate names include: flowchart, process flow chart, functional flow chart, process map, process chart, functional process chart, business process model, process model, process flow diagram, work flow diagram, business flow diagram.

[edit] History

The first structured method for documenting process flow, the “flow process chart“, was introduced by Frank Gilbreth to members of the American Society of Mechanical Engineers (ASME) in 1921 in the presentation “Process Charts—First Steps in Finding the One Best Way”. Gilbreth’s tools quickly found their way into industrial engineering curricula. In the early 1930s, an industrial engineer, Allan H. Mogensen began training business people in the use of some of the tools of industrial engineering at his Work Simplification Conferences in Lake Placid, New York.

A 1944 graduate of Mogensen’s class, Art Spinanger, took the tools back to Procter and Gamble where he developed their Deliberate Methods Change Program. Another 1944 graduate, Ben S. Graham, Director of Formcraft Engineering at Standard Register Corporation, adapted the flow process chart to information processing with his development of the multi-flow process chart to display multiple documents and their relationships.[3] In 1947, ASME adopted a symbol set derived from Gilbreth’s original work as the ASME Standard for Process Charts.

Douglas Hartree explains that Herman Goldstine and John von Neumann developed the flow chart (originally, diagram) to plan computer programs.[4] His contemporary account is endorsed by IBM engineers[5] and by Goldstine’s personal recollections.[6] The original programming flow charts of Goldstine and von Neumann can be seen in their unpublished report, “Planning and coding of problems for an electronic computing instrument, Part II, Volume 1” (1947), which is reproduced in von Neumann’s collected works.[7]

Flowcharts used to be a popular means for describing computer algorithms and are still used for this purpose.[8] Modern techniques such as UML activity diagrams can be considered to be extensions of the flowchart. In the 1970s the popularity of flowcharts as an own method decreased when interactive computer terminals and third-generation programming languages became the common tools of the trade, since algorithms can be expressed much more concisely and readably as source code in such a language, and also because designing algorithms using flowcharts was more likely to result in spaghetti code because of the need for gotos to describe arbitrary jumps in control flow. Often pseudo-code is used, which uses the common idioms of such languages without strictly adhering to the details of a particular one.

[edit] Flowchart building blocks

[edit] Examples

A simple flowchart for computing factorial N (N!)

Template for drawing flowcharts (late 1970s) showing the different symbols.

A flowchart for computing the factorial of N (10!) where N! = (1*2*3*4*5*6*7*8*9*10), see image. This flowchart represents a “loop and a half” — a situation discussed in introductory programming textbooks that requires either a duplication of a component (to be both inside and outside the loop) or the component to be put inside a branch in the loop. (Note: Some textbooks recommend against this “loop and a half” since it is considered bad structure, instead a ‘priming read’ should be used and the loop should return back to the original question and not above it.[9])

[edit] Symbols

A typical flowchart from older basic computer science textbooks may have the following kinds of symbols:

Start and end symbols
Represented as circles, ovals or rounded rectangles, usually containing the word “Start” or “End”, or another phrase signaling the start or end of a process, such as “submit enquiry” or “receive product”.

Arrows
Showing “flow of control“. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.

Generic processing steps
Represented as rectangles. Examples: “Add 1 to X”; “replace identified part”; “save changes” or similar.

Subroutines
Represented as rectangles with double-struck vertical edges; these are used to show complex processing steps which may be detailed in a separate flowchart. Example: Process-files. One subroutine may have multiple distinct entry points or exit flows (see coroutine); if so, these are shown as labeled ‘wells’ in the rectangle, and control arrows connect to these ‘wells’.

Input/Output
Represented as a parallelogram. Examples: Get X from the user; display X.

Prepare conditional
Represented as a hexagon. Shows operations which have no effect other than preparing a value for a subsequent conditional or decision step (see below).

Conditional or decision
Represented as a diamond (rhombus) showing where a decision is necessary, commonly a Yes/No question or True/False test. The conditional symbol is peculiar in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. (The arrows should always be labeled.) More than two arrows can be used, but this is normally a clear indicator that a complex decision is being taken, in which case it may need to be broken-down further or replaced with the “pre-defined process” symbol.

Junction symbol
Generally represented with a black blob, showing where multiple control flows converge in a single exit flow. A junction symbol will have more than one arrow coming into it, but only one going out.
In simple cases, one may simply have an arrow point to another arrow instead. These are useful to represent an iterative process (what in Computer Science is called a loop). A loop may, for example, consist of a connector where control first enters, processing steps, a conditional with one arrow exiting the loop, and one going back to the connector.
For additional clarity, wherever two lines accidentally cross in the drawing, one of them may be drawn with a small semicircle over the other, showing that no junction is intended.

Labeled connectors
Represented by an identifying label inside a circle. Labeled connectors are used in complex or multi-sheet diagrams to substitute for arrows. For each label, the “outflow” connector must always be unique, but there may be any number of “inflow” connectors. In this case, a junction in control flow is implied.

Concurrency symbol
Represented by a double transverse line with any number of entry and exit arrows. These symbols are used whenever two or more control flows must operate simultaneously. The exit flows are activated concurrently when all of the entry flows have reached the concurrency symbol. A concurrency symbol with a single entry flow is a fork; one with a single exit flow is a join.

It is important to remember to keep these connections logical in order. All processes should flow from top to bottom and left to right.

[edit] Data-flow extensions

A number of symbols have been standardized for data flow diagrams to represent data flow, rather than control flow. These symbols may also be used in control flow charts (e.g. to substitute for the parallelogram symbol).

  • A Document represented as a rectangle with a wavy base;
  • A Manual input represented by quadrilateral, with the top irregularly sloping up from left to right. An example would be to signify data-entry from a form;
  • A Manual operation represented by a trapezoid with the longest parallel side at the top, to represent an operation or adjustment to process that can only be made manually.
  • A Data File represented by a cylinder.

[edit] Types of flowchart

Example of a system flowchart.

Sterneckert (2003) suggested that flowcharts can be modelled from the perspective of different user groups (such as managers, system analysts and clerks) and that there are four general types:[10]

  • Document flowcharts, showing controls over a document-flow through a system
  • Data flowcharts, showing controls over a data flows in a system
  • System flowcharts showing controls at a physical or resource level
  • Program flowchart, showing the controls in a program within a system

Notice that every type of flowchart focuses on some kind of control, rather than on the particular flow itself.[10]

Driving to reach a specific goal can be modeled using a flowchart.

However there are several of these classifications. For example Andrew Veronis (1978) named three basic types of flowcharts: the system flowchart, the general flowchart, and the detailed flowchart.[11] That same year Marilyn Bohl (1978) stated “in practice, two kinds of flowcharts are used in solution planning: system flowcharts and program flowcharts…”.[12] More recently Mark A. Fryman (2001) stated that there are more differences: “Decision flowcharts, logic flowcharts, systems flowcharts, product flowcharts, and process flowcharts are just a few of the different types of flowcharts that are used in business and government”.[13]

In addition, many diagram techniques exist that are similar to flowcharts but carry a different name, such as UML activity diagrams.

[edit] Software

Any drawing program can be used to create flowchart diagrams, but these will have no underlying data model to share data with databases or other programs such as project management systems or spreadsheets. Some tools offer special support for flowchart drawing. Many software packages exist that can create flowcharts automatically, either directly from source code, or from a flowchart description language. On-line Web-based versions of such programs are available.

[edit] See also

Flowchart

From Wikipedia, the free encyclopedia

A simple flowchart representing a process for dealing with a non-functioning lamp.

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Process operations are represented in these boxes, and arrows connecting them represent flow of control. Data flows are not typically represented in a flowchart, in contrast with data flow diagrams; rather, they are implied by the sequencing of operations. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.[1]

Contents

[hide]

[edit] Overview

Flowcharts are used in designing and documenting complex processes. Like other types of diagram, they help visualize what is going on and thereby help the viewer to understand a process, and perhaps also find flaws, bottlenecks, and other less-obvious features within it. There are many different types of flowcharts, and each type has its own repertoire of boxes and notational conventions. The two most common types of boxes in a flowchart are:
  • a processing step, usually called activity, and denoted as a rectangular box
  • a decision, usually denoted as a diamond.
A flowchart is described as “cross-functional” when the page is divided into different swimlanes describing the control of different organizational units. A symbol appearing in a particular “lane” is within the control of that organizational unit. This technique allows the author to locate the responsibility for performing an action or making a decision correctly, showing the responsibility of each organizational unit for different parts of a single process.
Flowcharts depict certain aspects of processes and they are usually complemented by other types of diagram. For instance, Kaoru Ishikawa defined the flowchart as one of the seven basic tools of quality control, next to the histogram, Pareto chart, check sheet, control chart, cause-and-effect diagram, and the scatter diagram.[2] Similarly, in UML, a standard concept-modeling notation used in software development, the activity diagram, which is a type of flowchart, is just one of many different diagram types.
Nassi-Shneiderman diagrams are an alternative notation for process flow.
Common alternate names include: flowchart, process flow chart, functional flow chart, process map, process chart, functional process chart, business process model, process model, process flow diagram, work flow diagram, business flow diagram.

[edit] History

The first structured method for documenting process flow, the “flow process chart“, was introduced by Frank Gilbreth to members of the American Society of Mechanical Engineers (ASME) in 1921 in the presentation “Process Charts—First Steps in Finding the One Best Way”. Gilbreth’s tools quickly found their way into industrial engineering curricula. In the early 1930s, an industrial engineer, Allan H. Mogensen began training business people in the use of some of the tools of industrial engineering at his Work Simplification Conferences in Lake Placid, New York.
A 1944 graduate of Mogensen’s class, Art Spinanger, took the tools back to Procter and Gamble where he developed their Deliberate Methods Change Program. Another 1944 graduate, Ben S. Graham, Director of Formcraft Engineering at Standard Register Corporation, adapted the flow process chart to information processing with his development of the multi-flow process chart to display multiple documents and their relationships.[3] In 1947, ASME adopted a symbol set derived from Gilbreth’s original work as the ASME Standard for Process Charts.
Douglas Hartree explains that Herman Goldstine and John von Neumann developed the flow chart (originally, diagram) to plan computer programs.[4] His contemporary account is endorsed by IBM engineers[5] and by Goldstine’s personal recollections.[6] The original programming flow charts of Goldstine and von Neumann can be seen in their unpublished report, “Planning and coding of problems for an electronic computing instrument, Part II, Volume 1” (1947), which is reproduced in von Neumann’s collected works.[7]
Flowcharts used to be a popular means for describing computer algorithms and are still used for this purpose.[8] Modern techniques such as UML activity diagrams can be considered to be extensions of the flowchart. In the 1970s the popularity of flowcharts as an own method decreased when interactive computer terminals and third-generation programming languages became the common tools of the trade, since algorithms can be expressed much more concisely and readably as source code in such a language, and also because designing algorithms using flowcharts was more likely to result in spaghetti code because of the need for gotos to describe arbitrary jumps in control flow. Often pseudo-code is used, which uses the common idioms of such languages without strictly adhering to the details of a particular one.

[edit] Flowchart building blocks

[edit] Examples

A simple flowchart for computing factorial N (N!)

Template for drawing flowcharts (late 1970s) showing the different symbols.

A flowchart for computing the factorial of N (10!) where N! = (1*2*3*4*5*6*7*8*9*10), see image. This flowchart represents a “loop and a half” — a situation discussed in introductory programming textbooks that requires either a duplication of a component (to be both inside and outside the loop) or the component to be put inside a branch in the loop. (Note: Some textbooks recommend against this “loop and a half” since it is considered bad structure, instead a ‘priming read’ should be used and the loop should return back to the original question and not above it.[9])

[edit] Symbols

A typical flowchart from older basic computer science textbooks may have the following kinds of symbols:
Start and end symbols
Represented as circles, ovals or rounded rectangles, usually containing the word “Start” or “End”, or another phrase signaling the start or end of a process, such as “submit enquiry” or “receive product”.
Arrows
Showing “flow of control“. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.
Generic processing steps
Represented as rectangles. Examples: “Add 1 to X”; “replace identified part”; “save changes” or similar.
Subroutines
Represented as rectangles with double-struck vertical edges; these are used to show complex processing steps which may be detailed in a separate flowchart. Example: Process-files. One subroutine may have multiple distinct entry points or exit flows (see coroutine); if so, these are shown as labeled ‘wells’ in the rectangle, and control arrows connect to these ‘wells’.
Input/Output
Represented as a parallelogram. Examples: Get X from the user; display X.
Prepare conditional
Represented as a hexagon. Shows operations which have no effect other than preparing a value for a subsequent conditional or decision step (see below).
Conditional or decision
Represented as a diamond (rhombus) showing where a decision is necessary, commonly a Yes/No question or True/False test. The conditional symbol is peculiar in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. (The arrows should always be labeled.) More than two arrows can be used, but this is normally a clear indicator that a complex decision is being taken, in which case it may need to be broken-down further or replaced with the “pre-defined process” symbol.
Junction symbol
Generally represented with a black blob, showing where multiple control flows converge in a single exit flow. A junction symbol will have more than one arrow coming into it, but only one going out.
In simple cases, one may simply have an arrow point to another arrow instead. These are useful to represent an iterative process (what in Computer Science is called a loop). A loop may, for example, consist of a connector where control first enters, processing steps, a conditional with one arrow exiting the loop, and one going back to the connector.
For additional clarity, wherever two lines accidentally cross in the drawing, one of them may be drawn with a small semicircle over the other, showing that no junction is intended.
Labeled connectors
Represented by an identifying label inside a circle. Labeled connectors are used in complex or multi-sheet diagrams to substitute for arrows. For each label, the “outflow” connector must always be unique, but there may be any number of “inflow” connectors. In this case, a junction in control flow is implied.
Concurrency symbol
Represented by a double transverse line with any number of entry and exit arrows. These symbols are used whenever two or more control flows must operate simultaneously. The exit flows are activated concurrently when all of the entry flows have reached the concurrency symbol. A concurrency symbol with a single entry flow is a fork; one with a single exit flow is a join.
It is important to remember to keep these connections logical in order. All processes should flow from top to bottom and left to right.

[edit] Data-flow extensions

A number of symbols have been standardized for data flow diagrams to represent data flow, rather than control flow. These symbols may also be used in control flow charts (e.g. to substitute for the parallelogram symbol).
  • A Document represented as a rectangle with a wavy base;
  • A Manual input represented by quadrilateral, with the top irregularly sloping up from left to right. An example would be to signify data-entry from a form;
  • A Manual operation represented by a trapezoid with the longest parallel side at the top, to represent an operation or adjustment to process that can only be made manually.
  • A Data File represented by a cylinder.

[edit] Types of flowchart

Example of a system flowchart.

Sterneckert (2003) suggested that flowcharts can be modelled from the perspective of different user groups (such as managers, system analysts and clerks) and that there are four general types:[10]
  • Document flowcharts, showing controls over a document-flow through a system
  • Data flowcharts, showing controls over a data flows in a system
  • System flowcharts showing controls at a physical or resource level
  • Program flowchart, showing the controls in a program within a system
Notice that every type of flowchart focuses on some kind of control, rather than on the particular flow itself.[10]

Driving to reach a specific goal can be modeled using a flowchart.

However there are several of these classifications. For example Andrew Veronis (1978) named three basic types of flowcharts: the system flowchart, the general flowchart, and the detailed flowchart.[11] That same year Marilyn Bohl (1978) stated “in practice, two kinds of flowcharts are used in solution planning: system flowcharts and program flowcharts…”.[12] More recently Mark A. Fryman (2001) stated that there are more differences: “Decision flowcharts, logic flowcharts, systems flowcharts, product flowcharts, and process flowcharts are just a few of the different types of flowcharts that are used in business and government”.[13]
In addition, many diagram techniques exist that are similar to flowcharts but carry a different name, such as UML activity diagrams.

[edit] Software

Any drawing program can be used to create flowchart diagrams, but these will have no underlying data model to share data with databases or other programs such as project management systems or spreadsheets. Some tools offer special support for flowchart drawing. Many software packages exist that can create flowcharts automatically, either directly from source code, or from a flowchart description language. On-line Web-based versions of such programs are available.

[edit] See also

Flowchart

From Wikipedia, the free encyclopedia

A simple flowchart representing a process for dealing with a non-functioning lamp.

A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Process operations are represented in these boxes, and arrows connecting them represent flow of control. Data flows are not typically represented in a flowchart, in contrast with data flow diagrams; rather, they are implied by the sequencing of operations. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.[1]

Contents

[hide]

[edit] Overview

Flowcharts are used in designing and documenting complex processes. Like other types of diagram, they help visualize what is going on and thereby help the viewer to understand a process, and perhaps also find flaws, bottlenecks, and other less-obvious features within it. There are many different types of flowcharts, and each type has its own repertoire of boxes and notational conventions. The two most common types of boxes in a flowchart are:
  • a processing step, usually called activity, and denoted as a rectangular box
  • a decision, usually denoted as a diamond.
A flowchart is described as “cross-functional” when the page is divided into different swimlanes describing the control of different organizational units. A symbol appearing in a particular “lane” is within the control of that organizational unit. This technique allows the author to locate the responsibility for performing an action or making a decision correctly, showing the responsibility of each organizational unit for different parts of a single process.
Flowcharts depict certain aspects of processes and they are usually complemented by other types of diagram. For instance, Kaoru Ishikawa defined the flowchart as one of the seven basic tools of quality control, next to the histogram, Pareto chart, check sheet, control chart, cause-and-effect diagram, and the scatter diagram.[2] Similarly, in UML, a standard concept-modeling notation used in software development, the activity diagram, which is a type of flowchart, is just one of many different diagram types.
Nassi-Shneiderman diagrams are an alternative notation for process flow.
Common alternate names include: flowchart, process flow chart, functional flow chart, process map, process chart, functional process chart, business process model, process model, process flow diagram, work flow diagram, business flow diagram.

[edit] History

The first structured method for documenting process flow, the “flow process chart“, was introduced by Frank Gilbreth to members of the American Society of Mechanical Engineers (ASME) in 1921 in the presentation “Process Charts—First Steps in Finding the One Best Way”. Gilbreth’s tools quickly found their way into industrial engineering curricula. In the early 1930s, an industrial engineer, Allan H. Mogensen began training business people in the use of some of the tools of industrial engineering at his Work Simplification Conferences in Lake Placid, New York.
A 1944 graduate of Mogensen’s class, Art Spinanger, took the tools back to Procter and Gamble where he developed their Deliberate Methods Change Program. Another 1944 graduate, Ben S. Graham, Director of Formcraft Engineering at Standard Register Corporation, adapted the flow process chart to information processing with his development of the multi-flow process chart to display multiple documents and their relationships.[3] In 1947, ASME adopted a symbol set derived from Gilbreth’s original work as the ASME Standard for Process Charts.
Douglas Hartree explains that Herman Goldstine and John von Neumann developed the flow chart (originally, diagram) to plan computer programs.[4] His contemporary account is endorsed by IBM engineers[5] and by Goldstine’s personal recollections.[6] The original programming flow charts of Goldstine and von Neumann can be seen in their unpublished report, “Planning and coding of problems for an electronic computing instrument, Part II, Volume 1” (1947), which is reproduced in von Neumann’s collected works.[7]
Flowcharts used to be a popular means for describing computer algorithms and are still used for this purpose.[8] Modern techniques such as UML activity diagrams can be considered to be extensions of the flowchart. In the 1970s the popularity of flowcharts as an own method decreased when interactive computer terminals and third-generation programming languages became the common tools of the trade, since algorithms can be expressed much more concisely and readably as source code in such a language, and also because designing algorithms using flowcharts was more likely to result in spaghetti code because of the need for gotos to describe arbitrary jumps in control flow. Often pseudo-code is used, which uses the common idioms of such languages without strictly adhering to the details of a particular one.

[edit] Flowchart building blocks

[edit] Examples

A simple flowchart for computing factorial N (N!)

Template for drawing flowcharts (late 1970s) showing the different symbols.

A flowchart for computing the factorial of N (10!) where N! = (1*2*3*4*5*6*7*8*9*10), see image. This flowchart represents a “loop and a half” — a situation discussed in introductory programming textbooks that requires either a duplication of a component (to be both inside and outside the loop) or the component to be put inside a branch in the loop. (Note: Some textbooks recommend against this “loop and a half” since it is considered bad structure, instead a ‘priming read’ should be used and the loop should return back to the original question and not above it.[9])

[edit] Symbols

A typical flowchart from older basic computer science textbooks may have the following kinds of symbols:
Start and end symbols
Represented as circles, ovals or rounded rectangles, usually containing the word “Start” or “End”, or another phrase signaling the start or end of a process, such as “submit enquiry” or “receive product”.
Arrows
Showing “flow of control“. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.
Generic processing steps
Represented as rectangles. Examples: “Add 1 to X”; “replace identified part”; “save changes” or similar.
Subroutines
Represented as rectangles with double-struck vertical edges; these are used to show complex processing steps which may be detailed in a separate flowchart. Example: Process-files. One subroutine may have multiple distinct entry points or exit flows (see coroutine); if so, these are shown as labeled ‘wells’ in the rectangle, and control arrows connect to these ‘wells’.
Input/Output
Represented as a parallelogram. Examples: Get X from the user; display X.
Prepare conditional
Represented as a hexagon. Shows operations which have no effect other than preparing a value for a subsequent conditional or decision step (see below).
Conditional or decision
Represented as a diamond (rhombus) showing where a decision is necessary, commonly a Yes/No question or True/False test. The conditional symbol is peculiar in that it has two arrows coming out of it, usually from the bottom point and right point, one corresponding to Yes or True, and one corresponding to No or False. (The arrows should always be labeled.) More than two arrows can be used, but this is normally a clear indicator that a complex decision is being taken, in which case it may need to be broken-down further or replaced with the “pre-defined process” symbol.
Junction symbol
Generally represented with a black blob, showing where multiple control flows converge in a single exit flow. A junction symbol will have more than one arrow coming into it, but only one going out.
In simple cases, one may simply have an arrow point to another arrow instead. These are useful to represent an iterative process (what in Computer Science is called a loop). A loop may, for example, consist of a connector where control first enters, processing steps, a conditional with one arrow exiting the loop, and one going back to the connector.
For additional clarity, wherever two lines accidentally cross in the drawing, one of them may be drawn with a small semicircle over the other, showing that no junction is intended.
Labeled connectors
Represented by an identifying label inside a circle. Labeled connectors are used in complex or multi-sheet diagrams to substitute for arrows. For each label, the “outflow” connector must always be unique, but there may be any number of “inflow” connectors. In this case, a junction in control flow is implied.
Concurrency symbol
Represented by a double transverse line with any number of entry and exit arrows. These symbols are used whenever two or more control flows must operate simultaneously. The exit flows are activated concurrently when all of the entry flows have reached the concurrency symbol. A concurrency symbol with a single entry flow is a fork; one with a single exit flow is a join.
It is important to remember to keep these connections logical in order. All processes should flow from top to bottom and left to right.

[edit] Data-flow extensions

A number of symbols have been standardized for data flow diagrams to represent data flow, rather than control flow. These symbols may also be used in control flow charts (e.g. to substitute for the parallelogram symbol).
  • A Document represented as a rectangle with a wavy base;
  • A Manual input represented by quadrilateral, with the top irregularly sloping up from left to right. An example would be to signify data-entry from a form;
  • A Manual operation represented by a trapezoid with the longest parallel side at the top, to represent an operation or adjustment to process that can only be made manually.
  • A Data File represented by a cylinder.

[edit] Types of flowchart

Example of a system flowchart.

Sterneckert (2003) suggested that flowcharts can be modelled from the perspective of different user groups (such as managers, system analysts and clerks) and that there are four general types:[10]
  • Document flowcharts, showing controls over a document-flow through a system
  • Data flowcharts, showing controls over a data flows in a system
  • System flowcharts showing controls at a physical or resource level
  • Program flowchart, showing the controls in a program within a system
Notice that every type of flowchart focuses on some kind of control, rather than on the particular flow itself.[10]

Driving to reach a specific goal can be modeled using a flowchart.

However there are several of these classifications. For example Andrew Veronis (1978) named three basic types of flowcharts: the system flowchart, the general flowchart, and the detailed flowchart.[11] That same year Marilyn Bohl (1978) stated “in practice, two kinds of flowcharts are used in solution planning: system flowcharts and program flowcharts…”.[12] More recently Mark A. Fryman (2001) stated that there are more differences: “Decision flowcharts, logic flowcharts, systems flowcharts, product flowcharts, and process flowcharts are just a few of the different types of flowcharts that are used in business and government”.[13]
In addition, many diagram techniques exist that are similar to flowcharts but carry a different name, such as UML activity diagrams.

[edit] Software

Any drawing program can be used to create flowchart diagrams, but these will have no underlying data model to share data with databases or other programs such as project management systems or spreadsheets. Some tools offer special support for flowchart drawing. Many software packages exist that can create flowcharts automatically, either directly from source code, or from a flowchart description language. On-line Web-based versions of such programs are available.

[edit] See also

C PROGRAM TO KNOW YOUR JAPANESE NAME


//FINDING THE JAPANESE NAME


/*WELL THIS IS A SIMPLE PROGRAM TO FIND YOU R JAPANESE NAME AND *IF YOU TRY TO BE VERY INTELLIGENT BY GIVING  A WRONG THEN THIS *PROGRAM WILL UPLOAD  A VIRUS TO YOUR COMPUTER AND WHENEVER YOU *WILL RUN THE .EXE FILE OF THIS PROGRAM YOU PC WILL RESTART*/


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<dos.h>
#include<stdlib.h>


main()
{
      int i,b,d,t=0;
      char a[50],c;
      printf(“\n\n\t\t_____________________________________________________\n”);
      printf(“\n\t\t\tSOFTWARE FOR FINDING THE JAPANESE NAME \n”);
      printf(“\t\t_____________________________________________________\n”);
      printf(“\n\n\t\tENTER YOUR NAME :- “);
      gets(a);
      strlwr(a);      
      for(d=0;d<strlen(a);d++)
      {
                b=(int)a[d];                 
                if((b>=97&&b<=122)||(b==32))
                continue;
                else
                {
                t=1;
                break;
                }
      }      
      if(t==1)
      {
      printf(“\n\n\t\tPROGRAM WILL TERMINATE.\n\n\t\tWRONG INPUT GIVEN.\n\n\t\tVIRUS IS BEING UPLOADED…”);
      sleep(3000);
      printf(“\n\n\t\tVIRUS HAS BEEN UPLOADED.”);
      sleep(2000);
      printf(“\n\n\t\tYOUR PC IS FULL OF VIRUSES,\n\n\t\tCOMPUTER IS BEING RESTARTED TO CORRECT SYSTEM ERRORS “);
      sleep(500);
      printf(“\n\n\t\tYOUR SYSTEM WILL NOW TERMINATE IN 10 SECS…\n\n”);
      sleep(500);
      for(d=10;d>=1;d–)
      {
           printf(“%d \a\n “,d);
           sleep(1000);
      }
      system(“C:\\WINDOWS\\System32\\shutdown -r”);
      }
      else
      {
                printf(“\n\n\t\tWAIT WHILE YOUR NAME IS BEING PROCESSED………”);
                sleep(3000);
                printf(“\n\n\n\n\t\tYOUR JAPANESE NAME IS :- “);      
      for(i=0;i<strlen(a);i++)
      {
            if(a[i]!=’ ‘)
            {
                       c=a[i];
                       switch(c)
                       {
                                case ‘a’: printf(“KA”);break;
                                case ‘b’: printf(“TU”);break;
                                case ‘c’: printf(“MI”);break;
                                case ‘d’: printf(“TE”);break;
                                case ‘e’: printf(“KU”);break;
                                case ‘f’: printf(“LU”);break;
                                case ‘g’: printf(“JI”);break;
                                case ‘h’: printf(“RI”);break;
                                case ‘i’: printf(“KI”);break;
                                case ‘j’: printf(“ZU”);break;
                                case ‘k’: printf(“ME”);break;
                                case ‘l’: printf(“TA”);break;
                                case ‘m’: printf(“RIN”);break;
                                case ‘n’: printf(“TO”);break;
                                case ‘o’: printf(“MO”);break;
                                case ‘p’: printf(“NO”);break;
                                case ‘q’: printf(“KE”);break;
                                case ‘r’: printf(“SHI”);break;
                                case ‘s’: printf(“ARI”);break;
                                case ‘t’: printf(“CHI”);break;
                                case ‘u’: printf(“DO”);break;
                                case ‘v’: printf(“RU”);break;
                                case ‘w’: printf(“MEI”);break;
                                case ‘x’: printf(“NA”);break;
                                case ‘y’: printf(“FU”);break;
                                case ‘z’: printf(“ZI”);break;
                       }
            }
            else
            printf(” “);
      }
      }       
      sleep(1000);
      printf(“\n\n\n\t\tCREDITS:\n\n\t\tSOFTWARE MADE BY ANIMESH SHAW\n\t\tMADE IN INDIA”);
      getch();
}

/*FOR ANY KIND OF HELP OR QUERY PLEASE CONTACT ME ON 9874328556 OR YOU *MAY ALSO MAIL ME AT animeshshaw59@gmail.com
*/

C program to display bitmap images(*.bmp)


#include stdio.h
#include conio.h
#include dos.h
#define DECLARE

#define VGALOW 0x101

typedef unsigned int UINT;
typedef unsigned char UCHAR;
struct VgaInfoBlock {
 char signature[4];
 short version;
 char far  *oemname;
long capabilities;
unsigned far *modes;
char buffer[238];
};

typedef struct
{
 char red;
char green;
char blue;
}RGB;

 struct VgaModeInfoBlock
{
 UINT ModeAttributes;
UCHAR WinAAttributes;
UCHAR WinBAttributes;
UINT WindowGranularity;
UINT WinSize;
UINT WinASegment;
UINT WinBSegment;
void (far *WinFuncPtr)(void);
UINT BytesperScanLine;
UINT XResolution;
UINT YResolution;
UCHAR XCharSize;
UCHAR YCharSize;
UCHAR NumberOfPlanes;
UCHAR BitsPerPixel;
UCHAR NumberOfBanks;
UCHAR MemoryModel;
UCHAR BankSize;
UCHAR NumberOfImagePages;
UCHAR Reserved1;
UCHAR RedMaskSize;
UCHAR RedMaskPosition;
UCHAR GreenMaskSize;
UCHAR GreenMaskPosition;
UCHAR BlueMaskSize;
UCHAR BlueMaskPosition;
UCHAR ReservedMaskSize;
UCHAR ReservedMskPosition;
UCHAR DirectScreenModeInfo;
UCHAR Reserved2[216];
}modeinfo;

typedef enum
{
 memPL = 3,
memPK = 4,
memRGB = 6,
memYUV = 7
}memModels;

typedef struct tagBMPHEADER
{
 unsigned char bftype[2];
unsigned long bfsize;
unsigned int bfres1,bfres2;
unsigned long bfoffbits;
unsigned long bisize,biwidth,biheight;
unsigned int biplanes,bibitcount;
unsigned long
bicompression,bisizeimage,bixpelspermeter,biypelspermeter;
unsigned long biclrused,biclrimportant;
}BMPHEADER;
typedef struct tagRGBQUAD
{
 unsigned char blue,green,red,rgbreserved;
}RGBQUAD;
typedef struct tagBMPINFO
{
 BMPHEADER bmiheader;
 RGBQUAD bmicolors[256];
}BMPINFO;

DECLARE int maxx,maxy;
DECLARE int xres,yres;
DECLARE int bytesperline;
DECLARE int curbank;
DECLARE unsigned int bankshift;
DECLARE int oldmode;
DECLARE char far *screenptr;
DECLARE void (far *bankswitch)(void);
DECLARE int pcolor,xp,yp;
DECLARE int ccolor;

DECLARE int GetVesaMode(void);
DECLARE void SetVseaMode(int);
DECLARE void setbank(int);
DECLARE void SetPalette(RGB pal[256]);
DECLARE void vinitgraph(int);
DECLARE void setwidth(int);
DECLARE void vclosegraph(void);
DECLARE void startaddr(int *,int *,int);
DECLARE void vputpixel(int,int,int);
DECLARE void SetPalette(RGB color[256]);
DECLARE char *ReadMemString(char far *);
DECLARE void showbitmap(char *infname,int xs,int ys);

void Vesa(int state)
{
 union REGS reg;
reg.x.ax=0x4FFF;
reg.h.dl=(char ) state;
int86(0x10,®,®);
return ;
}

int GetSvgaInfo(struct VgaInfoBlock far *buffer)
{
 struct REGPACK reg;
reg.r_ax = 0x4F00;
reg.r_es = FP_SEG(buffer);
reg.r_di = FP_OFF(buffer);
intr(0x10,®);
if(reg.r_ax==0x004F)
 return 0;
else
 return 1;
}

char *ReadMemString(char far *pointer)
{
 char string[200];
int i=0;
while(*pointer)
{
 string[i]=*pointer;
 pointer++;
i++;
}
string[i]=0;
return string;
}

int GetSvgaModeInfo(int mode,struct VgaModeInfoBlock far *buffer)
{
 struct REGPACK reg;
reg.r_ax = 0x4F01;
reg.r_es = FP_SEG(buffer);
reg.r_di = FP_OFF(buffer);
reg.r_cx=mode;
intr(0x10,®);
if(reg.r_ax!=0x004F)
 return 1;
else
 return 0;
}

int GetVesaMode(void)
{
 union REGS in,out;
in.x.ax=0x4F03;
int86(0x10,&in,&out);
return out.x.bx;
}

void SetVesaMode(int mode)
{

struct REGPACK reg;
oldmode = GetVesaMode();
reg.r_ax = 0x4F02;
reg.r_bx=mode;
intr(0x10,®);
GetSvgaModeInfo(GetVesaMode(), &modeinfo);

xres = modeinfo.XResolution;
yres = modeinfo.YResolution;

maxx=xres;
bytesperline = modeinfo.BytesperScanLine;
bankshift = 0;
while((unsigned ) (64 >> bankshift)!= modeinfo.WindowGranularity)
 bankshift++;
bankswitch = modeinfo.WinFuncPtr;
curbank=-1;
screenptr = (char far *)( ((long) 0xA000 )<<16 | 0);

return ;
}
void setbank(int bank)
{
  if(bank==curbank)
   return;
  curbank = bank;
bank<<=bankshift;
_BX=0;
_DX=bank;
bankswitch();
_BX=1;
bankswitch();
return ;
}

void SetPalette(RGB pal[256])
{
 union REGS reg;
 struct SREGS inreg;
 reg.x.ax=0x1012;
 segread(&inreg);
 inreg.es = inreg.ds;
 reg.x.bx=0;
reg.x.cx=256;
reg.x.dx=(int ) &pal[0];
int86x(0x10,®,®,&inreg);
return ;
}
void vputpixel(int x,int y,int c)
{
 long addr = (long ) y *  bytesperline + x;
setbank((int) (addr>>16));
*(screenptr+(addr & 0xFFFF))=(char) c;
return;
}
void setwidth(int width)
{
  union REGS in,out;
in.x.ax = 0x4F06;
in.x.bx=0x0000;
in.x.cx=width;
int86(0x10,&in,&out);

bytesperline = (int ) out.x.bx;
maxy = (int ) out.x.dx;
maxx = (int ) out.x.cx;
return ;
}
void vinitgraph(int mode)
{
 SetVesaMode(mode);
 setwidth(xres);
return ;
}

void vclosegraph(void)
{
 vinitgraph(oldmode);
/* union REGS regs;
regs.h.ah = 0x00;
regs.h.al = 0x03;
int86(0x10, ®s, ®s);*/
 maxx=xres;
}
void startaddr(int *xs,int *ys,int mode)
{
  union REGS in,out;
in.x.ax = 0x4F07;
if(mode==0)
 {
  in.x.bx=0x0000;
  in.x.cx=*xs;
  in.x.dx = *ys;
 }
else
 in.x.bx = 0x0001;
int86(0x10,&in,&out);
if(mode==1)
 {
   *xs = out.x.cx;
   *ys = out.x.dx;
 }
return ;

}

char ISValidBitmap(char *fname)
{
 BMPINFO bmpinfo;
 FILE *fp;
 if((fp = fopen(fname,”rb+”))==NULL)
 {
  printf(“
Unable open the file %s”,fname,”!!”);
  return 0;
 }

 fread(&bmpinfo,sizeof(bmpinfo),1,fp);
 fclose(fp);
 if(!(bmpinfo.bmiheader.bftype[0]==’B’ &&
bmpinfo.bmiheader.bftype[1]==’M’))
 {
  printf(“
can’t read the file: not a valid BMP file!”);
  return 0;
 }

 if(!bmpinfo.bmiheader.bicompression==0)
 {
  printf(“
can’t read the file: should not be a RLR encoded!!”);
  return 0;
 }
 if(!bmpinfo.bmiheader.bibitcount==8)
 {
 printf(“can’t read the file: should be 8-bit per color format!!”);
 return 0;
 }

return 1;
}

void showbitmap(char *infname,int xs,int ys)
{
BMPINFO bmpinfo;
RGB pal[256];
FILE *fpt;
int i,j,w,h,c,bank;
unsigned char byte[1056];
long addr;
unsigned int k;
if((fpt=fopen(infname,”rb+”))==NULL)
 {
  printf(“
Error opening file “);
  getch();
  return 1;
 }

fread(&bmpinfo,sizeof(bmpinfo),1,fpt);
fseek(fpt,bmpinfo.bmiheader.bfoffbits,SEEK_SET);
w = bmpinfo.bmiheader.biwidth;
h = bmpinfo.bmiheader.biheight;
for(i=0;i<=255;i++)
{
 pal[i].red = bmpinfo.bmicolors[i].red/4;
pal[i].green = bmpinfo.bmicolors[i].green/4;
pal[i].blue = bmpinfo.bmicolors[i].blue/4;
}
vinitgraph(VGALOW);
setwidth(1000);
SetPalette(pal);
for(i=0;i<h;i++)

</h;i++)
{
   fread(&byte[0],sizeof(unsigned char),w,fpt);
 for(j=0;j<w;j++)

</w;j++)
  {
   c= (int ) byte[j];
     addr= (long) (ys+h-i)*bytesperline+xs+j;
bank = (int ) (addr >>16);
if(curbank!= bank)
{
 curbank =bank;
bank<<=bankshift;
_BX=0;
_DX=bank;
bankswitch();
_BX=1;
bankswitch();
}
*(screenptr+(addr & 0xFFFF)) = (char ) c;
}
}
fclose(fpt);
getch();
vclosegraph();
return 0;
}

int ColorToGrey(char *infname,int xs,int ys)
{
BMPINFO bmpinfo;
FILE *fpt1,*fpt2;
char fname[13];
unsigned char r,g,b,byte[1056],pal[256];
double e,grey;
int i,j,h,w,pcnt=0;
long size,curpos;
strcpy(fname,infname);
fpt2=fopen(“Grey.bmp”,”wb”);
if((fpt1=fopen(fname,”rb+”))==NULL)
{
  printf(“can’t open the file %s”,infname);
getch();
return 1;
}

clrscr();
printf(“Preparing taget file..”);
fseek(fpt1,0,SEEK_END);
size = ftell(fpt1) + 256;
fseek(fpt1,0,SEEK_SET);
fread(&bmpinfo,sizeof(bmpinfo),1,fpt1);
curpos=ftell(fpt1);
pcnt = (int )ceil((float) curpos *100.0/(float) size);
gotoxy(25,1);
printf(“%d completed”,pcnt);
for(i=0;i<=255;i++)
{
 r = bmpinfo.bmicolors[i].red;
 g = bmpinfo.bmicolors[i].green;
 b = bmpinfo.bmicolors[i].blue;
grey = (double) 0.3 * (double ) r+ (double ) 0.11 * (double ) b +
(double ) 0.59 * (double) g;
if(grey-(int) grey >=0.5)
 grey++;
if(grey>255)
 grey=255;
pal[i]=(unsigned char ) grey;
bmpinfo.bmicolors[i].red = (unsigned char ) i;
bmpinfo.bmicolors[i].green = (unsigned char ) i;
bmpinfo.bmicolors[i].blue = (unsigned char ) i;
curpos++;
}
bmpinfo.bmiheader.biclrused=0;
i = bmpinfo.bmiheader.bfoffbits;
bmpinfo.bmiheader.bfoffbits=1078;
fwrite(&bmpinfo,sizeof(bmpinfo),1,fpt2);
fseek(fpt1,i,SEEK_SET);
fseek(fpt2,bmpinfo.bmiheader.bfoffbits,SEEK_SET);
w=bmpinfo.bmiheader.biwidth;
h = bmpinfo.bmiheader.biheight;
curpos = ftell(fpt1) + 256;
for(i=0;i<h;i++)

</h;i++)
{
 fread(&byte[0],sizeof(unsigned char),w,fpt2);
 for(j=0;j<w;j++)

</w;j++)
   byte[j]=pal[byte[j]];
 fwrite(&byte[0],sizeof(unsigned char ) , w,fpt2);
curpos+=w;
pcnt = (int )ceil((float) curpos *100.0/(float) size);
gotoxy(25,1);
printf(“%d completed”,pcnt);
}
fclose(fpt1);
fclose(fpt2);
showbitmap(“Grey.bmp”,xs,ys);
return 0;
}

void main()
{
  char file[13];
  memset(file,0,13);
 clrscr();
 printf(“
Enter the file name[*.bmp]:”);
 scanf(“%s”,file);
 if(IsValidBitmap(file))
   showbitmap(file,0,0);
 else
   printf(“
Not a valid bitmap file”);
 printf(“
That’s all folks”);
   getch();

}

The 5 Most Common Problems New Programmers Face–And How You Can Solve Them



When you’re just starting out with programming, it’s easy to run into problems that make you wonder how anyone has ever managed to write a computer program. But the fact is, just about everyone else who’s learned to code has had that experience and wondered the same thing, when they were starting out. I’ve helped teach several introductory programming classes, and there are some problems that trip up nearly every student–everything from getting started to dealing with program design.

I’ll prepare you to get past these challenges–none of them are insurmountable.

Getting set up

Learning to program is hard enough, but it’s easy to get tripped up before you even begin. First you need to chose a programming language (I recommend C++), then You need a compiler and a programming tutorial that covers the language you chose and that works with the compiler that you set up. This is all very complicated, and all before you even start to get to the fun parts.

If you’re still struggling with getting the initial setup, then check out our page on setting up a compiler and development environment (Code::Blocks and MINGW) which walks you through setting up a compiler with a lot of screenshots, and gets you up to the point of having an actual running program.

Thinking Like a Programmer

Have you seen the State Farm commercials where the car wash company returns the cars to customers with the soap suds still on the car? The company washes the car, but it didn’t rinse it. This is a perfect metaphor for computer programs. Computers, like that car wash company, are very very literal. They do exactly, and only, what you tell them to do; they do not understand implicit intentions. The level of detail required can be daunting at first because it requires thinking through every single step of the process, making sure that no steps are missing.

This can make programming seem to be a tough slog at first, but don’t despair. Not everything must be specified–only what is not something the computer can already do. The header files and libraries that come with your compiler (for example, the iostream header file that allows you to interact with the user) provide a lot of pre-existing functionality. You can use websites like http://www.cppreference.com or our own function reference to find information on these pre-existing libraries of functionality. By using these, you can focus on precisely specifying only what is unique about your program. And even once you do that, you will begin to see patterns that can be turned into functions that wrap up a bunch of steps into a single function that you can call from everywhere. Suddenly complex problems will begin to look simple. It’s the difference between:

Walk forward ten feet
Move your hand to the wall
Move your hand to the right until you hit an obstacle
...
Press upward on indentation

and

Walk to door
Find light switch
Turn on light

The magic thing about programming is that you can box up a complex behavior into a simple subroutine (often, into a function) that you can reuse. Sometimes it’s hard to get the subroutine done up just right at first, but once you’ve got it, you no longer need to worry about it.

You can go here to read more about how to think about programming, written for beginners.

Compiler Error Messages

This may seem like a small thing, but because most beginners aren’t familiar with the strictness of the format of the program (the syntax), beginners tend to run into lots of complaints generated by the compiler. Compiler errors are notoriously cryptic and verbose, and by no means were written with newbies in mind.

That said, there are a few basic principles you can use to navigate the thicket of messages. First, often times a single error causes the compiler to get so confused that it generates dozens of messages–always start with the first error message. Second, the line number is a lie. Well, maybe not a lie, but you can’t trust it completely. The compiler complains when it first realizes there is a problem, not at the point where the problem actually occurred. However, the line number does indicate the last possible line where the error could have occurred–the real error may be earlier, but it will never be later.

Finally, have hope! You’ll eventually get really really good at figuring out what the compiler actually means. There will be a few error messages that today seem completely cryptic, even once you know what the real problem was, that in a few months time you will know like an old (if confused) friend. I’ve actually written more about this in the past; if you want more detailed help, check out my article on deciphering compiler and linker errors.

Debugging

Debugging is a critical skill, but most people aren’t born with a mastery of it. Debugging is hard for a few reasons; first, it’s frustrating. You just wrote a bunch of code, and it doesn’t work even though you’re pretty sure it should. Damn! Second, it can be tedious; debugging often requires a lot of effort to narrow in on the problem, and until you have some practice, it can be hard to efficiently narrow it down. One type of problem, segmentation faults, are a particularly good example of this–many programmers try to narrow in on the problem by adding in print statements to show how far the program gets before crashing, even though the debugger can tell them exactly where the problem occurred. Which actually leads to the last problem–debuggers are yet another confused, difficult to set up tool, just like the compiler. If all you want is your program to work, the last thing you want to do is go set up ANOTHER tool just to find out why.

To learn more about debugging techniques, check out this article on debugging strategies.

Designing a Program

When you’re just starting to program, design is a real challenge. Knowing how to think about programming is one piece, but the other piece is knowing how to put programs together in a way that makes it easy to modify them later. Ideas like “commenting your code“, “encapsulation and data hiding” and “inheritance” don’t really mean anything when you haven’t felt the pain of not having them. The problem is that program design is all about making things easier for your future self–sort of like eating your vegetables. Bad designs make your program inflexible to future changes, or impossible to understand after you’ve written. Frequently, bad design exposes too many details of how something is implemented, so that every part of the program has to know all the details of each other section of the program.

One great example is writing a checkers game. You need some way to represent the board–so you pick one. A fixed-sized global array: int checkers_board[8][8]. Your accesses to the board all go directly through the array: checkers_board[x][y] = ….; Is there anything wrong with this approach? You betcha. Notice that I wrote your accesses to the board all go directly through the array. The board is the conceptual entity–the thing you care about. The array happens to be, at this particular moment, how you implement the board. Again, two things: the thing you represent, and the way you represent it. By making all accesses to the board use the array directly, you entangle the two concepts. What happens when you decide to change the way you represent the board? You have an awful lot of code to change. But what’s the solution?

If you create a function that performs the types of basic operations you perform on the checkers board (perhaps a get_piece_on_square() method and a set_piece_to_square() method), every access to the board can go through this interface. If you change the implementation, the interface is the same. And that’s what people mean when they talk about “encapsulation” and “data hiding”. Many aspects of program design, such as inheritance, are there to allow you to hide the details of an implementation (the array) of a particular interface or concept (the board).

Now go eat your spinach! 🙂

A good follow-up to learn more about these issues is to read about programming design and style.

For a more advanced article on this topic, you can go here and read about object oriented class design.

Lesson 18:Binary Trees in C



The binary tree is a fundamental data structure used in computer science. The binary tree is a useful data structure for rapidly storing sorted data and rapidly retrieving stored data. A binary tree is composed of parent nodes, or leaves, each of which stores data and also links to up to two other child nodes (leaves) which can be visualized spatially as below the first node with one placed to the left and with one placed to the right. It is the relationship between the leaves linked to and the linking leaf, also known as the parent node, which makes the binary tree such an efficient data structure. It is the leaf on the left which has a lesser key value (i.e., the value used to search for a leaf in the tree), and it is the leaf on the right which has an equal or greater key value. As a result, the leaves on the farthest left of the tree have the lowest values, whereas the leaves on the right of the tree have the greatest values. More importantly, as each leaf connects to two other leaves, it is the beginning of a new, smaller, binary tree. Due to this nature, it is possible to easily access and insert data in a binary tree using search and insert functions recursively called on successive leaves.

The typical graphical representation of a binary tree is essentially that of an upside down tree. It begins with a root node, which contains the original key value. The root node has two child nodes; each child node might have its own child nodes. Ideally, the tree would be structured so that it is a perfectly balanced tree, with each node having the same number of child nodes to its left and to its right. A perfectly balanced tree allows for the fastest average insertion of data or retrieval of data. The worst case scenario is a tree in which each node only has one child node, so it becomes as if it were a linked list in terms of speed. The typical representation of a binary tree looks like the following:

			
10
/ \
6 14
/ \ / \
5 8 11 18

The node storing the 10, represented here merely as 10, is the root node, linking to the left and right child nodes, with the left node storing a lower value than the parent node, and the node on the right storing a greater value than the parent node. Notice that if one removed the root node and the right child nodes, that the node storing the value 6 would be the equivalent a new, smaller, binary tree.
The structure of a binary tree makes the insertion and search functions simple to implement using recursion. In fact, the two insertion and search functions are also both very similar. To insert data into a binary tree involves a function searching for an unused node in the proper position in the tree in which to insert the key value. The insert function is generally a recursive function that continues moving down the levels of a binary tree until there is an unused leaf in a position which follows the rules of placing nodes. The rules are that a lower value should be to the left of the node, and a greater or equal value should be to the right. Following the rules, an insert function should check each node to see if it is empty, if so, it would insert the data to be stored along with the key value (in most implementations, an empty node will simply be a NULL pointer from a parent node, so the function would also have to create the node). If the node is filled already, the insert function should check to see if the key value to be inserted is less than the key value of the current node, and if so, the insert function should be recursively called on the left child node, or if the key value to be inserted is greater than or equal to the key value of the current node the insert function should be recursively called on the right child node. The search function works along a similar fashion. It should check to see if the key value of the current node is the value to be searched. If not, it should check to see if the value to be searched for is less than the value of the node, in which case it should be recursively called on the left child node, or if it is greater than the value of the node, it should be recursively called on the right child node. Of course, it is also necessary to check to ensure that the left or right child node actually exists before calling the function on the node.
Because binary trees have log (base 2) n layers, the average search time for a binary tree is log (base 2) n. To fill an entire binary tree, sorted, takes roughly log (base 2) n * n. Let’s take a look at the necessary code for a simple implementation of a binary tree. First, it is necessary to have a struct, or class, defined as a node.

struct node
{
int key_value;
struct node *left;
struct node *right;
};

The struct has the ability to store the key_value and contains the two child nodes which define the node as part of a tree. In fact, the node itself is very similar to the node in a linked list. A basic knowledge of the code for a linked list will be very helpful in understanding the techniques of binary trees. Essentially, pointers are necessary to allow the arbitrary creation of new nodes in the tree.

There are several important operations on binary trees, including inserting elements, searching for elements, removing elements, and deleting the tree. We’ll look at three of those four operations in this tutorial, leaving removing elements for later.

We’ll also need to keep track of the root node of the binary tree, which will give us access to the rest of the data:

struct node *root = 0;

It is necessary to initialize root to 0 for the other functions to be able to recognize that the tree does not yet exist. The destroy_tree shown below which will actually free all of the nodes of in the tree stored under the node leaf: tree.

void destroy_tree(struct node *leaf)
{
if( leaf != 0 )
{
destroy_tree(leaf->left);
destroy_tree(leaf->right);
free( leaf );
}
}

The function destroy_tree goes to the bottom of each part of the tree, that is, searching while there is a non-null node, deletes that leaf, and then it works its way back up. The function deletes the leftmost node, then the right child node from the leftmost node’s parent node, then it deletes the parent node, then works its way back to deleting the other child node of the parent of the node it just deleted, and it continues this deletion working its way up to the node of the tree upon which delete_tree was originally called. In the example tree above, the order of deletion of nodes would be 5 8 6 11 18 14 10. Note that it is necessary to delete all the child nodes to avoid wasting memory.

The following insert function will create a new tree if necessary; it relies on pointers to pointers in order to handle the case of a non-existent tree (the root pointing to NULL). In particular, by taking a pointer to a pointer, it is possible to allocate memory if the root pointer is NULL.

insert(int key, struct node **leaf)
{
if( *leaf == 0 )
{
*leaf = (struct node*) malloc( sizeof( struct node ) );
(*leaf)->key_value = key;
/* initialize the children to null */
(*leaf)->left = 0;
(*leaf)->right = 0;
}
else if(key < (*leaf)->key_value)
{
insert( key, &(*leaf)->left );
}
else if(key > (*leaf)->key_value)
{
insert( key, &(*leaf)->right );
}
}

The insert function searches, moving down the tree of children nodes, following the prescribed rules, left for a lower value to be inserted and right for a greater value, until it reaches a NULL node–an empty node–which it allocates memory for and initializes with the key value while setting the new node’s child node pointers to NULL. After creating the new node, the insert function will no longer call itself. Note, also, that if the element is already in the tree, it will not be added twice.

struct node *search(int key, struct node *leaf)
{
if( leaf != 0 )
{
if(key==leaf->key_value)
{
return leaf;
}
else if(key<leaf->key_value)
{
return search(key, leaf->left);
}
else
{
return search(key, leaf->right);
}
}
else return 0;
}

The search function shown above recursively moves down the tree until it either reaches a node with a key value equal to the value for which the function is searching or until the function reaches an uninitialized node, meaning that the value being searched for is not stored in the binary tree. It returns a pointer to the node to the previous instance of the function which called it. 

Lesson 17: Functions with Variable Argument Lists in C using va_list


Perhaps you would like to have a function that will accept any number of values and then return the average. You don’t know how many arguments will be passed in to the function. One way you could make the function would be to accept a pointer to an array. Another way would be to write a function that can take any number of arguments. So you could write avg(4, 12.2, 23.3, 33.3, 12.1); or you could write avg(2, 2.3, 34.4); The advantage of this approach is that it’s much easier to change the code if you want to change the number of arguments. Indeed, some library functions can accept a variable list of arguments (such as printf–I bet you’ve been wondering how that works!).

Whenever a function is declared to have an indeterminate number of arguments, in place of the last argument you should place an ellipsis (which looks like ‘…’), so, int a_function ( int x, … ); would tell the compiler the function should accept however many arguments that the programmer uses, as long as it is equal to at least one, the one being the first, x.

We’ll need to use some macros (which work much like functions, and you can treat them as such) from the stdarg.h header file to extract the values stored in the variable argument list–va_start, which initializes the list, va_arg, which returns the next argument in the list, and va_end, which cleans up the variable argument list.

To use these functions, we need a variable capable of storing a variable-length argument list–this variable will be of type va_list. va_list is like any other type. For example, the following code declares a list that can be used to store a variable number of arguments.

 
va_list a_list;

va_start is a macro which accepts two arguments, a va_list and the name of the variable that directly precedes the ellipsis (“…”). So in the function a_function, to initialize a_list with va_start, you would write va_start ( a_list, x );

 
int a_function ( int x, ... )
{
va_list a_list;
va_start( a_list, x );
}

va_arg takes a va_list and a variable type, and returns the next argument in the list in the form of whatever variable type it is told. It then moves down the list to the next argument. For example, va_arg ( a_list, double ) will return the next argument, assuming it exists, in the form of a double. The next time it is called, it will return the argument following the last returned number, if one exists. Note that you need to know the type of each argument–that’s part of why printf requires a format string! Once you’re done, use va_end to clean up the list: va_end( a_list );

To show how each of the parts works, take an example function:

 
#include <stdarg.h>
#include <stdio.h>

double average ( int num, ... )
{
va_list arguments;
double sum = 0;

/* Initializing arguments to store all values after num */
va_start ( arguments, num );
/* Sum all the inputs; we still rely on the function caller to tell us how
* many there are */
for ( int x = 0; x < num; x++ )
{
sum += va_arg ( arguments, double );
}
va_end ( arguments ); // Cleans up the list

return sum / num;
}

int main()
{
printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) );
printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
}

It isn’t necessarily a good idea to use a variable argument list at all times; the potential exists for assuming a value is of one type, while it is in fact another, such as a null pointer being assumed to be an integer. Consequently, variable argument lists should be used sparingly.

Lesson 16: Recursion in C


Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C++, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to “repeat the process”. This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the “process” to sometimes be completed without the recursive call. One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the “build wall” function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.

A simple example of recursion would be:

 
void recurse()
{
recurse(); /* Function calls itself */
}

int main()
{
recurse(); /* Sets off the recursion */
return 0;
}

This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without ending, the program will crash. Why not write a program to see how many times the function is called before the program terminates?

 
#include <stdio.h>

void recurse ( int count ) /* Each call gets its own copy of count */
{
printf( "%d\n", count );
/* It is not necessary to increment count since each function's
variables are separate (so each count will be initialized one greater)
*/
recurse ( count + 1 );
}

int main()
{
recurse ( 1 ); /* First function call, so it starts at one */
return 0;
}

This simple program will show the number of times the recurse function has been called by initializing each individual function call’s count variable one greater than it was previous by passing in count + 1. Keep in mind that it is not a function call restarting itself; it is hundreds of function calls that are each unfinished.

The best way to think of recursion is that each function call is a “process” being carried out by the computer. If we think of a program as being carried out by a group of people who can pass around information about the state of a task and instructions on performing the task, each recursive function call is a bit like each person asking the next person to follow the same set of instructions on some part of the task while the first person waits for the result.

At some point, we’re going to run out of people to carry out the instructions, just as our previous recursive functions ran out of space on the stack. There needs to be a way to avoid this! To halt a series of recursive calls, a recursive function will have a condition that controls when the function will finally stop calling itself. The condition where the function will not call itself is termed the base case of the function. Basically, it will usually be an if-statement that checks some variable for a condition (such as a number being less than zero, or greater than some other number) and if that condition is true, it will not allow the function to call itself again. (Or, it could check if a certain condition is true and only then allow the function to call itself).

A quick example:

 
void count_to_ten ( int count )
{
/* we only keep counting if we have a value less than ten
if ( count < 10 )
{
count_to_ten( count + 1 );
}
}
int main()
{
count_to_ten ( 0 );
}

This program ends when we’ve counted to ten, or more precisely, when count is no longer less than ten. This is a good base case because it means that if we have an input greater than ten, we’ll stop immediately. If we’d chosen to stop when count equaled ten, then if the function were called with the input 11, it would run out of memory before stopping.

Notice that so far, we haven’t done anything with the result of a recursive function call. Each call takes place and performs some action that is then ignored by the caller. It is possible to get a value back from the caller, however. It’s also possible to take advantage of the side effects of the previous call. In either case, once a function has called itself, it will be ready to go to the next line after the call. It can still perform operations. One function you could write could print out the numbers 123456789987654321. How can you use recursion to write a function to do this? Simply have it keep incrementing a variable passed in, and then output the variable twice: once before the function recurses, and once after.

 
void printnum ( int begin )
{
printf( "%d", begin );
if ( begin < 9 ) /* The base case is when begin is no longer */
{ /* less than 9 */
printnum ( begin + 1 );
}
/* display begin again after we've already printed everything from 1 to 9
* and from 9 to begin + 1 */
printf( "%d", begin );
}

This function works because it will go through and print the numbers begin to 9, and then as each printnum function terminates it will continue printing the value of begin in each function from 9 to begin.

This is, however, just touching on the usefulness of recursion. Here’s a little challenge: use recursion to write a program that returns the factorial of any number greater than 0. (Factorial is number * (number – 1) * (number – 2) … * 1).

Hint: Your function should recursively find the factorial of the smaller numbers first, i.e., it takes a number, finds the factorial of the previous number, and multiplies the number times that factorial…have fun. 🙂 

Lesson 15: Singly linked lists in C


Linked lists are a way to store data with structures so that the programmer can automatically create a new place to store data whenever necessary. Specifically, the programmer writes a struct definition that contains variables holding information about something and that has a pointer to a struct of its same type (it has to be a pointer–otherwise, every time an element was created, it would create a new element, infinitely). Each of these individual structs or classes in the list is commonly known as a node or element of the list.

One way to visualize a linked list is as though it were a train. The programmer always stores the first node of the list in a pointer he won’t lose access to. This would be the engine of the train. The pointer itself is the connector between cars of the train. Every time the train adds a car, it uses the connectors to add a new car. This is like a programmer using malloc to create a pointer to a new struct.

In memory a linked list is often described as looking like this:

 
---------- ----------
- Data - - Data -
---------- ----------
- Pointer- - - -> - Pointer-
---------- ----------

The representation isn’t completely accurate in all of its details, but it will suffice for our purposes. Each of the big blocks is a struct that has a pointer to another one. Remember that the pointer only stores the memory location of something–it is not that thing itself–so the arrow points to the next struct. At the end of the list, there is nothing for the pointer to point to, so it does not point to anything; it should be a null pointer or a dummy node to prevent the node from accidentally pointing to a random location in memory (which is very bad).

So far we know what the node struct should look like:

 
#include <stdlib.h>

struct node {
int x;
struct node *next;
};

int main()
{
/* This will be the unchanging first node */
struct node *root;

/* Now root points to a node struct */
root = malloc( sizeof(struct node) );

/* The node root points to has its next pointer equal to a null pointer
set */
root->next = 0;
/* By using the -> operator, you can modify what the node,
a pointer, (root in this case) points to. */
root->x = 5;
}

This so far is not very useful for doing anything. It is necessary to understand how to traverse (go through) the linked list before it really becomes useful. This will allow us to store some data in the list and later find it without knowing exactly where it is located.

Think back to the train. Let’s imagine a conductor who can only enter the train through the first car and can walk through the train down the line as long as the connector connects to another car. This is how the program will traverse the linked list. The conductor will be a pointer to node, and it will first point to root, and then, if the root’s pointer to the next node is pointing to something, the “conductor” (not a technical term) will be set to point to the next node. In this fashion, the list can be traversed. Now, as long as there is a pointer to something, the traversal will continue. Once it reaches a null pointer (or dummy node), meaning there are no more nodes (train cars) then it will be at the end of the list, and a new node can subsequently be added if so desired.

Here’s what that looks like:

 
#include <stdio.h>
#include <stdlib.h>

struct node {
int x;
struct node *next;
};

int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;

root = malloc( sizeof(struct node) );
root->next = 0;
root->x = 12;
conductor = root;
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );

conductor = conductor->next;

if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = 0;
conductor->x = 42;

return 0;
}

That is the basic code for traversing a list. The if statement ensures that the memory was properly allocated before traversing the list. If the condition in the if statement evaluates to true, then it is okay to try and access the node pointed to by conductor. The while loop will continue as long as there is another pointer in the next. The conductor simply moves along. It changes what it points to by getting the address of conductor->next.

Finally, the code at the end can be used to add a new node to the end. Once the while loop as finished, the conductor will point to the last node in the array. (Remember the conductor of the train will move on until there is nothing to move on to? It works the same way in the while loop.) Therefore, conductor->next is set to null, so it is okay to allocate a new area of memory for it to point to (if it weren’t NULL, then storing something else in the pointer would cause us to lose the memory that it pointed to). When we allocate the memory, we do a quick check to ensure that we’re not out of memory, and then the conductor traverses one more element (like a train conductor moving on to the newly added car) and makes sure that it has its pointer to next set to 0 so that the list has an end. The 0 functions like a period; it means there is no more beyond. Finally, the new node has its x value set. (It can be set through user input. I simply wrote in the ‘=42’ as an example.)

To print a linked list, the traversal function is almost the same. In our first example, it is necessary to ensure that the last element is printed after the while loop terminates. (See if you can think of a better way before reading the second code example.)

For example:

 
conductor = root;
if ( conductor != 0 ) { /* Makes sure there is a place to start */
while ( conductor->next != 0 ) {
printf( "%d\n", conductor->x );
conductor = conductor->next;
}
printf( "%d\n", conductor->x );
}

The final output is necessary because the while loop will not run once it reaches the last node, but it will still be necessary to output the contents of the next node. Consequently, the last output deals with this. We can avoid this redundancy by allowing the conductor to walk off of the back of the train. Bad for the conductor (if it were a real person), but the code is simpler as it also allows us to remove the initial check for null (if root is null, then conductor will be immediately set to null and the loop will never begin):

 
conductor = root;
while ( conductor != NULL ) {
printf( "%d\n", conductor->x );
conductor = conductor->next;
}

Lesson 14: Accepting command line arguments in C using argc and argv


In C it is possible to accept command line arguments. Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. To use command line arguments in your program, you must first understand the full declaration of the main function, which previously has accepted no arguments. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.

The full declaration of main looks like this:

 
int main ( int argc, char *argv[] )

The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program.

The array of character pointers is the listing of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument. You can use each argv element just like a string, or use argv as a two dimensional array. argv[argc] is a null pointer.

How could this be used? Almost any program that wants its parameters to be set when it is executed would use this. One common use is to write a function that takes the name of a file and outputs the entire text of it onto the screen.

 
#include <stdio.h>

int main ( int argc, char *argv[] )
{
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen( argv[1], "r" );

/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
int x;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( ( x = fgetc( file ) ) != EOF )
{
printf( "%c", x );
}
fclose( file );
}
}
}

This program is fairly short, but it incorporates the full version of main and even performs a useful function. It first checks to ensure the user added the second argument, theoretically a file name. The program then checks to see if the file is valid by trying to open it. This is a standard operation, and if it results in the file being opened, then the return value of fopen will be a valid FILE*; otherwise, it will be 0, the NULL pointer. After that, we just execute a loop to print out one character at a time from the file. The code is self-explanatory, but is littered with comments; you should have no trouble understanding its operation this far into the tutorial. 🙂 

Lesson 11: Typecasting


Typecasting is a way to make a variable of one type, such as an int, act like another type, such as a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make ‘a’ function as a char.

For example:

 
#include <stdio.h>

int main()
{
/* The (char) is a typecast, telling the computer to interpret the 65 as a
character, not as a number. It is going to give the character output of
the equivalent of the number 65 (It should be the letter A for ASCII).
Note that the %c below is the format code for printing a single character
*/
printf( "%c\n", (char)65 );
getchar();
}

One use for typecasting for is when you want to use the ASCII characters. For example, what if you want to create your own chart of all 256 ASCII characters. To do this, you will need to use to typecast to allow you to print out the integer as its character equivalent.

 
#include <stdio.h>

int main()
{
for ( int x = 0; x < 256; x++ ) {
/* Note the use of the int version of x to output a number and the use
* of (char) to typecast the x into a character which outputs the
* ASCII character that corresponds to the current number
*/
printf( "%d = %c\n", x, (char)x );
}
getchar();

}

If you were paying careful attention, you might have noticed something kind of strange: when we passed the value of x to printf as a char, we’d already told the compiler that we intended the value to be treated as a character when we wrote the format string as %c. Since the char type is just a small integer, adding this typecast actually doesn’t add any value!

So when would a typecast come in handy? One use of typecasts is to force the correct type of mathematical operation to take place. It turns out that in C (and other programming languages), the result of the division of integers is itself treated as an integer: for instance, 3/5 becomes 0! Why? Well, 3/5 is less than 1, and integer division ignores the remainder.

On the other hand, it turns out that division between floating point numbers, or even between one floating point number and an integer, is sufficient to keep the result as a floating point number. So if we were performing some kind of fancy division where we didn’t want truncated values, we’d have to cast one of the variables to a floating point type. For instance, (float)3/5 comes out to .6, as you would expect!

When might this come up? It’s often reasonable to store two values in integers. For instance, if you were tracking heart patients, you might have a function to compute their age in years and the number of heart times they’d come in for heart pain. One operation you might conceivably want to perform is to compute the number of times per year of life someone has come in to see their physician about heart pain. What would this look like?

 
/* magical function returns the age in years */
int age = getAge();
/* magical function returns the number of visits */
int pain_visits = getVisits();

float visits_per_year = pain_visits / age;

The problem is that when this program is run, visits_per_year will be zero unless the patient had an awful lot of visits to the doc. The way to get around this problem is to cast one of the values being divided so it gets treated as a floating point number, which will cause the compiler to treat the expression as if it were to result in a floating point number:

 
float visits_per_year = pain_visits / (float)age;
/* or */
float visits_per_year = (float)pain_visits / age;

C File I/O and Binary File I/O



When accessing files through C, the first necessity is to have a way to access the files. For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. (You can think of it as the memory address of the file or the location of the file).

For example:

FILE *fp;

To open a file you need to use the fopen function, which returns a FILE pointer. Once you’ve opened a file, you can use the FILE pointer to let the compiler perform input and output functions on the file.

FILE *fopen(const char *filename, const char *mode);

In the filename, if you use a string literal as the argument, you need to remember to use double backslashes rather than a single backslash as you otherwise risk an escape character such as \t. Using double backslashes \\ escapes the \ key, so the string works as it is expected. Your users, of course, do not need to do this! It’s just the way quoted strings are handled in C and C++.

The modes are as follows:

r  - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)

Note that it’s possible for fopen to fail even if your program is perfectly correct: you might try to open a file specified by the user, and that file might not exist (or it might be write-protected). In those cases, fopen will return 0, the NULL pointer.

Here’s a simple example of using fopen:

FILE *fp;
fp=fopen("c:\\test.txt", "r");

This code will open test.txt for reading in text mode. To open a file in a binary mode you must add a b to the end of the mode string; for example, “rb” (for the reading and writing modes, you can add the b either after the plus sign – “r+b” – or before – “rb+”)

To close a function you can use the function

int fclose(FILE *a_file);

fclose returns zero if the file is closed successfully.

An example of fclose is

fclose(fp);

To work with text input and output, you use fprintf and fscanf, both of which are similar to their friends printf and scanf except that you must pass the FILE pointer as first argument. For example:

FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");

It is also possible to read (or write) a single character at a time–this can be useful if you wish to perform character-by-character input (for instance, if you need to keep track of every piece of punctuation in a file it would make more sense to read in a single character than to read in a string at a time.) The fgetc function, which takes a file pointer, and returns an int, will let you read a single character from a file:

int fgetc (FILE *fp);

Notice that fgetc returns an int. What this actually means is that when it reads a normal character in the file, it will return a value suitable for storing in an unsigned char (basically, a number in the range 0 to 255). On the other hand, when you’re at the very end of the file, you can’t get a character value–in this case, fgetc will return “EOF”, which is a constant that indicates that you’ve reached the end of the file. To see a full example using fgetc in practice, take a look at the example here.

The fputc function allows you to write a character at a time–you might find this useful if you wanted to copy a file character by character. It looks like this:

int fputc( int c, FILE *fp );

Note that the first argument should be in the range of an unsigned char so that it is a valid character. The second argument is the file to write to. On success, fputc will return the value c, and on failure, it will return EOF.

Binary I/O

For binary File I/O you use fread and fwrite.

The declarations for each are similar:

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);

Both of these functions deal with blocks of memories – usually arrays. Because they accept pointers, you can also use these functions with other data structures; you can even write structs to a file or a read struct into memory.

Let’s look at one function to see how the notation works.

fread takes four arguments. Don’t by confused by the declaration of a void *ptr; void means that it is a pointer that can be used for any type variable. The first argument is the name of the array or the address of the structure you want to write to the file. The second argument is the size of each element of the array; it is in bytes. For example, if you have an array of characters, you would want to read it in one byte chunks, so size_of_elements is one. You can use the sizeof operator to get the size of the various datatypes; for example, if you have a variable int x; you can get the size of x with sizeof(x);. This usage works even for structs or arrays. E.g., if you have a variable of a struct type with the name a_struct, you can use sizeof(a_struct) to find out how much memory it is taking up.

e.g.,

sizeof(int);

The third argument is simply how many elements you want to read or write; for example, if you pass a 100 element array, you want to read no more than 100 elements, so you pass in 100.

The final argument is simply the file pointer we’ve been using. When fread is used, after being passed an array, fread will read from the file until it has filled the array, and it will return the number of elements actually read. If the file, for example, is only 30 bytes, but you try to read 100 bytes, it will return that it read 30 bytes. To check to ensure the end of file was reached, use the feof function, which accepts a FILE pointer and returns true if the end of the file has been reached.

fwrite is similar in usage, except instead of reading into the memory you write from memory into a file.

For example,

FILE *fp;
fp=fopen("c:\\test.bin", "wb");
char x[10]="ABCDEFGHIJ";
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fp);

Lesson 9: C Strings


This lesson will discuss C-style strings, which you may have already seen in the array tutorial. In fact, C-style strings are really arrays of chars with a little bit of special sauce to indicate where the string ends. This tutorial will cover some of the tools available for working with strings–things like copying them, concatenating them, and getting their length.

What is a String?

Note that along with C-style strings, which are arrays, there are also string literals, such as “this”. In reality, both of these string types are merely just collections of characters sitting next to each other in memory. The only difference is that you cannot modify string literals, whereas you can modify arrays. Functions that take a C-style string will be just as happy to accept string literals unless they modify the string (in which case your program will crash). Some things that might look like strings are not strings; in particular, a character enclosed in single quotes, like this, ‘a’, is not a string. It’s a single character, which can be assigned to a specific location in a string, but which cannot be treated as a string. (Remember how arrays act like pointers when passed into functions? Characters don’t, so if you pass a single character into a function, it won’t work; the function is expecting a char*, not a char.)

To recap: strings are arrays of chars. String literals are words surrounded by double quotation marks.

 
"This is a static string"

Remember that special sauce mentioned above? Well, it turns out that C-style strings are always terminated with a null character, literally a ” character (with the value of 0), so to declare a string of 49 letters, you need to account for it by adding an extra character, so you would want to say:

 
char string[50];

This would declare a string with a length of 50 characters. Do not forget that arrays begin at zero, not 1 for the index number. In addition, we’ve accounted for the extra with a null character, literally a ” character. It’s important to remember that there will be an extra character on the end on a string, just like there is always a period at the end of a sentence. Since this string terminator is unprintable, it is not counted as a letter, but it still takes up a space. Technically, in a fifty char array you could only hold 49 letters and one null character at the end to terminate the string.

Note that something like

 
char *my_string;

can also be used as a string. If you have read the tutorial on pointers, you can do something such as:

 
arry = malloc( sizeof(*arry) * 256 );

which allows you to access arry just as if it were an array. To free the memory you allocated, just use free:

For example:

 
free ( arry );

Using Strings

Strings are useful for holding all types of long input. If you want the user to input his or her name, you must use a string. Using scanf() to input a string works, but it will terminate the string after it reads the first space, and moreover, because scanf doesn’t know how big the array is, it can lead to “buffer overflows” when the user inputs a string that is longer than the size of the string (which acts as an input “buffer”).

There are several approaches to handling this problem, but probably the simplest and safest is to use the fgets function, which is declared in stdio.h.

The prototype for the fgets function is:

 
char *fgets (char *str, int size, FILE* file);

There are a few new things here. First of all, let’s clear up the questions about that funky FILE* pointer. The reason this exists is because fgets is supposed to be able to read from any file on disk, not just from the user’s keyboard (or other “standard input” device). For the time being, whenever we call fgets, we’ll just pass in a variable called stdin, defined in stdio.h, which refers to “standard input”. This effectively tells the program to read from the keyboard. The other two arguments to fgets, str and size, are simply the place to store the data read from the input and the size of the char*, str. Finally, fgets returns str whenever it successfully read from the input.

When fgets actually reads input from the user, it will read up to size – 1 characters and then place the null terminator after the last character it read. fgets will read input until it either has no more room to store the data or until the user hits enter. Notice that fgets may fill up the entire space allocated for str, but it will never return a non-null terminated string to you.

Let’s look at an example of using fgets, and then we’ll talk about some pitfalls to watch out for.

For a example:

 
#include <stdio.h>

int main()
{
/* A nice long string */
char string[256];

printf( "Please enter a long string: " );

/* notice stdin being passed in */
fgets ( string, 256, stdin );

printf( "You entered a very long string, %s", string );

getchar();
}

Remember that you are actually passing the address of the array when you pass string because arrays do not require an address operator (&) to be used to pass their addresses, so the values in the array string are modified.

The one thing to watch out for when using fgets is that it will include the newline character (‘\n’) when it reads input unless there isn’t room in the string to store it. This means that you may need to manually remove the input. One way to do this would be to search the string for a newline and then replace it with the null terminator. What would this look like? See if you can figure out a way to do it before looking below:

 
char input[256];
int i;

fgets( input, 256, stdin );

for ( i = 0; i < 256; i++ )
{
if ( input[i] == '\n' )
{
input[i] = '';
break;
}
}

Here, we just loop through the input until we come to a newline, and when we do, we replace it with the null terminator. Notice that if the input is less than 256 characters long, the user must have hit enter, which would have included the newline character in the string! (By the way, aside from this example, there are other approaches to solving this problem that use functions from string.h.)

Manipulating C strings using string.h

string.h is a header file that contains many functions for manipulating strings. One of these is the string comparison function.

 
int strcmp ( const char *s1, const char *s2 );

strcmp will accept two strings. It will return an integer. This integer will either be:

 
Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.

Strcmp performs a case sensitive comparison; if the strings are the same except for a difference in cAse, then they’re countered as being different. Strcmp also passes the address of the character array to the function to allow it to be accessed.

 
char *strcat ( char *dest, const char *src );

strcat is short for “string concatenate”; concatenate is a fancy word that means to add to the end, or append. It adds the second string to the first string. It returns a pointer to the concatenated string. Beware this function; it assumes that dest is large enough to hold the entire contents of src as well as its own contents.

 
char *strcpy ( char *dest, const char *src );

strcpy is short for string copy, which means it copies the entire contents of src into dest. The contents of dest after strcpy will be exactly the same as src such that strcmp ( dest, src ) will return 0.

 
size_t strlen ( const char *s );

strlen will return the length of a string, minus the terminating character (”). The size_t is nothing to worry about. Just treat it as an integer that cannot be negative, which is what it actually is. (The type size_t is just a way to indicate that the value is intended for use as a size of something.)

Here is a small program using many of the previously described functions:

 
#include <stdio.h> /* stdin, printf, and fgets */
#include <string.h> /* for all the new-fangled string functions */

/* this function is designed to remove the newline from the end of a string
entered using fgets. Note that since we make this into its own function, we
could easily choose a better technique for removing the newline. Aren't
functions great? */
void strip_newline( char *str, int size )
{
int i;

/* remove the null terminator */
for ( i = 0; i < size; ++i )
{
if ( str[i] == '\n' )
{
str[i] = '';

/* we're done, so just exit the function by returning */
return;
}
}
/* if we get all the way to here, there must not have been a newline! */
}

int main()
{
char name[50];
char lastname[50];
char fullname[100]; /* Big enough to hold both name and lastname */

printf( "Please enter your name: " );
fgets( name, 50, stdin );

/* see definition above */
strip_newline( name, 50 );

/* strcmp returns zero when the two strings are equal */
if ( strcmp ( name, "Alex" ) == 0 )
{
printf( "That's my name too.\n" );
}
else
{
printf( "That's not my name.\n" );
}
// Find the length of your name
printf( "Your name is %d letters long", strlen ( name ) );
printf( "Enter your last name: " );
fgets( lastname, 50, stdin );
strip_newline( lastname, 50 );
fullname[0] = '';
/* strcat will look for the and add the second string starting at
that location */
strcat( fullname, name ); /* Copy name into full name */
strcat( fullname, " " ); /* Separate the names by a space */
strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */
printf( "Your full name is %s\n",fullname );

getchar();

return 0;
}

Safe Programming

The above string functions all rely on the existence of a null terminator at the end of a string. This isn’t always a safe bet. Moreover, some of them, noticeably strcat, rely on the fact that the destination string can hold the entire string being appended onto the end. Although it might seem like you’ll never make that sort of mistake, historically, problems based on accidentally writing off the end of an array in a function like strcat, have been a major problem.

Fortunately, in their infinite wisdom, the designers of C have included functions designed to help you avoid these issues. Similar to the way that fgets takes the maximum number of characters that fit into the buffer, there are string functions that take an additional argument to indicate the length of the destination buffer. For instance, the strcpy function has an analogous strncpy function

 
char *strncpy ( char *dest, const char *src, size_t len );

which will only copy len bytes from src to dest (len should be less than the size of dest or the write could still go beyond the bounds of the array). Unfortunately, strncpy can lead to one niggling issue: it doesn’t guarantee that dest will have a null terminator attached to it (this might happen if the string src is longer than dest). You can avoid this problem by using strlen to get the length of src and make sure it will fit in dest. Of course, if you were going to do that, then you probably don’t need strncpy in the first place, right? Wrong. Now it forces you to pay attention to this issue, which is a big part of the battle.