Wednesday, September 21, 2011

C Language: Beginners’ Guide



Introduction
The purpose of this post is to introduce elementary idea of C - Programming language to the readers. This post requires no earlier experience of any programming  language.
The post has been written keeping the audiences in mind who need to know what C programming language is and what are the different features available. It will help the elementary school students who need to prepare some type of reports for their annual/half-yearly report on a technical topic like this one.
This post will try to highlight the basic features of C. The post is not trying to teach the basic working knowledge of this programming language.
         1.  Overview of C:
C is a powerful structured programming language developed by Dennis Ritchie. It supports functions that enable easy maintainability of code, by breaking a large file
into smaller modules.

2.     Program structure:
A sample C Program template can be as simple as below. The famous “Hello World”
is the famous program among the people interested to learn this language.
#include<stdio.h>
int
main()                               
{     
        --other statements
}

3.     Header files:
The files that are specified in the include section above, are called as header files. These are precompiled files that have several commonly used functions defined in these files. The functions available in the header files are used by a program by supplying few or no parameters.

Like any other file, these header files contains an the file extension ‘.h’. The main program (not the header files) created in the C language are stored in the file system as physical file. These files must have a file name with file extension as ‘.c’. So if you see a file having an extension '.c' then you should understand that is program source code written in the C.
4. Main function:
There must be at least one function in any C source code. This is called as Main() and is a mandetory requirement of C language. This is the entry point of any C program.From main() function the code execution flows as per the programmer’s chosen custom functions. There may or may not be other functions written by user in a program.

5. The First program: Famous “Hello World”
#include<stdio.h>
int
main()
{
        printf(“Hello”);
        return 0;
}
This program prints Hello on the screen when we execute it.

6.   Running a C Program:
You need a C programming language compiler and the code editor at least. The famous ones are listed below

•  If you are working on Windows Operating system, you can download either c-tool or the whole C IDE from the link below. IDE is a helpful set of tool where there is no need to shift between multiple windows during program developement.
Borland IDE : http://www.borland.com

  If you are working on Linux Operating system, then you can download or configure the operating system components to include all the required C tools from the installation source like the DVD/CD.

  Type the above program and save it. With the help of whatever editor you are using compile the program – This will generate an exe file (executable). If you are using and IDE, it will automatically compile, link and run the program for you (actually the exe created out of compilation will run and not the .c file). The you can see the o/p in a blank screen (in most of IDE) whic is called as DOS command prompt.

7.   Comments in C:
C programming language provides two distinct type of code commenting options. Code commenting is required and considered as a very good habit for developers because it gives an adecaute logical information about a code section to the person who is reading for the first time.

• Single line comment
–   // (double slash).
–   Termination of comment is by pressing
enter key.

 Multi line comment looks like as below
/*
This is a comment to tell the reader that we can write multiline comments as in this section. More than one line commenting is possible in C just like these lines.
*/

Multiline comments helps expediting in writing comment which are more than a line.

8. Data types in C:
Any programming language needs to deal with different type of data. C may be handling some mathematical calculation based code, which demands C to work with data like integer values, decimal values. At the same time C may be handling some description about a product details. In this case it will be handling data like customer name, product name, etc. These type of description is nothing but demands C to handle data which are charachter in nature. So C must have pre-defined type of data which it can handle. It has the following type of data defination standards i.e. data types.

• Primitive data types
– int, float, double, char.

• Aggregate data types
– Arrays come under this category.
– Arrays can contain a collection of int or float or char or double type of data.

 User defined data types
– Instead of using the data types available in C, the developer can also define his/her own data type. This type of data is required when we need to store and manipulate the complex type of data, for example the student’s information.
–  Structures and enum data type fall under this category.

9. Variables:
Variables are the temporary place in the computer memory which actually stores the data (any type of data as defined in the above sections). The value in variables may change during the program execution life time,

How to Declare a variable
                         <<Data type>> <<variable name>>;
                    Example:   int a;
     
How to Define a variable
                 <<varname>>=<<value>>;
                  a=10;

How to use a variable
              <<varname>>
              a=a+1;//increments the value of a by 1.
              We can also declare and define a variable in single shot like this.
              int a=10;

          10. Variable names - Rules:
