Showing posts with label Basics. Show all posts
Showing posts with label Basics. Show all posts

Tuesday, 3 September 2013

Taking inputs from User

Taking Inputs from Users


This will be the first program where you will learn to take an input from user. And to do so we will write a program that welcomes you. So lets begin.

Copy the code below and execute. You will be prompted to "Enter your name", and on doing so it will print a message with your name. Remember to press the Enter key after the input.

/*
    Author: Ryan Sequeira
    Title:  A program that welcomes you
*/

#include <stdio.h>

int main()
{
    char name[20];
    
    printf("Enter your name: ");    //prompt the user to enter his name
    scanf("%s",&name);    //scan users input
    
    printf("Welcome %s !!!",name);    //print the welcome message
    
    return 0;
}


Lets understand how the code works. Since the program needs to remember your name, we need to create a variable of type string (a string is a sequence of characters, we will learn it in detail later ).

    char name[20];

The line above creates a string variable that can remember 19 characters. **(one character is reserved for a special symbol to detect string termination).

The next two important lines of code are the scanf statement and printf with a variable.

    scanf("%s",&name);    //scan users input
    printf("Welcome %s !!!", name);    //print the welcome message

scanf is used for receiving formatted Input and
printf is used for displaying formatted Output.

We can break the scanf and printf into two parts.
  1. Control String
  2. Variables

Control String

The control string is used to describe the formatted structure of the input or the output. If we directly wrote the variable names inside the formatted string the compiler wouldn't be able to differentiate it from the other characters in the string. Hence we make use of place holders for variables and list the variables outside so that the compiler can substitute the value of the variable in that place(in case of printf).

Variables

As we use place holders, the variables outside must match the total number of places holders used in the control string. Also the type of the place holders must match the variables. For example consider the following statement:

    int age=0;
    float percentage=0.0;
    char name[19];
    
    scanf("%s %d %f",&name, &age, &percentage);    //scan users name, age and percentage
    printf("Welcome %s !!!", name);    //print the welcome message
    printf("\nYour are %d years old and you scored %f this year", age, percentage);    

As you can see, in the scanf statement we scan three inputs viz name, age and percentage. Here the %s matches the name, %d (placeholder for integer) the age and %f (placeholder for float/decimal) the percentage.
Similarly in the second printf statement %d is followed by %f and hence the age is ahead of percentage in the variable list.

Format Specifiers



PlaceholderVariable TypeDescription
%ccharsingle character
%d (%i)intsigned integer
%e (%E)float or doubleexponential format
%ffloat or doublesigned decimal
%g (%G)float or doubleuse %f or %e as required
%ointoctal value
%ppointer address stored in pointer
%sarray of char sequence of characters
%uintunsigned decimal
%x (%X)intunsigned hex value

Now that you know how to take input and display it try do it your self exercises.


Do it your self 

  1. Implement the code that scans name, age and percentage.
  2. Write a program that takes name and percentage of 3 users and display the names and percentage side by side
    • Example
      • Name   Percentage
      • Joel      33.5%
      • Marco  56.5%
      • Sam     90.6% 

Saturday, 31 August 2013

Deconstructing a C Program


Deconstructing a C Program


We now know how to run a C program in linux. So its time to understand the inner workings of a program. For this purpose we will take a small program and dissect and understand it one part at a time. The whole program may look confusing but understanding each component in isolation will make things simple and clear.

So lets take this example. A simple program that prints a line on the screen.


/*  
  Title: code that prints a line.  
  Author: Roshan Tirkey  
*/  

#include<stdio.h>

int main(){  
    // no need for local variables  

    printf("This is my first program\n");  
    return 0;
 } 

**Its important that you understand the basics correctly, hence if there is anything that you find confusing or needs to be explained in detail please comment below. Finally the intent of the blog is to make things simpler for you to understand, and anything that deviates us from doing that should be removed.

The code above can be broken down into five parts, each of which you will be able to reuse in your programs. Each component is listed below and discussed in detail.

  1. The comments
    • Single line comments
    • Multi line comments
  2. The preprocessor statement
  3. The main function
  4. The printf statement
  5. The return statement

The Comments


Comments are never processed. As a matter of fact when the code is converted into binary code the comments and all the white-spaces are neglected, since the compiler only understands the commands.
The reason why one should include comments in his programs is that as the complexity of the program increases it becomes more and more difficult for other programmers to understand. Hence is a good practice to include comments, starting with your first program.

Single-line comments


Single Line comments


A single line comment is used to comment out only one line of code. Anything written after two backslashes "//" will be considered a comment. Hence you can write a line of code followed by // and explain it.

Example:
printf("Hello\n"); // prints Hello followed by new line

You can also use comments to keep some line of code from executing. This technique comes handy when debugging your code, as you can comment out some part of the code and check if the error has disappeared. The example below will show how its done.

//printf("Hello User\n");

printf("Welcome User\n");


Multi-line comments


Multi Line comments


You can make use of multi-line comments to add a description for your program, describing attributes like author, date of creation, title of the program along with a short description of what it does.
Alternately you can also used it to comment out a block of code. This way you can un-comment it whenever you want. This comes in handy while debugging. Let me demonstrate how its done with this example

