Home | Search


2026-04-02

Repost note

2018-11-20

Learn basics of programming in an hour

This is mainly for those who have no prior experience in programming.

The emphasis is on understanding programming from a logical point of view so that you know enough to understand algorithms, rather than on becoming a programmer. Though there's no harm in going through it if your motivation is the latter.

I know there are numerous tutorials on the same, but I felt all of them had more content than was required in the bare minimum.

I'll be using c++ since it's the only language I'm familiar with. Once you learn one language, it's quite easy to pick up more languages if you are so inclined.

I will be using terms/phrases that you may not initially understand. It doesn't matter, as long as your code is working as expected, that's enough. You can anyway learn the rest later. But make sure you understand as much as possible from each example before moving on to the next one because the later concepts build on the earlier ones. Also I'll be going at breakneck speed. :P

If you can think of an alternate way of doing something but aren't sure if it'll work, try it out yourself. Programming expertise comes with practice.

And if you can't learn all of it in an hour, don't be deterred. Not everyone can.

Your first program

You will need a compiler for the purpose. I would recommed Dev C++ (gcc) but you can download any compiler you choose.

Once installed, create a new file.

This is the template for all our code.

#include <iostream>
using namespace std;
int main()
{
 // your code goes here
 return 0;
}

I will not be explaining why we write all this. It's not important, and stays the same all the time.

We will now write a program that outputs a single statement "Hello world" on the screen. Copy-paste the following code:

#include <iostream>
using namespace std;
int main()
{
 cout<<"Hello world";
 return 0;
}

Save your file with file extension ".cpp".

Now click on "build and run" or "compile and run". This might be present on a toolbar on the main screen and/or in one of the menus (menu usually titled build/execute/compile/something like that).

Wait till it does its work and confirm that you receive the output 'Hello world'.

If you get an error that says anything to do with iostream or cout, replace "#include " with "#include <iostream.h>". If you get an error that says anything to do with namespace, remove the line "using namespace std;". If your error says something about int, main or return, replace this:

int main()
{
 cout<<"Hello world";
 return 0;
}

With this:

void main()
{
 cout<<"Hello world";
}

If none of this worked, try this:

#include <iostream.h>
#include <conio.h>
void main()
{
 cout<<"Hello world";
 getch();
}

Or:

#include <iostream>
#include <conio.h>
void main()
{
 cout<<"Hello world";
 getch();
}

If it's still not working, ask someone who knows C++ to help you. Getting your first program running shouldn't take long.

Input and output

We want a program that does the following:

  1. Display on the screen "Enter a number:" so that the user knows he has to enter a number.
  2. Accept a single number as input.
  3. Display "Your number is " followed by the number.

Yes it's a useless program, it's just for learning purposes.

To accept a number as input, we need to create a space in memory where we can store the number. Since this number is an integer, we will use the 'int' keyword.

We use cout<< and cin>> for output and input respectively.

#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
int main()
{
 int x;
 cout<<"Enter a number: ";
 cin>>x;
 cout<<"Your number is: "<<x;
 return 0;
}

We have directly written cout<<"Your number is: "<<x; instead of cout<<"Your number is: "; cout<<x; to save time typing, though the latter will work too.

All statements are to be terminated by semicolon as in the examples. Forgetting semicolons is a very common beginner's mistake.

Also note that when outputting our own text we enclosed it in double quotes. When outputting data from memory however we directly use the name of the variable, in this case x.

Whitespace (spaces, tabs, newlines, etc) present in the code is usually ignored by the compiler, so it doesn't matter where whitespace is or isn't present. Indentation using tabs is done simply to keep the code easier to read for the programmer.

Conditional statements

Now we want to write a program that accepts two numbers as input and tells us which one is greater.

Here's the code:

#include <iostream>
using namespace std;
int main()
{
 int x,y;
 cout<<"Enter two numbers: \n";
 cin>>x>>y;
 if(x>y)
 {
  cout<<"The first number "<<x<<" is greater.";
 }
 else
 {
  cout<<"The second number: "<<y<<" is greater.";
 }
 return 0;
}

Mostly self-explanatory. "\n" is used to output a newline which basically takes the cursor to the next line. Makes things neater and is optional.