• Should not be a reserved word like intchar etc.
• Should start with a letter or an underscore (_).
 Can contain letters, numbers or underscore.
• No other special characters are allowed including space.
• Variable names are case-sensitive
– A and a are different.

11.  Input and Output:
• Input
– scanf(“%d”,&a);
– Gets an integer value from the user and stores it under the name “a”
• Output
– printf(“%d”,a);
– Prints the value present in variable on the screen.

                 Format specifier
• %d is the format specifier. This informs to the compiler that the incoming value is an integer value.
• Other data types can be specified as follows:
• %c – character
• %f – float
• %lf – double
• %s – character array (string)
• Printf and scanf are defined under the header file stdio.h

12.  For loops:
For loop is used when a set of work has to be repeated multiple time. The syntax offor loop is below
for (initialisation;condition checking;increment)
 {
      set of statements
}

A Program which print Hello 10 times can be similar like one below.
for(I=0;I<10;I++)
{
      printf(“Hello”);
}

13.  While loop:
 The while loop is used to perform some set of tasks which need to be repeated until the parent condition holds true. The syntax for while loop,
while(condn)
{
            statements;
}
Eg:
            a=10;
            while(a !=
0)   
            {
                        printf(“%d”,a);
                        a--;
            }
Output:
10987654321


14.  Do While loop:
The do while is similar to the while loop except that predecided set of task is performed without checking any condition for the first time. The syntax of do whileloop is described below.

do
{
            set of
statements
}while(condn);
Eg:
i=10;                                       
do                                                                   
{
            printf(“%d”,i);
            i--;
}while(i!=0)
Output:
10987654321
             While – Entry controlled loop. Do While – Exit controlled loop.

15.  Conditional statements:
If you want to do some set of task only once but again based on some condition which hold true, then use the IF statement as illustrated below.

if
(condition)          
{
        stmt 1;             //Executes if Condition is true.
}
else
{
        stmt 2;             //Executes if condition is false.
}

switch(var)                         
{
case
1:         //if var=1 this case executes.
                                stmt;
                                break;
case
2:         //if var=2 this case executes.
                                stmt;
                                break;
default:        //if var is something else this will
execute.
                                stmt;
}

16. Operators:
• Arithmetic (+,-,*,/,%).
• Relational (<,>,<=,>=,==,!=).
• Logical (&&,||,!).
• Bitwise (&,|).
• Assignment (=).
• Compound assignment (+=,*=,-=,/=,%=,&=,|=).
• Shift (right shift >>, left shift <<).

17.  String functions:
• strlen(str) – To find length of string str .
 strrev(str) – Reverses the string str as rts .
• strcat(str1,str2) – Appends str2 to str1 and returns str1.
• strcpy(st1,st2) – copies the content of st2 to st1.
• strcmp(s1,s2) – Compares the two string s1 and s2.
• strcmpi(s1,s2) – Case insensitive comparison of strings.
    String.h header file must be included before any of the above string functions is used in the code.

18.  Numeric functions:
• pow(n,x) – evaluates n^x.
• ceil(1.3) – Returns 2
• floor(1.3) – Returns 1
• abs(num) – Returns absolute value
• log(x)  - Logarithmic value
• sin(x) 
• cos(x)
• tan(x)
Header file to be included math.h

19.  Procedures:
• Procedure is a function whose return type is void.
• Functions will have return types int, char, double, float or even structs and arrays.
• Return type is the data type of the value that is returned to the calling point after the called function execution completes.

20. Functions and Parameters:
Functions are the small unit of a program which has some set of instruction which needs to be done as a single unit of work. Each function can do its pre-decided work based on some value which is passed to it. The values which are passed to the function called as parameters. Find below some illustrations as below.

Declaration
section
<<Returntype>>
funname(parameter list);
Definition
section
<<Returntype>>
funname(parameter list)
{
        body of the
function
}

Function
Call
Funname(parameter);

Example
function
#include<stdio.h>
void
fun(int a);                    //declaration.
int
main()
{
        fun(10);                                   //Call.
}     
void
fun(int x)                     //definition.
{
        printf(“%d”,x);                       
}

21.  Actual and Formal parameters:
• Actual parameters are those that are used during a function call.
• Formal parameters are those that are used in function definition and function declaration.

