An Introduction to C

This entry is part 1 of 10 in the series Fundamentals of C

Fundamentals of C

Introduction

C is a general purpose, structured programming language. Its instructions consist of terms that resemble algebraic expressions, augmented by certain English keywords such as if, else, for, do and while. In this respect it resembles high level structured programming languages such as Pascal and Fortran. C also contains additional features, that allow it to be used at a lower level, thus bridging the gap between machine language and high level language. This flexibility allows C to be used for systems programming as well as for applications programming. Therefore C is called a middle level language.  

C is characterized by the ability to write very concise source programs, due in part to the large number of operators included within the language. It has a relatively small instruction set, though actual implementations include extensive library functions which enhance the basic instructions. C encourages users to create their own library fuctions.

An important characteristic of C is that its programs are highly portable. The reason for this is that C relegates most computer dependent features to its library functions. Thus, every version of C is accompanied by its own set of library functions which are relatively standardized. Therefore most C programs can be processed on many different computers with little or no alteration.

History of C:

C was developed in the 1970′s by Dennis Ritchie at Bell Telephone Laboratories,Inc. (now a part of AT&T). It is an outgrowth of two earlier languages, called BCPL and B, which were also developed at Bell Laboratories.

The Combined Programming Language(CPL) was developed at Cambridge University in 1963 with the goal of developing a common programming language which can be used to solve different types of problems on various hardware platforms. However it turned out to be too complex, hard to learn and difficult to implement. Subsequently in 1967, a subset of CPL, Basic CPL(BCPL) was developed by Martin Richards incorporating only the essential features. However it was not found to be sufficiently powerful. Around the same time another subset of CPL, a language called B was developed by Ken Thompson at Bell Labs. However it also turned out to be insufficient . Then, in 1972, Dennis Ritchie at Bell Labs developed the C language incorporating the best features of both BCPL and B.

C was largely confined to use within Bell Labs until 1978, when Brian Kernighan and Ritchie published a definitive description of the language . The Kerninghan and Ritchie description of C is commonly referred to as ‘K &R C’.

Following the publication of ‘K&R C’,computer professionals, impressed with C’s many desirable features, began to promote the use of C. By the mid 1980′s the popularity of C had become widespread-many c compilers and interpreters had been written for computers of all sizes and many commercial application programs had been developed. Moreover, many commercial software products that had originally been written in other languages were rewritten in C in order to take advantage of its efficiency and portability.

Early commercial implementations of C differed a little from Kerninghan and Ritchie’s original description, resulting in minor incompatibilities between different implementations. As a result, the American National Standards Institute(ANSI committee X3J11)  developed a standardized definition of C. Virtually all commercial compilers and interpreters adhere to the ANSI standard. Many provide additional features of their own.

C and Systems Programming:

There are several features of C, which make it suitable for systems programming. They are as follows:

  • C is a machine independent and highly portable language.
  • It is easy to learn; it has only 28 keywords.
  • It has a comprehensive set of operators to tackle business as well as scientific applications with ease.
  • Users can create their own functions and add to the C library to perform a variety of tasks.
  • C language allows the manipulation of bits, bytes and addresses.
  • It has a large library of functions.
  • C operates on the same data types as the computer, so the codes generated are fast and efficient.

Structure of a C Program:

Every C program consists of one or more modules called functions. One of the functions must be called main. The program will always begin by executing the main function, which may access other functions. The main function is normally,but not necessarily located at the beginning of the program. The group of statements within main( ) are executed sequentially. When the closing brace of main( ) is encountered, program execution stops and control is returned to the operating system.

Any other function defintions must be defined separately, either ahead or after main( ). Each function must contain:

1. A function heading, which consists of the function name, followed by an optional list of arguments, enclosed in parantheses.

2. A return type written before the function name. It denotes the type of data that the function will return to the program.

3. A list of argument declarations, if arguments are included in the heading.

4. A compound statement, which comprises the remainder of the function.

The arguments(also called parameters) are symbols that represent information being passed between the function and other parts of the program.

