Credits

Saturday, February 28, 2009

Keyboard Input in Java with Array

A keyboard input is required in any program, check the sample keyboard class below with array integration.



[+/-] show/hide




class OneDarray{
public static void main(String args[])
throws java.io.IOException{
int t, i;
int num []=new int[3];
int sum=0;

int xnum;
for (t=0;t<3;t++){
System.out.println("Input a number and hit enter key :" );
do
{
xnum=(int)System.in.read(); /*this line allows type casting from char to int from keyboard input*/
num[t]=xnum;
System.out.print(num[t]);
}while(xnum!='\n');

sum=sum+num[t];
}
System.out.println("The sum of 3 numbers "+sum);}}

Methods with Parameters and Returned Values in Java

A method in Java may contain parameters and may or may not return values. The data type of the returned value shall determine the datatype of the method.

Check the sample program below.



[+/-] show/hide



public class samplemethods2{
public static void main(String [] args){
double radius=5,pi=3.1416;
samplemethods1.init();
System.out.print("The area is "+compute(radius,pi) );
}

public static double compute(double rad,double PI)
{
return rad*PI; */the result of this is passed to the invoking class*/
}}

Methods as Functions of Java

Like C or C++, modular programming is also enforced in Java. We employ this through methods.

A method must be defined inside a class but this can be called from other classes.
Try the sample class below.



[+/-] show/hide



public class samplemethods1{
public static void main(String [] args){

System.out.print("hello\n");
init(); /*invoking the method*/
}

public static void init() /*this is the method*/
{
System.out.print("hi\n");
}}

Multi-Dimensional Arrays of Java

Typical in other programming languages are two - dimensional arrays. In Java, we can have more than 2-D arrays.

General syntax for 2-D array:

datatype arrayname[ ][ ] = new datatype[row_size][col_size];

eg.:
int table[ ] [ ] =new int[3][2];

Check the sample programs below:



[+/-] show/hide



class TwoDarray{
public static void main(String args[]){
int t, i;
int table [][]=new int[3][4];
for (t=0;t<3;t++){
for (i=0;i<4;++i){
table[t][i]=(t*4)+i+1;
System.out.print(table[t][i]+" ");
}
System.out.println();}}}

/* another program*/

class TwoDarray{
public static void main(String args[]){
int sqrs[][]={
{1,1},
{2,4},
{3,9}};

int i,j;
for (i=0;i<10;i++){
for (j=0;j<2;++j){
System.out.print(sqrs[i][j]+" ");
System.out.println();
}}}}

What are the output of these two classes?

Java Sorting Program using Array

Sorting is a technique to arrange elements in a pattern or orderly manner. Various sorting techniques can be applied. However, if elements are in bigger number, these sorting techniques may show a distinguishing difference from one another.

Sorting techniques can be bubble sort, selection sort, insertion sort, heap sort, merge sort and quick sort.

But bubble sort can be implemented through Java. Check the program below.



[+/-] show/hide