22. Arrays:
• Arrays fall under aggregate data type.
• Aggregate – More than 1.
• Arrays are collection of data that belong to same data type.
• Arrays are collection of homogeneous data.
• Array elements can be accessed by its position in the array called as index.
• Array index starts with zero. 
• The last index in an array is num – 1 where num is the no of elements in a array.
• int a[5] is an array that stores 5 integers.
• a[0] is the first element where as a[4] is the fifth element.
• We can also have arrays with more than one dimension.
• float a[5][5] is a two-dimensional array. It can store 5x5 = 25 floating point
numbers.
• The bounds are a[0][0] to a[4][4].

23.  Structures :
• Structures are user defined data types.
• It is a collection of heterogeneous data.
• It can have integer, float, double or character data in it.
• We can also have array of structures. 
struct
<<structname>>
{
  members;
}element;
We can access element.members;
struct
Person
{
int id;
char name[5];
}P1;
P1.id = 1;
P1.name = “vasu”;
For assigning more values we need to create an array of structure element like this
Struct
Person
{
Int id;
Char name[5];
}P[10];
P[0].id = 1;
P[0].name = “saran”;
P[1].id = 2;
P[1].name = “arya”;
And
so on till P[9].

24. Type def:
The typedef operator is used for creating alias of a data type. For example I have this statement, I can use integer in place of int  i.e instead of declaring int a;, I can use integer a; This is applied for structures too. 
typedef int integer;
typedef struct student
{
int id;
Char name[10];
}s;
Now I can put
s1,s2;

Instead of struct student s1,s2; //In case typedef is missed in struct definition as below
struct student
{
int id;
char name[10];
};


25.  Pointers:
•  Pointer is a special variable that stores address of another variable. Addresses are
integers. Hence pointer stores integer data. Size of pointer = size of int.

• Pointer that stores address of integer variable is called as integer pointer and is declared as int *ip;

Examples
int a;
a=10;           //a stores 10
int *ip ;
ip = &a;       //ip stores address of a (say 1000)
ip     :           fetches 1000
*ip :           fetches 10
* Is called as dereferencing operator

26.  Call by Value:
• Calling a function with parameters passed  as values
int  a=10;                                   
void fun(int a)
fun(a);                           {
                                                              defn;
                                      }
Here fun(a) is a call by value. Any change done with in the function is local to it and will not be effected outside the function. 
27.  Call by reference:
• Calling a function by passing pointers as parameters (address of variables is passed instead of variables).

int a=1;                         
void fun(int *x)
fun(&a);                                    {
                                                              defn;
                                      }
Any change done to variable a will affect outside the function also.

28. Example program – Call by value:
#include<stdio.h>
void
main()
{
        int a=10;
        printf(“%d”,a);                        a=10
        fun(a);
        printf(“%d”,a);                        a=10
}

void fun(int x)
{
        printf(“%d”,x)             x=10
        x++;
        printf(“%d”,x);                        x=11
}

 Explanation
c pointer

29.  Example Program – Call by reference:
#include<stdio.h>
void
main()
{
        int a=10;
        printf(“%d”,a);                        a=10
        fun(a);
        printf(“%d”,a);                        a=11
}
void fun(int x)
{
        printf(“%d”,x)             x=10
        x++;
        printf(“%d”,x);                        x=11
}

Explanation
c pointer illustration
30. Conclusion:
• Call by value: Copying value of variable in another variable. So any change made in the copy will not affect the original place.
• Call by reference: Creating link for the parameter to the original location. Since the address is same, changes to the parameter will refer to original location and the value will be over written.
.
[About the Author: Pratima Gutal is an engineering student in the IT department of College of Engineering Pandharpur, Maharashtra, India. Contact Pratima at her email-id pratima.gutal@gmail.com. If you have any concern, question or objection about this article please feel free to contact her.]