Each compound statement is enclosed between a pair of braces{ }. The braces may contain one or more elementary statements (called expression statements) and other compound statements. Thus compound statements may be nested one within another. Each expression statement must end with a semicolon(;).

Comments (remarks) may appear anywhere within a program as long as they are enclosed within the delimiters /* and */. Comments are used for documentation and are useful in identifying the program’s principal features or in explaining the underlying logic of various program features.

Components of C Language:

There are five main components of the C Language:-

1. The character set: C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9 and certain special characters as building blocks to form basic program elements(e. g. constants, variables, expressions, statements etc. ).

2. Data Types: The C language is designed to handle five primary data types, namely, character, integer, float, double and void; and secondary data types like array, pointer, structure, union and enum.

3. Constants: A constant is a fixed value entity that does not change its value throughout program execution.

4. Variables: A variable is an entity whose value can change during program execution. They are used for storing input data or to store values generated as a result of processing.

5. Keywords: Keywords are reserved words which have been assigned specific meanings in the C language. Keywords cannot be used as variable names.

The components of C language will be discussed in greater detail in the following articles. This section gives only a brief introduction to the components of C.

Example 1: The following program reads in the radius of a circle, calculates the area and then prints the result.

/* program to calculate the area of a circle*/

#include<stdio.h> /*Library file access*/

#include<conio.h> /*Library file access*/

void main( )            /* Function Heading*/

    {

       float radius, area; /*Variable declarations*/

       /*Output Statement(prompt)*/

       printf("Enter the radius :");

      /*Input Statement*/

      scanf("%f", &radius);

      /*Assignment Statement*/

      area = 3.14159*radius*radius;

      /*Output Statement*/

      printf("Area of the circle :%f", area);

       getch( );

     }

Program output:-

Enter the radius: 3

Area of the circle: 28. 27431

The following points must be considered to understand the above program:-

1. The program is typed in lowercase. C is case sensitive i. e. uppercase and lowercase characters are not equivalent in C. It is customary to type C instructions in lowercase. Comments and messages(such as those printed using printf() ) can be typed in anycase.

2. The first line is a comment that identifies the purpose of the program.

3. The instruction #include <stdio.h> contains a reference to a special file called stdio. h . This file contains the definition of certain functions required to read and print data such as printf() and scanf() . It is a header file and hence the extension . h.

4. Similarly #include <conio.h> links the file conio. h which is another header file that contains the definitions of functions used for reading and printing data at the console. The function getch() is defined in conio. h. # denotes a preprocessor directive. More about this in a later article.

5. The instruction void main() is a heading for the function main( ). The keyword void denotes the return type of main and indicates that the function does not return any value to the program after the program has finished executing. The empty parantheses ( ) after main indicates that this function does not include any arguments. Program execution always begins from main( ).

6. The remaining five lines of the program are indented and enclosed in a pair of braces { }. These five lines comprise the compound statement within the function main( ).

7. The instruction float radius, area;  is a variable declaration. It establishes the symbolic names ‘radius’ and ‘area’ as floating point variables. These variables can accept values of type ‘float ‘ i. e numbers containing a decimal point or an exponent.

8. The next four instructions are  expression statements. The instruction printf(“Enter the radius :”); generates a request for information namely,the value for the radius. This statement generates a prompt where the user enters the value .

9. The value of the radius is read into (or stored in) the variable radius with the help of the scanf ( ) function. The instruction scanf(“%f”, &radius); is used for reading data.   “%f” is a conversion character which is used to accept a floating point value.

10. The next instruction, area = 3.14159*radius*radius; is called an  assignment statement. This instruction calculates the area by using the value of radius entered by the user and assigns the value to the variable area.

11. The next printf( ) statement prints the message Area of the circle followed by the calculated area.

12. The statement getch(); is used to pause the screen so that you can read the output. If getch( ) is not used the screen will just flash and go away. This function waits for the user to input some character(as it accepts a character as input), after the program has finished executing. Any key present on the keyboard pressed by the user is accepted by the getch function as input and its ASCII value is returned to main( ).

