Archive

Archive for the ‘Programming’ Category

[C Tutorial 5] Taking Input From User

July 2nd, 2011 No comments

/* how to take input data from the user - so we can later perform operations on it */

Just like printf is used to display output, scanf is its counterpart used to take input from the user. Assume that we need a number as input from the user(you're gonna need them in almost every program you make). We first need to define a variable that will hold the value of this number. A C variable is used to hold a value - it will store the value we take from the user.

So, there are essentially three steps we need to program this :

Step 1 - declare a variable to store value that the user will enter
Syntax - int a; declares a variable called a(you can call it anything) of the integer type.

Step 2 - ask the user to enter a value
Syntax - using printf

Step 3 - take the value and store it in the variable
Syntax - scanf("%d", &a);
%d stands for "take the value" and &a stands for "store it the variable called a".

The Program :

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

int main()
{
int a; /* Step 1 */
printf("Enter any number\n"); /* Step 2 */
scanf("%d", &a); /* Step 3 */
getch();
return 0;
}

Now, just to check it the program does what it's supposed to do. Let's display the value of a as the output. We just need to add another printf function to the above code :

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

int main()
{
int a; /* Step 1 */
printf("Enter any number\n"); /* Step 2 */
scanf("%d", &a); /* Step 3 */

printf("The value you entered was %d", a); /* displays the value of a */

getch();
return 0;
}

[C Tutorial 4] More on Displaying Output Text

July 2nd, 2011 No comments

/* this tutorial teaches how to move to a new line while printing text to output */

As we've seen in the previous tutorial, the printf function is used to display something as the output. Now, suppose we need to display the following :

Hello Sweety!
How are you?

We now need our program to go to the next line after printing Hello Sweety! Writing two different printf's won't work. A special keyword "n" (without the inverts) is used to do this. Printf takes n as an instruction to move to the next line.

The Program:

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

int main()
{
printf("Hello Sweety!\nHow are you?");
getch();
return 0;
}

Also, to leave a line between the two statements, i would add nn. Now look at the following images to see how the n works.
The first image is the same program written above. In the second image, we move to the next line after printing How are you?

same_line

[C Tutorial 3] The First Program

July 1st, 2011 No comments

A program to display "Hello Sweety!" as the output. All the explanations are in the form of comments. And everything between /* and */ is a comment and everything else is a part of the code. To prevent confusion, the program is first written without the comments.

The Program (without comments/explanation) :

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

int main()
{
printf("Hello Sweety!");
getch();
return 0;
}

The Program (with comments for explanation) :

#include <stdio.h> /* a header file which has the function
printf used to display text as output */

#include <conio.h> /* another header file that has the function
used below */

int main() /* main - the main function,
int - function returns an integer type,
() - for arguments, no arguments in this case */

{ /* main function begins */

printf("Hello Sweety!"); /* shows Hello Sweety! on the screen */
getch(); /* waits for a character before closing program */
return 0; /* since main function should return integer */

} /*main function ends */

It may not look like it but this is one of the most important programs you will ever learn. The syntax used in the program can be generalized as following :

#include <filename.h> is the general syntax you'll use to include any header file. You'll need to include many header files as you deal with more complex problems. stdio.h contains the printf function that we've used to display output.

return-type function-name (arguments) {...} is used to define a function. In this case the function is called main and the return type is integer with no arguments.

printf("..."); a function that shows whatever is inside the double inverts on the output. This is your first C statement. All C statements end with a semi-colon (;)

getch(); this function waits for a character input from the user and then exits the program. Try running the code without it and with it and you'll know what i mean. This function is actually part of a header file conio.h but will work without it on most compilers - but no harm adding the conio.h header

return value; Since the main function must return an integer value, we return 0. However, your program will run without it, but you should make it a practice since you'll need it in the long run.

By the way, All the code we write goes in a new source file on your compiler. (File > New > Source File) Once you type in the above code, you need to compiler & run your program. It should give the following output :

first_program_output

[Note - we added the header file conio.h for getch();]

[C Tutorial 2] The Building Blocks of C

July 1st, 2011 No comments

If you look at any program in C - you'll find that it's actually made up of various "functions". A function is a basic building block of every C program. All the code that we write is a part of a C function.

The "main function" in C is called the "main function". It is the first function your compiler is gonna look for. Apart from the main function, we can define and use our own functions.

Also, Some functions are used very commonly and cannot be defined again & again in every program - like functions to get input and show output - these are already defined in a standard program and can be used in our own program by "including" their source file. These files of code included in our program for ready-made functions are called header files.

c_building_blocks

Now, all the code & the syntax goes inside these functions. We begin coding in the next tutorial. Get ready to write your first C program.

[C Tutorial 1] Introduction to Programming

June 30th, 2011 No comments

In these tutorials, we're not really getting into the whos & whens - our one and only aim is to write efficient programs in C. For everything else - there's Google.

Now, you could be here either to pass an exam - get a degree or you could be here for the love of code - to make something new. Make sure your's is the second reason. If not, make it so.

What is a Program? Why do we need to program at all?

Some people wonder(believe me, they do) - what's with this code stuff.. why do we really need to write a program at all? The answer is simple - even simpler if you know how a computer works. A computer or any electronic system for that matter, is made of a large number of switches or gates - When a certain combination of gates is created - an operation is performed. This combination is made by opening and closing appropriate switches.

Since a computer doesn't have a mind of its own - we need to give instructions to the computer in order to close and open the switches. This set of instructions is called a program. A program is essentially a blueprint for this combination.

What is a Compiler? Which compiler should be used for C?

Since our computer only understands binary - we need a "program" to translate the code written by us in a programming language of our choice - to binary. This program is called the compiler. The programs written by us are a "higher-level" (user-friendly or rather human-friendly) than what the computer understands.

You can download any of the C compilers available for free. Try Dev C++ (Download Link) or Code::Blocks (Download Link) to start with - and you can later switch to a compiler of your choice. A list of all the C compilers is available here.

10 Major Differences Between C And JAVA

October 8th, 2010 36 comments

Here are the major differences between C And JAVA.

1. JAVA is Object-Oriented while C is procedural. Different Paradigms, that is.

Most differences between the features of the two languages arise due to the use of different programming paradigms. C breaks down to functions while JAVA breaks down to Objects. C is more procedure-oriented while JAVA is data-oriented.

2. Java is an Interpreted language while C is a compiled language.

We all know what a compiler does. It takes your code & translates it into something the machine can understand-that is to say-0's & 1's-the machine-level code. That's exactly what happens with our C code-it gets 'compiled'. While with JAVA, the code is first transformed to what is called the bytecode. This bytecode is then executed by the JVM(Java Virtual Machine). For the same reason, JAVA code is more portable.

3. C is a low-level language while JAVA is a high-level language.

C is a low-level language(difficult interpretation for the user, closer significance to the machine-level code) while JAVA is a high-level lagunage(abstracted from the machine-level details, closer significance to the program itself).

4. C uses the top-down {sharp & smooth} approach while JAVA uses the bottom-up {on the rocks} approach.

In C, formulating the program begins by defining the whole and then splitting them into smaller elements. JAVA(and C++ and other OOP languages) follows the bottom-up approach where the smaller elements combine together to form the whole.

5. Pointer go backstage in JAVA while C requires explicit handling of pointers.

When it comes to JAVA, we don't need the *'s & &'s to deal with pointers & their addressing. More formally, there is no pointer syntax required in JAVA. It does what it needs to do. While in JAVA, we do create references for objects.

6. The Behind-the-scenes Memory Management with JAVA & The User-Based Memory Management in C.

Remember 'malloc' & 'free'? Those are the library calls used in C to allocate & free chunks of memory for specific data(specified using the keyword 'sizeof'). Hence in C, the memory is managed by the user while JAVA uses a garbage collector that deletes the objects that no longer have any references to them.

7. JAVA supports Method Overloading while C does not support overloading at all.

JAVA supports function or method overloading-that is we can have two or more functions with the same name(with certain varying parameters like return types to allow the machine to differentiate between them). That it to say, we can overload methods with the same name having different method signatures. JAVA(unlike C++), does not support Operator Overloading while C does not allow overloading at all.

8. Unlike C, JAVA does not support Preprocessors, & does not really them.

The preprocessor directives like #include & #define, etc are considered one of the most essential elements of C programming. However, there are no preprocessors in JAVA. JAVA uses other alternatives for the preprocessors. For instance, public static final is used instead of the #define preprocessor. Java maps class names to a directory and file structure instead of the #include used to include files in C.

9. The standard Input & Output Functions.

Although this difference might not hold any conceptual(intuitive) significance, but it's maybe just the tradition. C uses the printf & scanf functions as its standard input & output while JAVA uses the System.out.print & System.in.read functions.

10. Exception Handling in JAVA And the errors & crashes in C.

When an error occurs in a Java program it results in an exception being thrown. It can then be handled using various exception handling techniques. While in C, if there's an error, there IS an error.

[C++ Tutorial 4] More on Namespaces

July 10th, 2010 1 comment

To see an introduction to what namespaces are, go back to tutorial 3. Now, cout is a function in the namespace "std". Now, there's another way of using cout without specifying the namespace before hand.

#include<iostream>
int main(
{

a
std::cout<<"Hello Jolly!";
system("pause");
return 0;
}

Here, std::cout means the cout that comes from the std namespace. However, since we would eventually use a large number of output and input statements(ie cout's and cin's), we would usually declare the namespace beforehand.

Creating our own namespaces

We can also create our own namespaces. These may contain a number of variables and functions to be used for the particular namespace. We here create a namespace called "my" with a variable of integer type called x.

We will be going into variables and data types in a few tutorials, but here's ow you create an integer variable called x-

int x;   //creates a variable called x
           //which takes integral values

So, here's our own namespace-

namespace my{   //creating a namespace
int x;
}
int main()
{
my::x;         //using the namespace variable
}

If we intend to use our variable x a number of times, we could specify our namespace in the program.

using namespace my;  //declare namespace beforehand

[C++ Tutorial 3] Basic Program Structure

July 10th, 2010 1 comment

So here's our very first program in C++. We're gonna take a look at it and then see what each line of code means.

#include<iostream>
using namespace std;

int main(
{
cout<<"Hello Jolly!";
system("pause");
return 0;
}

#include<iostream>

Here, we're using the code already there in the file iostream in own program. So the compiler is told to get the code from iostream and compile it before moving on to compile the rest of the code. The "<" and ">" are used when the file is located in the default compiler bin and not in an external location. You can try making your own iostream file. Copy all code from iostream to any file, say phoenix.txt and use #include<phoenix.txt> and it'll work.

using namespace std;

Before anything else, you need to know that all statements end with a semi-colon. So, this is your first C++ statement. This just means that you're using a namespace called the standard library. Now, this is done to avoid name collisions. For instance, consider a university which has a student with roll number 70. Another university may also have a student with the same roll number. Now, these are two namespaces, and by specifying  which namespace we're using, we can differentiate between the two students.

int main(){...}

All he shit that we do before this statement is just getting things ready and set for the main function. Did i say function? Yes, this is your first C++ function. Like any function, it must return some data. We use "int" here to show that the returned data would be an integer. Every function has pretty much the same format.

It goes like this-> return-type func-name (parameters){statements}

cout<<"Hello Jolly!";

Now this is another C++ statement. If you have seen the output of the program using your compiler-which is what you should have done. You'll only see Hello Jolly! printed on a stupid blank black screen. Well, there you go-the cout is your standard output function. Anything in the double inverts with the output operator "<<" goes as output to the screen. This function, along with the standard input function(cin) is stored in the "std" file which we talked about in the namespace statement.

system("pause");

A program like this one would usually run in a matter of nanoseconds and the window would close in a flash, unless mi friend-you use the above to simply, pause the system-causing it to wait until you exit.

return 0;

Did I say the main function in C++ would return an integer? So, here we return 0-nada-nothing-goose egg.

Again, the most important thing is to go and try it out for yourself.

[Go to Tutorial 4]

[C++ Tutorial 1] The Basics

July 10th, 2010 No comments

Hello world! I just thought maybe a bunch of C++ tutorial could help. So here they are. To start with, a program is a simply, a set of instructions for the computer to do. The programmer is he who makes the instructions. And the language in which they are written is the programming language.

Low-Level VS High-Level Language

Now, just like you, your computer has its own languages-called the low-level languages(these are the ones your computer knows but they're hard for you to understand). Then there are the ones which resemble your language including words like if, else, while, for called the high-level languages(these are the ones you know but your computer does not).

THE COMPILER

Now, a compiler is just another program which makes your high-level languages understandable to your computer. It is a translator that translates the code written in a high-level language into assembly language(low-level). So, the first thing you need is the compiler. I use Dev C++. You can use whichever you like. (The most popular being Visual C++).

Programming PARADIGM

This is more theoretical and would not much really affect your coding skills, but anyhow-a paradigm is a style of programming. For instance, a procedural paradigm would concentrate on the sequence of the program, a generic paradigm would concentrate on generalization concepts like templates, etc. C++ is a multi-paradigm language.

[Go to Tutorial 2]

An Introduction to Pointers in C++ Programming

July 1st, 2010 1 comment

A pointer, formally called a "derived data type" defines where to get the value of a data variable. It itself, does not store the data but the memory location of the variable.

So, in short, it is a (derived)data type which points to the data of the variable but stores only the memory location of the variable.

The pointer uses the deference(*) operator & the reference/address(&) operator. Some of the stuff we can do using pointers is shown down there.. ;)

int *p1;          /* all of these can be used
int* p2;                  to declare pointers */
int*p3;

int *ptr, a;      //declared pointer and variable
ptr=&a;           //pointer now contains the address of a

cout<<ptr;        //gives the memory location of a
cout<<*ptr;       //gives the value stored at a

It's very important not to get confused between the &variable, pointer, and *pointer.

&variable is used to assign the pointer an address of the variable, pointer gives the memory location of the variable and *pointer gives the value of the variable.