Archive

Posts Tagged ‘c++ programming’

[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

Understanding Inheritance in OOP

October 4th, 2009 No comments

The example below explains inheritance, an important property of OOP languages.

We have three classes: living, animal & dog. The dog inherits all the characteristics of living & animal base classes however, the plant does not(being an instance of just the living class).

#include<iostream>
using namespace std;
class living
{
      int energy;
      public:
                void getenergy()
                {
                     cout<<"Gets energy"<<endl;
                     }
};
class animal:public living
{
      int feet;
      public:
                void move()
                {
                     cout<<"It moves"<<endl;
                     }
};
class dog:public animal
{

      int tail;
      public:
                void bark()
                {
                     cout<<"It barks"<<endl;
                     }
};
int main()
{
    living plant;
    plant.getenergy();

    dog phoenix;
    phoenix.getenergy();
    phoenix.move();
    phoenix.bark();

    system("pause");
    return 0;
}

The dog inherits the properties of animal which inherits the properties of living. Hence, this inheritance is an example of "Multi-level" inheritance.

10 Major Differences Between C And C++

August 14th, 2009 214 comments

 

C++, as the name suggests is a superset of C. As a matter of fact, C++ can run most of C code while C cannot run C++ code. Here are the 10 major differences between C++ & C...

1. C follows the procedural programming paradigm while C++ is a multi-paradigm language(procedural as well as object oriented)

In case of C, importance is given to the steps or procedure of the program while C++ focuses on the data rather than the process.
Also, it is easier to implement/edit the code in case of C++ for the same reason.

2. In case of C, the data is not secured while the data is secured(hidden) in C++

This difference is due to specific OOP features like Data Hiding which are not present in C.

3. C is a low-level language while C++ is a middle-level language (Relatively, Please see the discussion at the end of the post)

C is regarded as a low-level language(difficult interpretation & less user friendly) while C++ has features of both low-level(concentration on whats going on in the machine hardware) & high-level languages(concentration on the program itself) & hence is regarded as a middle-level language.

4. C uses the top-down approach while C++ uses the bottom-up approach

In case of C, the program is formulated step by step, each step is processed into detail while in C++, the base elements are first formulated which then are linked together to give rise to larger systems.

5. C is function-driven while C++ is object-driven

Functions are the building blocks of a C program while objects are building blocks of a C++ program.

6. C++ supports function overloading while C does not

Overloading means two functions having the same name in the same program. This can be done only in C++ with the help of Polymorphism(an OOP feature)

7. We can use functions inside structures in C++ but not in C.

In case of C++, functions can be used inside a structure while structures cannot contain functions in C.

8. The NAMESPACE feature in C++ is absent in case of C

C++ uses NAMESPACE which avoid name collisions. For instance, two students enrolled in the same university cannot have the same roll number while two students in different universities might have the same roll number. The universities are two different namespace & hence contain the same roll number(identifier) but the same university(one namespace) cannot have two students with the same roll number(identifier)

9. The standard input & output functions differ in the two languages

C uses scanf & printf while C++ uses cin>> & cout<< as their respective input & output functions

10. C++ allows the use of reference variables while C does not

Reference variables allow two variable names to point to the same memory location. We cannot use these variables in C programming.


Don't forget to check out :


MORE -

11. C++ supports Exception Handling while C does not.

C does not support it "formally" but it can always be implemented by other methods. Though you don't have the framework to throw & catch exceptions as in C++.

(will add more..)


UPDATES (ref to comments)-

Praveen - some of them r telling ‘C’ is a middle level language…..tell me the correct type of level language….?

Answer-@praveen – I agree there are always mixed opinions about this one. Some even like to call it a high-level language. But there’s really no determining factor behind the level of a programming language. Essentially, we’re making all the changes at the machine level, right? Now, as we increase the abstraction and move away from the machine-level, the level of the language increases. So, the level is nothing but the level of abstraction. So, most of the languages we use in applications today will have aspects of both machine-level and user-level. The two levels are machine-level & user(real world)-level while high & low levels are relative terms. Although, C is on a lower level of abstraction “relatively”- when compared to C++. Hence, referred to here as low-level.

Mitchell -
cin and cout are part of the std namespace, and they’re not functions. They’re almost like “pipes” in a sense. What you’re doing is essentially bit shifting (<> are bit shift operators) data into and out of them. As well, C++ still supports use of printf and scanf, so your std.cin and std.cout are by no means exclusive in their duties.

[C++ Tutorial 2] Multi-Paradigm Programming

August 7th, 2009 No comments

Whenever the programmers feel the need to change the basic layout of setting up a program, a new paradigm is introduced. Computer languages can then be classified based on the respective paradigm.

A programming paradigm is nothing but a style of programming. In one paradigm we may concentrate on the logic, in another, we may stress on the structure or procedure of our program.

C++ is a programming language that uses three such paradigms & hence, is said to be a Multi-Paradigm programming language.

A) Generic - We generalize concepts as templates & reuse them in the source code.

B) Imperative - We work with a sequence of commands so as to change the state of the program.

(Procedural Programming is the most common way this can be done. Structural Programming is a subset of Procedural programming)

C) Object-Oriented - We use classes which are blueprints of objects that share common behavior & properties.

(The focus here is on the data & instructions rather than the process).

[Go to Tutorial 3]