Example2: Below is a variation of the above program:

/*program to calculate the area of a circle using a user defined function*/

#include <stdio.h>

#include <conio.h>

#define PI 3.14159

float process(float radius);/*function prototype*/

void main()

    {

      float area,radius;

      printf("n Enter the radius:");

      scanf("%f", &radius);

      area= process(radius);

      printf("Area =%f", area);

      getch();

     }

float process( float r)

     {

     float a; /*local variable declaration*/

     a= PI*r*r;
     return(a);

     }

This version utilizes a separate programmer defined function called process, to calculate the area. Within this function, r is an argument (also called a parameter) that accepts the value of radius supplied to  process from main, and a is the calculated result returned to main. A reference to the function appears in main( ), within the statement area= process(radius);

In this statement, the value of area being returned from the function process is stored in the variable area.

The main function is preceeded by a function prototype, which indicates that there is a user defined function called process which is defined after main and that it accepts a floating point argument and returns a floating point value. If the user defined function process, was defined before main( ), the function prototype would,generally, have not been required.

More explanation about this when I write about functions in a later article.

This program also contains a symbolic constant, PI, which represents the numeric value 3. 14159. This is a form of shorthand that exists for the programmers convenience. When the program is actually compiled, the symbolic constant will automatically be replaced by its numerical value. The output of this program is the same as that of the previous program.

This article was a brief introduction, it gives an idea of C programming. The next article will talk about the fundamental concepts of C which include the C character set, Identifiers and keywords, data types in detail, constants,variables, variable declarations, expressions, statements and symbolic constants .

Fundamentals of C