#include<stdio.h>

int main(){  
/*
    printf("Welcome\n");  
    printf("Good Morning\n"); 
*/
    printf("Hello\n");  
    printf("Good Afternoon\n"); 

    return 0;
 } 


The proprocessor statement


Pre processor Statement


The pre-processor statements allow us to make use of functions that are already implemented. The pre-processor statements are made of two parts
  • include - The include keyword
  • stdio.h - The file where the functions are already implemented
When the compiler reads this statement, the file is fetched and the functions that we require are linked to our program. That way our program becomes independent of other files.

The main function


Main Function Structure


The main program is the entry point for the execution of our program. Each line written within the main program block is executed sequentially. Hence a C program cannot run without a main program.

The printf statement


printf statement

The printf statement is the functionality we import from stdio.h. This function allows us to print a string(a message) on the terminal(stdout). Later as we learn data types we will use it to format text as well.
**The "\n" is a placeholder for a new line.

The return statement


return statement


The return statement, as the name suggests returns a value. Since the main function has a return type of int, it is mandatory for us to return an integer value. A main function returning a value 0 is considered to have executed successfully.
**Note that anything written below the return statement, in that block, will not be executed since the execution of that function is stopped and the value returned.


*Indentation


Indentation in C


As you can see the code we considered was easy to read, and one can easily figure out which lines of code belong within the main function. Making use of tabs allows us to describe the hierarchy withing the program. This process of formatting the program is called indentation. Incorporating indentation will not only make your code look beautiful but it will also convey more meaning and hence become easier to read.
**Indentation comes in handy when debugging the code.



Do it yourself

  1. Try to print "Hello Everyone".
  2. Place return 0; above printf and see what happens.
  3. Comment the printf command ( type // before it ) and see how the programs works. 

Sunday, 25 August 2013

Enter the Dragon - Running your first program




Before we run our first program lets make sure you have Linux installed on your PC.
If not the check our installation guide.
  1. Installing Ubuntu with Windows.
  2. Installing Ubuntu on a Virtual Machine.
*If you install Linux on a Virtual Machine you won't have to restart your PC to switch between Windows and Linux


Since you will be using Linux for the first time, I made sure there were a lot of screenshots to guide you.

For first time you  run a C program on Linux (Ubuntu) you will have to:

  1. Create a directory and the (program) file.
  2. Locate it on the Terminal.
  3. Run the C program on the Terminal. 

Create a directory and the (program) file.


Step 1:

Open the Home directory using the file explorer.



Step 2:

Create a new directory, name it MyPrograms. To create a directory simply Right Click and select New Directory.


Step 3:

Create a new file(Empty Document) in MyPrograms directory. To create a file, RightClick, followed by New Document and select Empty Document. Name it FirstProgram.c


*Make sure you don't leave a blank space in the directory name or file name.

Step 4:

Now open the file and copy the code below.

#include<stdio.h>

int main(){
 printf("Congratulations,\nYou successfully ran this piece of code !!!\n");

 return 1;
}


Congratulations, you created your first C program.


Locate it on the Terminal

Now that the first part of creating the program is done, lets locate it on the Terminal.
A terminal is like the command prompt in Windows.

Step 1:

You can either open the Terminal by searching for it in the search utility, or simply use Ctrl+Shift+T to open the terminal.




This is how the Terminal in Ubuntu looks like.
Better than the rusty Command prompt in Windows right?
The text that appears on the left side is called the shell prompt. It displays your user name and the current directory you are on.

In the pic below ryan is the username and ~ is the present directory.  ~ is an alias for your home directory.



Step 2:

To locate the file on the Terminal open the properties of the file you just created (FirstProgram.c).
Copy the Location.



Step 3:

What u do next will make you feel like a pro programmer.
Use the pwd command to display the directory you are currently using. PWD stands for Present Working Directory



The ls command will display the contents of the directory. LS is an abbreviation for Listing.



You can see the directory you created. MyPrograms.
If you cannot see your directory, it means you are in the wrong directory and you need to enter the following command:
cd <The file location you copied>

If you were able to see the directory then enter the following command:

cd MyPrograms

*Notice the current directory has changed from ~ to MyPrograms.

Step 5:

All that's left to do is locate your file. Use the ls command to list the contents of MyDirectory. It will
display your file FirstProgram.c



Good job, you located your program in the Terminal.


Run the C Program on the Terminal

Just a few steps until you run the program. I know it wasn't easy, but don't give up. You only need to learn this once, it wont be as difficult the next time.

Step 1:

This is the command you need to enter to run your program.

gcc <Your Program Name>

You will notice that no output is printed, instead executing the ls command will show a new file called a.out is created. 
Don't worry, your program is converted into a binary code, a format that your computer understands. If this file gets created you can say your code is compiled.

Step 2:

Now that your code is compiled its time to run it. Simply execute this command

./a.out



Congratulations, you didn't give up and successfully ran the program. A great achievement indeed.


More Information:

If you don't like the name a.out run the gcc command with the -o option. This will make the command 
syntax
gcc <Your Program Name> -o <output file name>th>


And use the ./ prefix  with the output file name to run it.