Note the use of comma (,) to chain the 'int' statements together and >> to chain the 'cin' statements together. Again it's just to save time typing.

In general we can write any number of statements in the if block or the else block. Once execution of the entire block completes, the program will resume from where the block ends. We can also create nested ifs (an if inside an if), feel free to experiment with these on your own.

We can use the following operators in our condition statement: greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equal to (==).

We can also use the and operator (&&), or operator (||) and the not operator (!). For example, if we have to check that a=5 and b=3, we will use

if(a==5&&b==3)

Loops - while loop

Perhaps the most important concept to be learnt in programming.

Task: User enters a number. Program should output "hello" that many times.

For this we use a loop. A loop keeps repeating execution of a statement or a set of statements as long as a certain condition is met. The condition is important, since otherwise the loop will be an infinite loop that doesn't know when to stop.

#include <iostream>
using namespace std;
int main()
{
 int n,i;
 i=1;
 cout<<"Enter a number: ";
 cin>>n;
 while(i<=n)
 {
  cout<<"hello\n";
  i=i+1;
 }
  return 0;
}

Probably the statement that appears the weirdest on first sight is 'i=i+1'. How can i=i+1?

The equal to is an assignment operator here, meaning it assigns the expression on the right to the variable on the left. So the best way to understand this is 'the future value of i is set to the current value of i+1'. The syntax is

variable = expression

Where an expression can be a variable/constant or a set of variables and/or constants joined by operators (like + - * / etc)

expression = expression is not allowed.

So in the above code, first the value of i is set to 1. Suppose the user enters the value 5 in n. Now the condition is checked. i<=n which is 1<=5 which is true. Hence the computer executes the statements in the loop block. It displays hello and sets the new value of i to be i+1, which is 2.

It then checks i<=n which is 2<=5. Which is still true so the loop repeats again.

So on and so forth until i becomes 6. Now 6<=5 is not true so the loop stops executing and the program resumes after the loop. Since we have nothing written after the loop, the program terminates.

For loop

For loop is the most commonly used loop. It has 3 parts - initialisation, condition and update expression. Everything that can be done with a for loop can be done with a while loop and vice versa. It's just a matter of convenience.

initialisation and update expressions are optional and consist of only assignment expressions (statements that use =)

The above code can be written using a for loop as follows:

#include <iostream>
using namespace std;
int main()
{
 int n,i;
 cout<<"Enter a number: ";
 cin>>n;
 for(i=1;i<=n;i=i+1)
 {
  cout<<"hello\n";
 }
  return 0;
}

The initial expression(s) are executed exactly once just before the loop starts. The update expression is executed after the execution of the loop body and before the condition is checked for the next iteration.

Note that if the condition is false right at the start, the loop body and update expression will not execute even once. The same is true for the while loop.

Prime testing

Here is a more complicated program using loops. It asks for a number as input and checks if the number is a prime or not. It does so by dividing the number with every number from 2 to the square root of n and checking for the remainders.

We have a modulus operator (%) in C++ for checking remainders. a%b returns the remainder when a is divided by b so 5%3=2 and 6%2=0 for example.

We will use a ready-made function which calculates square roots. This is present in "math.h" which is a header file that contains a lot of mathematical functions such as sin, cos, tan, arccos, arctan, log, exponentation, etc. Check them out here.

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
 int n,i,m,flag;
 cout<<"Enter a number: ";
 cin>>n;
 m=sqrt(n);
 flag=999;
 // flag = 999 means prime, flag = 1000 means not a prime
 for(i=2;i<=m;i=i+1)
 {
  if(n%i == 0)
  {
   cout<<n<<" is divisible by "<<i<<". Not a prime";
   flag=1000;
  }
 }
  if(flag==999)
  cout<<"PRIME!!!!";
  return 0;
}

We have also used the concept of a flag memory to ensure that the computer remembers that the number is indeed composite. Try writing the code without using a flag variable; you will understand why we need it.

Statements that start with // are comments and are ignored by the compiler. We can use them to inform the person reading the code (and that could be even yourself) about key things to help them understand the code more quickly.

A minor point that I'm yet to mention is that if we are typing only a single statement where a block of statements is required (for instance, if block, else block, for loop block, while loop block), we can omit the curly braces {} altogether.