Fundamentals of C >>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.carlosja.com Carlos Arias

    Nice.. Basic stuff they teach in college. Keep up the good work :)

    • http://www.myblogonunix.blogspot.com Surabhi Saxena

      Thank you for the encouragement:)

  • Martin

    Great article, thanks!

    • http://www.myblogonunix.blogspot.com Surabhi Saxena

      thank you for reading the article

  • http://www.apcooper.co.uk Andrew Cooper

    Hi Surabhi,

    Just wanted to say great introduction to C, very well researched, structured, and written.

    Hi SitePoint HQ,

    Why on Earth are you publishing articles on C programming (used for desktop programming) when you are a publisher of web design and development articles and books (used for web programming)?

    I don’t come to SitePoint expecting to read about how-to program in C. I realize that you provide the articles on this website for free, but you also display advertisements I’m not interested in, and the profit you gain from the advertisements on this website will no doubt, partially at least, contribute to paying writers to publish articles on SitePoint.

    Although this is a very good article, I don’t see how it has a place on SitePoint and if I was interested in learning C programming, which I’m not (but I am interested in learning C++ programming, and am studying it currently) I would search Google for the most credible, authoritive, and popular websites that provide tutorials and articles on C programming, none of which would be SitePoint. Therefore it makes me feel like you’re wasting good money on articles like this when you could be spending it on articles and tutorials on web based programming languages such as PHP, ASP.NET Ruby on Rails, etc that people who frequent the website are interested in learning and will read because it’s from SitePoint, and SitePoint is one of the most credible, authoritive, and popular websites that provide tutorials and articles on web design and development.

    I really don’t understand. Nonetheless…

    Kind regards,

    Andrew Cooper

    • http://aosteraas.com Aaron Osteraas

      Hi Andrew,

      Thanks for your comment. Indeed, SitePoint is, typically, home of web programming topics, and yes, it is a little unusual that we have a piece on C. Though, a number of talented programmers I have spoken with on this said it would be beneficial. More specifically, I recall an interview I had at RailsCamp about a year ago, where it came up. So it was done in the interest of the readers, in that it may help them with other programming languages and the challenges they tackle.

      Thanks
      Aaron

      • http://www.apcooper.co.uk Andrew Cooper

        Hi Aaron,

        Thanks for the reply and the explanation, it seems like a reasonable thing to do and I can understand your point of view, but…

        If you have specific sites within the SitePoint Network, RubySource for Ruby, BuildMobile for iOS, Android, WP7, and Mobile Web, DesignFestival for website design, PHPMaster for PHP & MySQL, and so on, why not just introduce a new network website specifically for desktop programming, a site teaching C / C++ and Java or something?

        I won’t say anything more on the subject, I can understand why you’ve done this, but I think if you’ve done this purely in the interest of the readership then it would be better off as a new programming specific site within the SitePoint Network. I mean, if you aren’t going “all-in” with providing traditional programming language tutorials and articles, why bother at all? It’s like you’d be leading the readership on into reading the tutorials / articles up until you decide to stop providing them, then they’ll get annoyed that they have to find and rely on another website…One that actually is a credible, reliable, authoritive, and popular programming website.

        All the best with this venture anyway. As I said to the author and to you, it’s a great article, I’m not denying that, there’s absolutely nothing negative for me to say about it, it’s just authoring it on the SitePoint website that I’m slightly against. Personally, as a long-time fan of SitePoint and everything they produce (I’ve bought the books, the courses, the videos, the posters, all sorts on different subjects!) I just want to say, I won’t be one of the interested readers for the programming tutorials as I rely on other websites for that.

        Kind regards,

        Andrew Cooper

      • David

        Let’s have a look at Andrew and Aaron’s experience in web publishing and see who has the experience to know whether or not it is okay to post an intro to C for web developers.

        Let’s see… Aaron Osteraas has run two of the biggest networks out there for developers and creatives. Andrew Cooper… frequents forums?

        Man. I suggest you listen to Cooper, Aaron.

    • Jamie Diemer

      I’d have to agree with you on most points, but I’ll throw out some justifications for the sake of conversation :-P

      In my experience, web languages like PHP are sometimes used as a stepping-stone that leads to desktop programming. For these programmers, being confronted with a C article on a website they frequent might evoke a “hey, that’s not so bad” reaction and push them toward further learning. That’s stretching it a bit, I know…

      A logical follow-up to this article to make it slightly more relevant might be looking at how to write a small CGI program in C for use with web server like Apache. Theoretically some or all of your web app can be written in C/C++ using CGI/FastCGI, so this might be something that readers would be interested in.

      • Johnny

        I also believe that this article about C programming language is somewhat out of place. But it’s a good read, I’m good C programmer when I was in College. It brings back good old memories. ha. If you have fundamentals of C programming, you will also do good on web programming base on experience. I have to admit PHP, ASP and other web programming is much easier to learn compare to C.

  • Les

    I am affluent with PHP on the server side and this I am confortable with but… I’ve always been curious about C and this introduction has definitely made me think about wanting to learn more alas I would prefer Objective C though, as I develop skills for OOP with PHP.

    Maybe you could cover this further down the road, that I would welcome very much!

  • Charle

    Thanx for the post. It has actually helped remove some of the dreadding I was doing into learning C. Post more of this stuff please.

    • http://www.myblogonunix.blogspot.com Surabhi Saxena

      Thank you for your comment.I will be continuing with C- from basic to advanced.

  • https://systemsaviour.com/ boltronics

    The examples are very Windows focused. Apparently conio.h only exists for old DOS compilers? Wikipedia seems to think so. https://en.wikipedia.org/wiki/Conio.h
    Additionally, “If getch( ) is not used the screen will just flash and go away” sounds like Windows behaviour to me.

    There are also some syntax errors (probably messed up by WordPress formatting). It seems that all ‘.’ characters have been proceeded by a space which is invalid. Further, main should return an int instead of void to prevent compiler warnings, the printf statement in the first example is missing the %f, and “float process( float r);” function heading in the second example shouldn’t have a ‘;’ before the opening bracket. Hopefully these points appear in this post correctly at least. :)

    As such, I’ve thrown together a version of the examples that work for me here:
    https://gitorious.org/sitepoint-an_introduction_to_c/sitepoint-an_introduction_to_c/trees/master

    Otherwise, a very enjoyable read. I haven’t programmed in C in years and this brought back memories from my student days.

    • http://www.myblogonunix.blogspot.com Surabhi Saxena

      Thank you very much for pointing out the errors.Yes they were due to wordpress formatting.I have corrected them now and I hope that they show up properly.
      As for conio.h it exists even for windows. In general you can program by including only stdio.h but I have seen some compilers give errors.
      A main function that returns an int has given many problems when I programmed on windows. Whereas on Linux an int main() works better.
      Coming to getch( ) yes it is typically Windows based behaviour.
      In this post I have already mentioned that “Virtually all commercial compilers and interpreters adhere to the ANSI standard. Many provide additional features of their own”. IBM mainframe computers adhere to the EBCDIC code and not ASCII. Similarly for different operating systems program behaviour is different .Even when you program on windows the same program gives different errors on different compilers.
      I believe C was one of the first languages that introduced the concept of portability along with the ease of programming in simple English. There are very minor differences from compiler to compiler and O.S. to O.S.
      This is my first post on C so I didn’t get into too many technicalities..but from my next post which has already been scheduled to be printed I will be pointing out the differences that exist from compiler to compiler.
      I also saw the examples that you put up. Thank you as they will make things clearer for those who do not program on windows.
      Thank you for reading my post and appreciating it. :)

      • https://systemsaviour.com/ boltronics

        Hi Surabhi,

        It’s mostly correct now, but I still don’t think the second example will compile with the extra ‘;’ in the process function header before the curly braces. I can’t use your exact example since I’m not on Windows, however when I change my version to have that I get “error: expected identifier or ‘(’ before ‘{’ token”.

        > As for conio.h it exists even for windows.

        I think it is specific only to MS operating systems. I don’t know of any Debian GNU/Linux package that includes that, and it’s definitely not ANSI. Relying on it to exist kills the portability benefits C brings.

        > In this post I have already mentioned that “Virtually all commercial compilers and interpreters adhere to the ANSI standard. Many provide additional features of their own”

        Agreed, and most released in the last 10 years should probably support C99 also. The standards exists to bring code compatibility across different compilers so it would be helpful to the widest audience of readers for you to stick to those. When I was in uni (before C99 was common), each compiler warning produced with gcc -ansi -pedantic -Wall would cost a mark! :)

        > A main function that returns an int has given many problems when I programmed on windows. Whereas on Linux an int main() works better.

        I’ve thankfully never programmed in C on Windows, however my understanding is that ANSI C requires main to return an int. It’s used in all the C text books I have on my shelf (except for a really old book from back when functions without a return type specified were assumed to be int). See here: http://c-faq.com/ansi/maindecl.html . In any case, this could only be a problem with a few specific compilers. I am aware that there is Cygwin for Windows which includes the gcc compiler, so that likely won’t have the problem you mention if you happen to be on that platform. http://cygwin.com/

        Look forward to reading about different compilers in your next article. I’ve been hearing a lot lately about Clang (eg. http://www.phoronix.com/scan.php?page=news_item&px=MTEwMjI ), but don’t recall ever using anything other than GCC.

  • Kise S.

    Thank you i always wanted to learn C but for some reason never had the time to actually start learning it!

  • http://www.bestsms4u.com/ Best SMS

    Nice post. too much help full for the students who are going to learn C language.

  • Roger

    Surabhi,
    Very nice post, nice to see someone writing this way about C that is a wonderful language. Mainly because it is one of the easiest to learn.

    Jamie Diemer,
    Couldn’t agree more, it would be very good if people knew they can write CGI scripts in C to respond requests as they write in Ruby on Rails, PHP or whatever other high level server side languages.
    It would be also good to mention that most languages came from C, most had theirs first compilers/interpreters written in C and many still have.

    By the way, great post!

    • http://www.myblogonunix.blogspot.com Surabhi Saxena

      Thank you very much for your comment as well as for appreciating my post. I am happy to see that so many people like C.
      Yes C is very easy to learn and once you are good at C you can easily learn any other language.I agree with you that most languages came from C. We were taught that C was the mother of all languages.