//program to bubble sort
class onedarray{
public static void main (String [] args){
int sample[]={99,-10,100123,18,-978,5623,463,-9,287,49};
int i,a,b,t;
int size=10;
System.out.print("\nThe unsorted array elements are ");
for(i=0;i<10;i++)
System.out.print(" "+sample[i]);

//sorting technique
for(a=1;\ /*concatenate the next line*/
a

for (b=size-1;b>=a;b--){
if (sample[b-1]>sample[b]){
//if out of order
//exchange elements
t=sample[b-1];
sample[b-1]=sample[b];
sample[b]=t;
}
}

System.out.print("\nThe sorted array elements are ");
for(i=0;i<10;i++)
System.out.print(" "+sample[i]);
}
}

More Java Single Array Sample

Check other sample programs of the single dimensional array in Java.



[+/-] show/hide


//program to check largest/smallest number
class onedarray{
public static void main (String [] args){
int sample[]={99,-10,100123,18,-978,5623,463,-9,287,49};
int i,min,max;
min=max=sample[0];
for(i=0;i<10;i++)
{ if (sample[i]>min)
min=sample[i];
if (sample[i]\ /* the slash symbol means to concatenate the next line*/
max==sample[i];}

System.out.println("The lowest number is "+min );
System.out.println("The largest number is "+max );
}
}

The output is expected to display the lowest and largest number from the initial elements given.

Single Dimensional Array in Java

Just like in C or C++, Java possesses advanced data types like array. We define array as a collection of similar elements.

A general syntax in Java for array elements is the one below:

data_type arrayname[ ] = new data_type[size];
eg.
int sample[]=new int[10];

other form of syntax declarations could be this:
int sample[]={1,2,3,4}; /* the number of initial elements tell the size of the array*/



/* sample one dimensional array elements*/

//program to assign array elements
class onedarray{
public static void main (String [] args){
int sample[]=new int[10];
int i;
for(i=0;i<10;i++)
sample[i]=i;
for(i=0;i<10;i++)
System.out.println("Sample ["+i+"]:"+sample[i]);
}
}

What is the output of this code?

Thursday, February 26, 2009

Structures or Records

A structure is defined as a collection of variables that are referenced under a name. In Pascal, we call this a record. In C or C++, we call this a structure, and in Java, we call this object.

General syntax of structure in C or C++:

struct structure_tag_name{
type variable_name1;
:
:
type variable_nameN;
} structure_variables;

sample structure definition:

struct address{
char name[30];
char street[30];
char zip[4];
};

or

struct {
char name[30];
char street[30];
char zip[4];
} address_info;

The difference in the two can be possible but not the same declaration may miss both the structure name or variables.

to assign or access the structure element:

strcpy(address_info.zip,"9500");
printf("%s",address_info.zip);

on the screen, you will see:
9500

See the complete sample program:



[+/-] show/hide




#include stdio.h /*enclose this library in <> */

main()
{
struct my_info{
char name[30];
float height;
float weight;
};

strcpy(my_info.name,"Rosilie");
my_info.height=64.0;
my_info.weight=48.0;

printf("\nHello %s",my_info.name);
printf("\nYou are %f inches tall",my_info.height);
printf("\nYou weigh %s kilograms",my_info.weight);
getche();
}

What is the output of the code above?
Translate this in C++.

Monday, February 23, 2009

Brain Twister

Using your prior knowledge in functions, perform the following:

1. A program that reads 10 integers and checks the smallest and biggest number.
2. A program that reads N sales of items, their unit price and quantity, and computes the total charges and change from the cash given.

Learn Functions More-Part 2

Sometimes, functions must return and/or pass a value. So, the function type will be based on the data type of the value returned. Check the sample programs below.



[+/-] show/hide




#include stdio.h /*enclose this in <> */
int compute(int len, int wid);

main()
{
clrscr();
printf("\nEnter a dimension for length of the rectangle : ");
scanf("%d",&length);
printf("\nEnter a dimension for width of the rectangle : ");
scanf("%d",&width);
printf("The area of the rectangle is %d ",compute(length,width)); /*inside your function compute, we call these the actual parameters whose values are passed to the formal parameters*/
getche();
}

int compute(int len, int wid) /* these are your formal parameters */
{
return len * wid; /* the product of length and width is returned back to main function. The data type of this returned value shall define the function datatype. */
}

In Bloodshed C++:

#include iostream /*enclose this in <> */
using namespace std;
int compute(int len, int wid);

main()
{
cout<<"Enter a dimension for length of the rectangle : ";
cin>>length;
cout<<
"Enter a dimension for width of the rectangle : ";
/* add endl for the newline before the text */
cin>>width;
cin.ignore();
cout<<
"The area of the rectangle is %d "+compute(length,width); /*inside your function compute, we call these the actual parameters whose values are passed to the formal parameters*/
cin.get();
}

int compute(int len, int wid) /* these are your formal parameters */
{
return len * wid; /* the product of length and width is returned back to main function. The data type of this returned value shall define the function datatype. */
}

Learn Functions More-Part 1

One desirable approach to programming is to modularize your system. One approach is to use functions or procedures or modules whatever is the term used in the language you are in.

In C or C++, we call this modular structures as functions. We have at least one function in C or C++, the main( ). Regardless of the number of functions defined, this main function is always executed first.

What is a function?

-Schi (1992) defined this as, "the building of C in which all program activity occurs"
-It is also called as a subprogram/subroutine that performs a specific task, operation, or computation that may return or not a value.
-It is executed through a function call.
-Its general syntax is this:

function declaration is this:
function_datatype functionname(parameters);


Function definition is this:
function_datatype functionname(parameters)
{
body_of_ the_function;
}

Sample program:



[+/-] show/hide




#include stdio.h /*enclose this library in between <> */
/*function declaration at this line */
void greet1();
void greet2();

main()
{
clrscr(); /* also a function call to clear the screen */
greet1(); /* a function call to greet1 */
greet2(); /* a function call to greet2 */
getche();
}

/*function defintion at this line */
void greet1()
{
printf("Hello there!\n");
}

void greet2()
{
printf("Welcome to modular programming!);
}

The expected output:
Hello there!
Welcome to modular programming!

Sunday, February 22, 2009

Another Single Array Sample Program

Conversion of number systems may be a little confusing but not at all impossible. Use the codes below as basis for a more improved conversion from decimal to hexadecimals.



[+/-] show/hide



/* program to convert decimals to hexadecimals or base 16 */
# include stdio.h /* enclose the library in <> */
main()
{
float quofloat, decimal;
int dec, quotient;
int ctr;
int converted[10];
clrscr();

printf("Enter decimal digits : ");
scanf("%",&decimal);

quofloat=decimal;

ctr=0;
do
{
quofloat=quofloat/16;
quotient=quofloat%16;
printf("%.2f division by 16\n",quofloat);
converted[ctr]=quotient;
printf(" remainder: %d\n ",converted[ctr]);
ctr=ctr+1;
}
while(quofloat>=1);
getch();
}

Translate this to C++.

Saturday, February 21, 2009

Brain Twisters

From the problems below, create a C, C++ or Java program to solve them.

1. To check the number of occurence per number in the list.
2. To create a menu to convert a temperature from Celsius, Kelvin, and Fahrenheit
3. To create a unit conversion from ounces,pounds,grams, kilograms, and tons.
4. To read 5 grades and compute their average.

Single Dimensional Array

Arrays are complex data structures in any programming language.

The program below searches a number from a given list and count its occurence.



[+/-] show/hide




#include stdio.h /* enclose this with <> */
main()
{
int number[10],x,search,occurence=0;

printf("Input 10 numbers :");
for (x=0;x<10;x++)
{ scanf("%d",&number[x]);}

printf("input a number to search:" );
scanf("%d",&search);

for (x=0;x<10;x++)
{ if (search==number[x])
occurence++;
}

if (occurence==0)
printf("YOur searched number is not in the input list.");
else
printf("There are %d of your searched number %d.",occurence,search);
getch();
}

You can rewrite this in C++.

String Manipulation with C

C makes use of string functions to perform certain string operation.

Below is a program that checks whether the word encoded is a palindrome or not.
Sample palindromes are the following:

mom
dad
noon
wow
etc.

Palindromes are words that can be read forward or backward. Check the program below to test if your words encoded are palindrome or not.



[+/-] show/hide



#include stdio.h /*enclose the library with <> */
#include string.h /*enclose the library with <> */

main()
{
char w1[10],w2[10],wr[10];
int same;
clrscr();
printf("enter a word\n");gets(w1);
strcpy(w2,w1); /* copies the value of string w1 to w2 */
strcpy(wr,strrev(w2)); /* reverses the value of string w2*/
same=strcmpi(w1,wr); /* compares the two strings */
if (same==0)
printf("Your word %s is a palindrome.",w1);
else
printf("Your word %s is not a palindrome",w1);
getch();
}

Java's Loop Sample Programs

Here are more Java sample loop structures. You can add nested loops or loops inside another loop. Just don't get all tangled!!!!



[+/-] show/hide




//Multiplication table
class SquareCube{
public static void main(String args[])
{
int num,square,cube;
for(num=1;num<10;num++)
{
square=num*num;
cube=num*num*num;
System.out.println(num+"\t"+square+"\t"+cube);

}

}
}

//Guessing program
class Squareroot{
public static void main(String args[])
{
double num,sroot,rerr;
for(num=1.0;num<100.0;num++)
{ sroot=Math.sqrt(num);
System.out.println("Square root of "+num+" is "+sroot);

//compute rounding error
rerr=num-(sroot*sroot);
System.out.println("Rounding error is "+rerr);
System.out.println();
}
}
}


//Guessing program
class Squareroot{
public static void main(String args[])
{
double num,sroot,rerr;
for(num=1.0;num<100.0;num++)
{ sroot=Math.sqrt(num);
System.out.println("Square root of "+num+" is "+sroot);
}
}
}

WHAT ARE THE OUTPUTS OF THESE PROGRAMS?

Another Sample on C++ Functions

Actual and formal parameters hold similar values. Use the command return should you need to return a value to the calling program. Remember that the data type should be similar to the returned value otherwise you will be seeing errors when you run this program.

Below is another C++ function with parameter passing.
[+/-] show/hide


#include iomanip //enclose this in <>
#include iostream //enclose this in <>

using namespace std;
void read();
float payment(float totalcharges);
float charges();
float compute(float charges);
main()
{
float tcharge;
read(); //calling function read
tcharge=charges(); //passing the returned value
payment(tcharge); //actual parameter passing
cin.get();
cin.ignore();
}

void read()
{
char name[30];
char course[15];
cout<<"input student's name:";
cin.getline(name,30);
cout<<"input student's course:";
cin>>course;
}

float charges()
{
float tuition, units, misc;
cout<<"input tuition rate per unit: ";
cin>>tuition;
cout<<"input total units enrolled: ";
cin>>units;
cout<<"input total miscellaneous: ";
cin>>misc;
return tuition*units+misc;}

float payment(float totalcharges) //formal parameters
{
float cash;
cout<<<">
cout<<<"input>
cin>>cash;
cout<<<"your>
}

Modular Facility of C++

Like any programming languages, the use of modular programming is enforced. In C or C++, we call this as a function.

We have to however declare function/s before use and this declaration must be similar to how we define functions.

Check this sample program:



[+/-] show/hide




#include
using namespace std;
float convert(float feet);
main()
{
float xfeet;

cout<<"input values for feet:";
cin>>xfeet;
cout<<"Equivalent in inches: "<
cin.get();
cin.ignore();
}
float convert(float feet)
{return feet*12.00;}

You can write this in C by replacing the input and output functions with scanf() and printf() and the predefined library of stdio.h.

Java's Break from Loop Structures

We have to sometimes use a force exit from a loop or go to certain structures. Java uses break and goto to perform these actions.

Check the sample program below to evaluate break command.



[+/-] show/hide




//break samples as label
class breakdemo1{
public static void main(String args[])
{
done:
for(int i=0;i<10;i++){
for (int j=0;j<10;j++){
for (int k=0;k<10;k++){
System.out.println (k+ " ");
if (k==5) break done; //jump to done;
}
System.out.println("After k loop"); //wont execute
}
System.out.println("After j loop"); //wont execute
}
System.out.println("After i loop");
}
}

//break as goto
class breakdemo1{
public static void main(String args[])
{
int i;
for (i=1 ;i<4>

one: {
two: {
three: { System.out.println("\n i is " +i);
if (i==1) break one;
if (i==2) break two;
if (i==3) break three;
//this is never reached
System.out.println("wont print.");
}
System.out.println("After block three.");
}
System.out.println("After block two.");
}
System.out.println("After block one.");
}
System.out.println ("After for statement");
}
}


// break inside loop
class breakdemo{
public static void main(String args[])
throws java.io.IOException{
char ch;
for ( ; ;)
{
ch=(char)System.in.read(); //get a char
if (ch=='\n') break;
}
System.out.println("You pressed Enter key");

}
}

//break inside loop
class breakdemo{
public static void main(String args[]){
int num=100;
//loop while i-squared is less than num
for (int i=0; i
if (i*i>=num) break; //terminate the loop
System.out.print(i+" ");
}
System.out.println("Loop complete.");
}

}

Java's Conditional Statement: Switch

Apart from the IF statements, Java uses Switch for a more flexible validation of filter condition.
Check the sample program below:



[+/-] show/hide



class Sampleswitch{
public static void main(String args[])
throws java.io.IOException
{ int a=20,b=4,sum,diff,product,quo;

char ch;

System.out.println("[A]ddition");
System.out.println("[S]ubtraction");
System.out.println("[M]ultiplication");
System.out.println("[D]ivision");
System.out.println("Enter letter of option");
ch=(char)System.in.read(); //to read from keyboard
switch(ch){
case 'A':
case 'a':
sum=a+b;
System.out.println("SUm is "+sum);break;
case 'S':
diff=a-b;
System.out.println("Difference is "+diff);break;
case 'M':
product=a*b;
System.out.println("Product is "+product);break;
case 'D':
//quo=a/b;
System.out.println("Quotient is "+a/b);break;

}

}
}

Java's Conditional Statements

Just like C or C++, Java has conditional statements similar to the former's structures.

Do check these sample Java programs on IF statements.



[+/-] show/hide



//sample if program
public class SampleIF{
public static void main(String args[])
{ double grade=90.00;
if (grade<75.00)
System.out.println("Sorry, you failed!");
else
System.out.println("Sorry, you passed!");

}
}

WHAT IS THE OUTPUT OF THE CODE # 1 ABOVE?

//Guessing program version 1
class Guess{
public static void main(String args[])
throws java.io.IOException{
char ch, answer='R';
System.out.println("I am thinking of a letter between A to Z. Guess?");
ch=(char) System.in.read();
if (ch == answer) System.out.println("Your guess is right");
else System.out.println("Your guess is wrong");

}

}


//Guessing program version 2
class Guess{
public static void main(String args[])
throws java.io.IOException{
char ch, answer='R';
System.out.println("I am thinking of a letter between A to Z. Guess?");
ch=(char) System.in.read();
if (ch == answer) System.out.println("Your guess is right");
else
{ System.out.println("Your guess is wrong");
if (ch
else
System.out.println("Too high");}
}

}

HOW ABOUT THE LAST TWO PROGRAMS?

Friday, February 20, 2009

Handbook 2009

HANDBOOK 2009



Health:


1. Drink plenty of water.

2. Eat breakfast like a king, lunch like a prince and dinner like a beggar.

3. Eat more foods that grow on trees and plants and eat less food that is manufactured in plants.

4. Live with the 3 E's -- Energy, Enthusiasm, and Empathy.

5. Make time to practice meditation, yoga, and prayer.

6. Play more games.

7. Read more books than you did in 2008.

8. Sit in silence for at least 10 minutes each day.

9. Sleep for 7 hours.

10. Take a 10-30 minutes walk every day. And while you walk, smile.


Personality:

11. Don't compare your life to others'.
You have no idea what their journey is all about.

12. Don't have negative thoughts or things you cannot control.
Instead invest your energy in the positive present moment.

13. Don't over do. Keep your limits.

14. Don't take yourself so seriously. No one else does.

15. Don't waste your precious energy on gossip.

16. Dream more while you are awake.

17. Envy is a waste of time. You already have all you need.

18. Forget issues of the past. Don't remind your partner with his/her mistakes of the past.
That will ruin your present happiness.

19. Life is too short to waste time hating anyone. Don't hate others.

20. Make peace with your past so it won't spoil the present.

21. No one is in charge of your happiness except you.

22. Realize that life is a school and you are here to learn.
Problems are simply part of the curriculum that appear and
fade away like algebra class but the lessons you learn will last a lifetime.

23. Smile and laugh more.

24. You don't have to win every argument. Agree to disagree.


Society:

25. Call your family often.

26. Each day give something good to others.

27. Forgive everyone for everything.

28. Spend time with people over the age of 70 & under the age of 6.

29. Try to make atleast three people smile each day.

30. What other people think of you is none of your business.

31. Your job won't take care of you when you are sick. Your friends will. Stay in touch.


Life:

32. Do the right thing!

33. Get rid of anything that isn't useful, beautiful or joyful.

34. GOD heals everything.

35. However good or bad a situation is, it will change.

36. No matter how you feel, get up, dress up and show up.

37. The best is yet to come.

38. When you awake alive in the morning, thank GOD for it.

39. Your Inner most is always happy. So, be happy.


Last but not the least:

40. Please Forward this to everyone you care about

Simple Data Types of Java

Basic data types of Java include:

int for integers
float or double for numbers with decimals only that double has larger range
char for character or string of characters

Mathematical operators of other languages are also employed in Java. Check this sample program:


class Compute{
public static void main (String args [ ] ){
/* This is a comment paragraph
in Java */
// This is a comment line too
int birthyear=1977, currentyear=2009, age;


age=currentyear-birthyear;
System.out.println("You are " +age+" years old.");
}}


This file may be saved as Compute.java or something else since we did not mark it as public. The variables birthyear, currentyear are initialized.

To display a value of a resulting operation, you may do this inside the output command or as a separate variable.

Creating Your First Java Program

I used the codes below through JC Creator. These codes work as well in other Java variants, they may differ in the environment where you add these codes and run them.

The basic structure of a Java program is this:



[+/-] show/hide




public class Greetings{
public static void main( String args [ ]){
System.out.print ("Hello! Welcome to Java programming!");
}}


This program must be saved as Greetings.java since we use public to make this file known to other classes.

Compile and run this code.

Thursday, February 19, 2009

What is Object-Oriented Programming?

This is the current and one of the hot - pick programming paradigms of programmers. We could not help but discuss this first before going into the depths of C++ and JAVA programming.

What is OOP? Wikipedia says:

Object-oriented programming (OOP) is a programming paradigm that uses "Objects" and their interactions to design applications and computer programs. Programming techniques may include features such as information hiding, data abstraction, encapsulation, modularity, polymorphism, and inheritance. It was not commonly used in mainstream software application development until the early 1990s. Many modern programming languages now support OOP.

Typical concepts of OOP include:

1. Objects
2. Classes
3. Methods
4. Events
5. Inheritance
6. Polymorphisms
8. Encapsulation

Read more on these concepts.

Popular OOP Languages are listed below:
1. Cecil, by Craig Chambers.
2. Dylan
3. Python
4. Smalltalk
5. Scala
6. Blue
7. Eiffel
8. Modula-3
9. Oberon
10. Sather
11. Component Pascal
12. TOM
13. Suneido
14.D from Digital Mars
15. simple OO Forth
16. Objective-C
17.C++
18.D
19. Java
20.Perl and Ada
21.CLU

Here are some Software Engineering methods/tools for object-oriented programming:

Credits for the OOP language compilation go to:
http://www.cs.waikato.ac.nz/~marku/languages.html#ool

Loops in Sales

Below is another sample program in C. This program is expected to read an item, its code, quantity, unit price and compute the needed charge and change from the cash given.



[+/-] show/hide



#include stdio.h /*enclose stdio.h with <> */
main()
{char item[20],itemcode[5],option;
float quantity,total,unitprice,
charge,cash,change;

clrscr();
total=0.0;

do
{
printf("\nInput an item code:");
scanf("%s",&itemcode);
printf("\ninput item description:");
scanf("%s",&item);
printf("\ninput quantity:");scanf("%f",&quantity);
printf("\ninput unit price:");scanf("%f",&unitprice);
charge=quantity * unitprice;
total=charge+total;
printf("\nInput item again [y/n]?");
option=getch();
}
while (option=='Y' || option=='y');

printf("\nYOur total charge : %.2f",total);
printf("\ninput your cash");
scanf("%f",&cash);
change=cash-total;
printf("Your change:%.2f",change);
getch();
}

Translate this in Bloodshed C++.

Tuesday, February 17, 2009

Brain Twister

*
**
***
****
*****

The program below displays the triangle of asterisks above.



[+/-] show/hide



#include stdio.h /*enclose stdio.h with <> */
main()
{
int x,y;
for(x=1;x<=5;x++)
{ for (y=1;y<=x;y++)
printf("*");
printf("\n");
}
getche();
}

The outer loop above controls the line by line of asterisks while the inner loop controls the number of asterisks per line.

Using the program above as guide, make the needed C program to display the following outputs:
*****
****
***
**
*

*
**
***
****
*****

*
* *
* * *
* * * *
* * * * *

Another Loop Sample

You want to display only even numbers between 1 - 100. You can try this program in C.



[+/-] show/hide



#include stdio.h /* enclose the stdio.h in between <> */
main()
{
int x;
clrscr(); /* this is used to clear the screen */
printf("The even numbers are :\n");

for (x=1;x<=100;x++)
if (x % 2 ==0)
printf(" %d ",x);
getche(); } /* the % is a MOD operator or gets the remainder. If the operation results to zero, it means the number is divisible by two, thus, it is an even number */ In Bloodshed C++, it can be like this:

#include iostream /* enclose the iostream in between <> */
#include iomanip /*enclose the iomanip in between <> */
using namespace std;
main()
{
int x;

cout<<"The even numbers are :"<

for (x=1;x<=100;x++) if (x % 2 ==0) cout<<\ /* the slash means to concatenate the statements*/ setw(2)<<\ x;
cin.get();

}

In C++, the setw() is used to set spaces supported by the library iomanip.


Writing Programs Easier

Who says programming is E-A-S-Y? It is never easy, when I was a college student, I almost went crazy with it but I loved and am loving the challenge of solving problems and giving my solutions through the codes.

So, perhaps, these strategies I employ will help assist you:

1. Know the problem. What are the expected input, the process and the expected output. If you are unsure, you may ask to further clarify the problem.

2. Write an algorithm or better a pseudocode to make it easier to write the source code.

3. Try the long method first in solving the problem. If the process is already clear, translate this into a shorter and more efficient solution.

4. Ask your friends or teachers how they propose the solution to be. Compare your solution to theirs. Are they similar or far different? Is your solution more feasible and efficient or not? Choose then to redo or pursue your solution.

5. Unfamiliar with the programming language? Use then your solution in a language you are used to and try it. If this works, similar solution but with different syntax may work in another programming language.

6. Still clueless? It pays off to read and read and practice programming more. . . as a teacher and a student before, I have my programming lapses too but we keep on trying.

Program Development Process

As a programmer, you have to understand that our programs go through these basic stages:

source code --> translator --> executable code

where:

Source Code
is the actual program that we write, may it be in C or C++ or Java, or in Visual Basic or something else. But since this is normally written in higher language, then, our computer/machine could not possibly understand this.

Translator can take two forms: compiler or interpreter. Syntax errors are then checked. If errors are found, you have to correct these in your source code and retranslate again.

Compiler like C is to translate your source code to machine code as one program so if your program is quite big, this may take time (but with the processor's speed now, this has become unnoticeable) while Interpreter translates your source code, line after line, so this makes your program easier to translate like what we do in Java.

Executable Code - the machine-translated code that makes us execute our code with out the environment of our programming language where we have written our source code. Should you have run-time or logical errors or the output you desire is not the one displayed, then you have to edit again your source code and redo the process.

Know C Programmming Language More

Typically, C is created not only for system applications but also for application programs already. It is used to write language compilers, assemblers, text editors, and print spoolers.

But, to picture out C in perspective, here is the summary (excerpt from www.wikipedia.org):


The C Programming Language (aka "K&R") is the seminal book on C.
Paradigm imperative (procedural), structured
Appeared in 1972
Designed by Dennis Ritchie
Developer Dennis Ritchie & Bell Labs
Typing discipline static, weak, manifest
Major implementations GCC, MSVC, Borland C, Watcom C
Influenced by B (BCPL,CPL), ALGOL 68,[1] Assembly, PL/I, FORTRAN
Influenced awk, csh, C++, C#, Objective-C, BitC, D, Java, JavaScript, Limbo, Perl, PHP

The influences of C in other popular programming languages show that C has become the backbone for more advanced languages that studying it will make us understand current programming languages.

Monday, February 16, 2009

Caution on Common Programming Mistakes

Should your program won't run because of syntax errors, check the following:

1. undeclared variables
2. uninitialized variables
3. undeclared functions
4. using a single equal sign to check equality
5. setting a variable to an uninitialized value
6. extra semi-colons
7. misusing the && and || operators
8. overstepping array boundaries
9. Cases are different

But, if your program does not produce a result that is expected, your program then has logical error, and must review the flow or logic again.

The Major Differences of C and C++

When I taught C++ using Bloodshed C, I indeed had my struggle, but as I learned the ins and outs of C++, somehow I find the transition between the two languages. They are quite similar with structures and all except for other stuffs listed below:

For input and output commands in C:
scanf() and printf()

For C++:
cin>> and cout<< */
using namespace std;


These control the input and output functions and variables that are used in the program.
To ignore the return key after set of inputs, we have to issue a command:

cin.ignore()


If in C, we use the command getche() or getchar() to wait for keyboard hit to see the result, in C++, we use the command, cin.get() instead.

To display a newline, in C, we use \n while in Bloodshed C++, we use endl.

Check our these two sample programs in C and C++.



[+/-] show/hide



In C:
#include stdio.h /*enclose the stdio.h in between <> */
main()
{
int a,b,sum;
printf("\nInput your first number : ");
scanf("%d",&a);
printf("\nInput your second number : ");
scanf("%d",&b);
sum=a+b;
printf("\nThe sum of %d and %d is %d",a,b,sum);
getche();
}

In Bloodshed C++

#include iostream /*enclose the iostream in between <> */
using namespace std;

main()
{
int a,b,sum;
cout<<"Input your first number : "; cin>>a;
cout<<"Input your second number : "; cin>>b;
cin.ignore();
sum=a+b;

/* the \ symbol means to concatenate the succeeding lines*/
cout<<<"The sum of "<< \ a<< \ "and "<< \ b << \ " is "<< \ sum;
cin.get();
}

Are the outputs the same?
There are still differences between C and C++. Do check other related articles.

Thursday, February 12, 2009

Brain Twister in C: Loops

Identify and correct the errors from the codes below.

for(int x=1;x<=5;x++);
printf("Hello);

int y=105;
While y>100
{ Printf(“%d”,y);
y--;}

int x=10;
Do
Printf(“Your number is %d:,x);
X++;
while (x>1);

Wednesday, February 11, 2009

More For Statement Examples and Break From Loops

Sometimes you have to repeat loops more than the usual and break from them whenever we need it.

We can use a double loops and a break to do these tasks respectively.

Check the programs below:



[+/-] show/hide




/* a program to display a multiplication table of 15 by 10 */
#include stdio.h /*write stdio.h in between <>*/
main()
{
int row,col;
for (row=1;row<=15;row++) {for(col=1;col<=10;col++) printf("%d\t",row*col); printf("\n");} getche(); } /*A program to exit from loops */ #include stdio.h /*write stdio.h in between <>*/
main()
{
int row,col;
for (row=1;row<=15;row++)
{for(col=1;col<=10;col++)
printf("%d\t",row*col);
printf("\n");
if (row=10) /* this means that if the outer loop has reached 10, it will exit from this loop*/
break;}
getche();
}

What are the outputs of these two programs?
Translate this into Bloodshed C++. Simply replace the printf command with cout.

Loop Applications

C or C++ has three (3) loop structures : for, while and do while statements. Let us dissect for statement first:

General syntax:

for (initialization;condition;increment/decrement)

To display a series of 1 to 100 using for statement, it may look like this:
int x;

for (x=1;x<=100;x++)
printf(" %d ",x);


Check this program below to display a number and its square and cube.



[+/-] show/hide




#include stdio.h /* use <> in between stdio.h*/
main()
{
int num,square,cube;
clrscr();
for(num=1;num<10;num++)
{
square=num*num;
cube=num*num*num;
printf("%d\t%d\t%d\n",num,square,cube);
}
getch();
}

Translate this into Bloodshed C++.

Condition Statements Using Switch

Another condition statement in C or in C++ is the switch statement. The general syntax is :

switch (selector)
{
case value1: ;break;
case value2: ;break;
:
case valuen: ;break;
default:
;
}

Check the sample program below.



[+/-] show/hide




/* a program to determine the days of the months in a year */

#include stdio.h /* must include stdioh in between <> */
main()
{ int month,days;
clrscr();
printf("Input a month from 1-12: ");
scanf("%d",&month);
switch (month)
{
case 1:
case 3:
case 5: /* these statements are valid if to mean several values but w
ith one group of action*/
case 7:
case 8:
case 10:
case 12:
days=31;printf("\nMonth %d has % days",month,days);break;
case 2: if (month%4==0)
days=29;
else
days=28;
printf("\nMonth %d has % days",month,days);break;
case 4:
case 6:
case 9: /* these statements are valid if to mean several values but w
ith one group of action*/
case 11:
days=30;printf("\nMonth %d has % days",month,days);break;
default:
printf("\nYour input %d is out of range",month);
}
getch();
}


What is the output of this program?
Replace the input and output commands in Bloodshed C++. Translate this.

Brain Twister

Spot the mistakes from the following C's conditional statements.

if answer=’Y’
printf(“Your answer is correct.”)
then printf(“Your answer is wrong.”);


switch num
{
case 1=printf(“one”);break;
case 2=printf(“two”);break;
default: printf(“Not in the option.”);
}

Monday, February 9, 2009

Conditional Statements

C and C++ accept conditional statements through if statement. There are different forms of this depending on your solution. C++ takes its structures from C. Thus, conditional and loop structures among others are similarly written.

The syntax is:

form 1
if (condition)
statement_if_true;

form2:
if (condition)
{
/*Do these actions here if the condition is true.
Use the curly braces if you have more than one statement to execute*/
statement1;
statement2;
;
statementn;
}

form 3:
if (condition)
statement_if_true;
else
statement_if_false;

form 4:
if (condition)
{statements_if_true;}
else
{statements_if_false;}

Check this sample program to input name and birth date.



[+/-] show/hide



#include stdio.h /*the stdio.h must be enclosed in <> */
main( )
{ char firstname[15];
char lastname[15];
int birthyear;
int currentyear;
int age;

clrscr();
printf("\nPlease enter your firstname: ");
scanf("%s",&firstname);
printf("\nPlease enter your lastname");
gets(lastname);
printf("\nPlease enter the current year: ");
scanf("%d",&currentyear);
printf("\nPlease enter your birth year: ");
scanf("%d",&birthyear);
age=currentyear-birthyear;
printf("\nHello %s %s",firstname,lastname);
printf("\You are %d years old\n",age);
if (age>18)
printf("You are qualified to vote!);
else
printf("You are still underage. Go to your mommy!");
getche();
}

What is the output of this code?
Translate these codes into Bloodshed C++.

Input of Strings

A C program may accept an input of string of characters apart from the input of numbers or single characters.

Check this sample program to input a name and a birth date:



[+/-] show/hide



#include stdio.h /*the stdio.h must be enclosed in <> */
main( )
{ char firstname[15];
char lastname[15];
int birthyear;
int currentyear;
int age;

clrscr();
printf("\nPlease enter your firstname: ");
scanf("%s",&firstname);
printf("\nPlease enter your lastname");
gets(lastname);
printf("\nPlease enter the current year: ");
scanf("%d",&currentyear);
printf("\nPlease enter your birth year: ");
scanf("%d",&birthyear);
age=currentyear-birthyear;
printf("\nHello %s %s",firstname,lastname);
printf("\You are %d years old",age);
getche();
}

What is the output of this code?
Translate this into BLoodshed C++.

C's Input and Output Commands

In C, we have to declare our variables. To do this, we have to specify their data types. The following are the basic data types. These are basic data types as well in C++.


int - for integer or whole number values
float - for values with floating points or with decimals
double - similar with float but with bigger range
char - for characters or string of characters


These too can be further modified through the following:

signed unsigned
long short


We use putchar( ) function to display a character at a time and printf () to display more.

Check samples below:
putchar('H'); /*H is displayed on the screen*/
printf("Hello"); /*Hello is displayed*/
int x=5; /*Declaring a variable x with integer data type with initial value of 5*/
printf(%d",x); /*Displaying 5 as the value of x, %d denotes the format specifier for integer*/

We use gets() to read a string of characters,getchar() or getche() for a single character and scanf() to read variants of inputs.

Check samples below:
getche();
getchar(x);
int x;
scanf("%d",&x); /*to read an integer and assign it to variable x*/

/*the program below reads two integers and computes them*/



[+/-] show/hide



#include stdio.h /*the stdio.h must be enclosed in <> */
main()
{ int x,y,sum;
clrscr(); /*a function to clear your screen*/
printf("\nInput your first number: "); /*\n is used to denote carriage return*/
scanf("%d",&x);
printf("\nInput your second number: ");
scanf("%d",&y);
sum=x+y; /*adding x and y and assigning it to variable sum*/
printf("\n The sum of %d and %d is %d",x,y,sum);
getche();
}

The input and output commands in C++ are cin and cout functions. Do check C++ for their uses.

Sunday, February 8, 2009

C Shouts "Hello World!"

To start your C program, load the C editor so you can write your codes. A simple program can be the one below. A body of a C program basically resembles below:

/*This is a comment line.
The lines colored red are simply comments and must be enclosed in a pair of slash and
asterisks*/

#include stdio.h /*the stdio.h must be enclosed in <>. This line calls the library that supports basic I/O command*/

/*this signals the beginning of your main program.
printf command is used to display an output on the screen
and getche() shall halt the program on the runtime mode waiting for you to hit the keyboard*/
main( )
{
printf("Hello World!");
getche();
}

Each command line must end with a semi-colon. C program is case sensitive. Thus, all reserve words should be written in smaller case and identifiers should be used the same way, they were declared.

In Bloodshed C++, this will look like this:

#include iostream /*the iostream must be enclosed in <>. */
main( )
{
cout<<"Hello World!"; cin.get(); }


Compile and run this code and on the screen, you shall see, "Hello World!"
Congratulations! You have just made your first program.

Reserved Keywords and Identifiers in C

You may write identifiers or names for your variables or functions through valid characters like numbers, letters and underscores. But these identifiers should not be similar to the reserved keywords of C as they have special purpose inside your C program.

The following are the keywords:

auto break case char continue default
do double else enum exterm float
for goto if int long register
return short sizeof static struct switch
typedef union unsigned void while

An identifier must start with an underscore or a letter and may be followed by letters/underscores/numbers. I advice that identifiers should connote their function so it would be easier to distinguish them from the rest.

Sample valid identifiers are: address, name, age, mygrade, _average, total1

Beginnings of C Programming

C was built by Dennis Ritchie in 1970's at Bell Technology Labs to help him make UNIX operating system. His works made Unix more portable and improved as programmers of C find this new language easier to implement than its predecessors.

Now, C is used not only to create system applications inclusive of which are operating systems and embedded systems, but also, application software.

With C's excellent features and capability, it is widely known and had grown successors, which for one is JAVA to address wider functionality of applications.

See full history of C. . .

Saturday, February 7, 2009

Techie Frills on the Loose

I decided to continue with this blog which was originally created for my class in Computer Organization. But since, I am an IT teacher, I decided to use my blog to help my students in their works and learning by posting too related lectures and articles that will help them appreciate IT.

I am quite used to programming with C and C++ but my students find their programming quite difficult. Thus, the very inspiration that made me pursue this blog.

So, welcome back teacher Rosilie!