34 comments:

  1. Alex: Many gamers have a problem getting "friend zoned" with
    girls they like. Unfortunately, the percentage of these people who actually find a real romance as a direct result
    of their site memberships is very low - probably less
    than 10%. This guy is so good looking, and he is the definition of Prince Charming.

    Feel free to visit my web page :: The Tao of Badass Review

    ReplyDelete
  2. When the feces has passed, the sphincter muscles contract and the
    anal pillows deflate, contracting back into position.
    First to provide relief and begin shrinking the hemorrhoids you will want to start with sitz bath and
    witch hazel. You simply cannot live a quality lifestyle if you are suffering from External hemorrhoids.


    Here is my site :: treatment for piles

    ReplyDelete
  3. I think the admin of this web page is actually working hard for his web site, since here every material
    is quality based data.

    Here is my web site; german binary robot reviews

    ReplyDelete
  4. Αnd just because it can be used to seducе women, spawn cult leaԁers, and
    make money doeѕn't mean its my faսlt people use it that way.
    Since 2005, when this reporter began publishing
    accounts of self-identіfied Targeted Individuals
    (ΤIѕ), most readers and collеagues asserted in disbelief that it would be impossible for enough spies to harm as many TIs as it is estimated tҺere arе: 350,000 Americans
    alone targeted, lives ruіned. Perhaps you've heard about a
    technique popularized by Oprah Winfrey calleɗ affirmations.


    My webpage :: The Art Of Covert Hypnosis Steven Peliari PDF

    ReplyDelete
  5. Howdy! Ι could have swoгn I've been to this site before but after reading through some of the post I realized it's
    new to me. Anyways, I'm definitely Ԁelіցhted I found it
    and I'll be book-marking and checking back often!

    Here іs my website - Family Survival Course Review

    ReplyDelete
  6. When someone writes an paragraph he/she maintains the plan of a user in his/her brain that how a user can know
    it. So that's why this paragraph is perfect. Thanks!

    My webpage :: Blog.A

    ReplyDelete
  7. AdԀitionally, tɦis helps you to determine for sure if
    yoսr ex is really serious about you and for you to observe them to know if reuniting with him
    or her is worth the hassle. You need to look strong and determined [even if you're not].
    The headline got your attеntion, and brought you in and made you гead this article.


    My web site; make him desire you free download

    ReplyDelete
  8. Stay at home moms, who have college degrees, have been outright asked questions
    like, "Don't you feel guilty throwing four years of college down the drain. Learn the fine points of augmenting -- not repeating -- a resume. A mom can earn from $25 to $600 a month from answering surveys.

    My blog post; stay at home mom jobs; www.youtube.com,

    ReplyDelete
  9. and mould them off. If you are decisive to spam filters might catch it too.
    Be confident and savor fair a few companies in front decision making who to charter.
    You testament not be as snappy as diluent women. It is fresh to inform
    yourself with the results. This cleaning Ray Ban Sunglasses
    Outlet - www.forfriends.in - Oakley Sunglasses Outlet
    () Oakley Sunglasses Cheap Oakley Sunglasses Oakley Sunglasses Cheap Ray Ban Sunglasses,
    Blog.vbcimail.Org, Cheap Oakley Sunglasses [fkbcus.ipage.com] Oakley Sunglasses Outlet Cheap Ray Ban Sunglasses Cheap Ray Ban Sunglasses
    Cheap Ray Ban Sunglasses - archiplanet.org - Oakley Sunglasses Cheap Cheap Ray Ban Sunglasses (Svenskabatmarknaden.Se) Oakley Sunglasses Oakley
    Sunglasses Outlet; , Oakley Sunglasses Oakley Sunglasses Cheap Oakley Sunglasses
    Wholesale, http://scottalanciolek.com/User:AntonetAtchison, Oakley Sunglasses Oakley Sunglasses Outlet store for an nonliteral
    expelling of clip. If you think out the old damaged parts, you poverty to bonk what to do is use
    these tips in this subdivision you testament be fit to implement your knowledge and military
    science.Top Suggestions To control Your organization merchandising Tips That Can growth Your Crops?

    ReplyDelete
  10. What's up, I desire to subscribe for this web site to obtain most recent updates, therefore
    where can i do it please help out.

    Take a look at my weblog ... www.blogigo.com

    ReplyDelete
  11. authentic christian louboutin outlet shop similar designs or the exact style on red bottom shoes christian louboutin eBay until they're restocked.
    If last year was valentino sandals any indication, we can expect some seriously sexy Valentino Shoes Sale looks from the supermodels come July 4. Your cheap louboutin shoes favorite It girls 'grammed up a storm, showing christian louboutin off the suits they wore to hang poolside. jimmy choo boots Since these ladies were already rocking trendy one-pieces christian louboutin sale and sporty bra tops in 2015, their old christian louboutin shoes snaps should provide plenty of inspiration for your valentino shoes own beach weekend ahead. Read on to scope valentino sneakers out the styles Gigi Hadid, Behati Prinsloo, Emily valentino rockstud shoes Ratajkowski, and more slipped into, then shop some red bottom shoes for women last-minute designs that fit the bill for Independence valentino sneakers Day.
    Designers, editors, influencers, and insiders took to valentino rockstud shoes Instagram Saturday afternoon to pay tribute to the valentino bags incomparable Bill Cunningham. The iconic photographer died on Saturday in NYC at the cheap louboutin shoes age of 87, after suffering a stroke earlier in the week.Bill was not only a visionary and a pioneer, who shaped the age of street

    ReplyDelete
  12. “After the divorce, I felt like I needed a fresh start,” says the 43-year-old Upper East Sider, who works in real estate. “It’s that feeling of ‘out with the old, in with the new.’ ”Sanders went through Wilson’s wardrobe, chucking her outdated Michael Kors Handbags jeans and old “blah” turtlenecks. She outfitted her client in sleek leather pants, sexy knee-high boots and colorful patterned frocks.“Even though it’s just aesthetics, it actually changes the coach handbags way you feel,” says Wilson. “It really put me in the mindset to start anew and move forward . . . and I get a lot of compliments.”Michelle McFarlane, founder michael kors purses and CEO of the personal shopping business the Shopping Friend, charges $700 for an hourlong consultation that includes an assessment of a client’s closet, and $250 an hour Michael Kors for personal shopping services. McFarlane says women who hire a stylist post-divorce are usually looking to erase every trace of their marriage, clothes included, while men are looking coach factory outlet to hire a replacement wife.
    Monday night’s Council of Fashion Designers of America Awards brought out some of the shiniest superstars in the fashion, modeling and acting worlds, Longchamp Handbags but many chose surprisingly somber black looks. Chic? Yes. Festive? Less so.Where was all the glamour?Doing her part to buck the trend at the Hammerstein Ballroom was Australian michael kors

    ReplyDelete
  13. Make a fiscal (Ray Ban Outlet) info or sign up a information (Ray Ban Outlet Store) sheet, In addition to allow us be suggesting to Dallas's articles without having paywalls.All the people realised due (New Jordan Releases 2020) to Sanders' significant other subsequently on tomorrow. The girl we hadn't resulted in (Coach Outlet Store Online) featuring tiger woods the actual internet (Coach Outlet Clearance Sale) day the actual 26th, Fortunately (Michael Kors Outlet Store) however known to as the woman the particular following afternoon to pick out (Yeezy Boost 350 Cheap) it all the way further increase originally caused (Michael Kors Outlet) by that hotel by the wonderful resort during (Cheap Yeezy Shoes Sale) go camping perception street. She or he realized that he had couple of small but successful sections within their hturnnd or a a small amount of body clea pants.

    Explain to a nice mug to malleable spend crb. Along with (Cheap Jordan Shoes Websites) regards to during a food, 9 days to weeks about off 10

    ReplyDelete
  14. The NDTV Challan Update app, apart from giving you status of your online challan, provides you with information on petrol price in India. It provides you the list petrol prices Yeezy Boost 350 in metro cities Delhi, Mumbai, Kolkata and Chennai. As you scroll down, the app would give the per litre petrol price of the day in all the cities across India, along Ray Ban Glasses with the change (upward or downward). Yeezy Discount

    Background: Atopic eczema (AE) Ray Ban Outlet is a common skin problem that impairs quality of life and is associated with the development of other atopic diseases Coach Handbags Clearance including asthma, food allergy and allergic rhinitis. AE treatment is a significant cost burden for healthcare providers. The purpose of the trial is to investigate whether Coach Outlet daily application of emollients for the first year of New Jordan Shoes 2020 life can prevent AE developing in high risk infants (first degree relative with asthma, AE or allergic rhinitis).Methods: This is a protocol for a Coach Outlet Store pragmatic two arm randomised controlled, multicentre trial.

    ReplyDelete