Shorthand operators

a=a+1 can be written as ++a or a++ a=a-1 can be written as --a or a--

a=a+b can be written as a+=b a=a-b can be written as a-=b a=ab can be written as a=b a=a/b can be written as a/=b a=a%b can be written as a%=b

Data types

So far we've been only dealing with integers. We can also create character variables using char and decimal value variables using float

Here's some gibberish code that is nevertheless syntactically correct

char f;
float x,y;
int z;
f='i';
x=3.14;
cin>>f>>x>>y>>z;
if(x>y)
 cout<<x+y+z;
else
 cout<<f;
cout<<f+3;

One should generally be careful about mixing data of different types in the same expression, but it is usually possible.

Character variables are treated using their ASCII values so f+3 just returns the character with ASCII value 3 greater than the ASCII value of the character stored in f. So if we enter 'j' (ASCII value 105) in the value for f, we get 'm' (ASCII value 108) for f+3

Words and text data is dealt with by creating character arrays.

And you're done!!!

If you've grasped the above concepts you've understood the basics of programming.

Given below are some more advanced concepts that you could pick up in a short amount of time as well.

Arrays

Task: Write a program that accepts 15 integers as input and outputs them in reverse order.

We need to create 15 locations in memory as input. We could create 15 separate variables with names a,b,c,d,e... but that's time consuming so we use arrays.

#include <iostream>
using namespace std;
int main()
{
 int a[15];
 int i;
 cout<<"Enter 15 numbers: \n";
 for(i=0;i<15;++i)
  cin>>a[i];
 for(i=14;i>=0;--i)
  cout<<a[i]<<" ";
 return 0;
}

As evident from the example, dealing with arrays normally requires loops.

An array declared as a[15] will by default have indices starting from zero (a[0],a[1], ...... a[14])

Suppose now we need to find the largest number in the array.

#include <iostream>
using namespace std;
int main()
{
 int a[15],i,max;
 cout<<"Enter 15 numbers: \n";
 for(i=0;i<15;++i)
  cin>>a[i];
 max=a[0];
 for(i=1;i<15;++i)
  if(a[i]>max)
   max=a[i];
 cout<<"Max value is: "<<max;
 return 0;
}

Sorting

Task: Write a program that accepts n integers and sorts them in ascending order

This job is not so easy. It requires nested loops. Google the solution once you fail.

(Assuming you fail, that is :P)

Functions

A function is a snippet of code that does something for you and usually (but not necessarily) returns an answer value. sqrt() for example was a function we used earlier. It accepted one input and gave one output.

Here is an example of a function that calculates exponentation a^b for a positive integer exponent.

int exp(int a,int b)
{
 int i,r=1;
 for(i=1;i<=b;++i)
  r*=a;
  return r;
}

Here is a complete program that uses this function to compute f(x) = (x+2)^x

#include <iostream>
using namespace std;
int exp(int a,int b)
{
 int i,r=1;
 for(i=1;i<=b;++i)
  r*=a;
  return r;
}
int main()
{
 int x,y;
 cout<<"Enter x: ";
 cin>>x;
 cout<<"f(x)=(x+2)^x is being computed ....";
 y= exp(x+2,x);
 cout<<"f("<<x<<") = "<<y;
 return 0;
}

Note that our function has two inputs which are integers and one output which is also an integer. We have used different variable names for clarity. The values of x+2 and x get copied onto a and b, which are then used while the function runs. Once the function hits a return statement it terminates and passes the returned value r to its place in the expression y=exp(x+2,x). Hence the value gets stored in y.

In general we cannot access variables created in main() while inside a function and variables created in a function while inside main(). We can only access those values which we have explicitly passed to the function. These are rules of scope.

Recursion

We can also access a function from inside of itself. Here's a function that calculates factorial recursively.

int fact(int n)
{
 if(n==0||n==1)
  return 1;
 else
  return n*fact(n-1);
}

Pointers

Also a useful concept in competitive programing, however my coding is rusty in this area. So bad luck, learnt it from elsewhere.

Subscribe

Enter email or phone number to subscribe. You will receive atmost one update per month

Comment

Enter comment