Results 1 to 6 of 6

Thread: C Programmin Tutorial - Chapter 3

  1. #1
    Antionline Herpetologist
    Join Date
    Aug 2001
    Posts
    1,165

    C Programmin Tutorial - Chapter 3

    C Programming Tutorial Chapter 3

    =============================
    Things Covered in Chapter 3
    Variables
    Rules and Guidelines for Naming Variables
    Getting Input from the User
    =============================

    Finally, a chapter 3! Chapter 4 coming soon.

    First of all, I suggest that you go back and revise chapters one and two.
    Chapter two especially has some stuff that you'll need in order to understand
    this chapter.
    Chapter 1 can be found at http://www.antionline.com/showthread...hreadid=137499
    Chapter 2 can be found at http://www.antionline.com/showthread...hreadid=140166

    Variables

    A variable is a storage space for data. Think of a variable as a kind of a
    suitcase. Just as you store stuff in a suitcase, you store data in a variable.
    Also, just as you can change the contents of the suitcase, you can change the
    contents of a variable as well. That's why it's called a variable. It's
    contents can vary. Remember all that discussion about the types of data, their
    ranges and stuff. Well, it might have sounded a bit needless then, but all that
    becomes of vital importance now.
    To understand variables better, type this program into your editor and save it
    as var1.c

    Code:
    /*var1.c
    A program to demonstrate the use of different types of variables*/
    
    #include <stdio.h>
    
    void main()
    {
    	char c;
    	int i;
    	long l;
    	float f;
    	double d;
    
    	c='C';
    	i=1454;
    	l=345346;
    	f=34.65;
    	d=3455667567.2345;
    
    	printf("char c   =\t%c\n",c);
    	printf("int i    =\t%d\n",i);
    	printf("long l   =\t%2d\n",l);
    	printf("float f  =\t%f\n",f);
    	printf("double d =\t%2f\n",d);
    
    }
    Save the program as var1.c. Compile. Fix any errors that crop up. Run.
    This program shows you that there are five types of variables in C, one for
    each
    type of data. And just so you know, int can also be written as short and short
    int while long can also be written as long int. Usually these names aren't
    used, but they exist and you should know about them.

    There's really nothing new in this program except for the variables.

    Taking the suitcase analogy further, you have to use a variable of the
    appropriate size to store any give data. Just as you can't use a small suitcase
    to store tons of stuff, you can't use a char variable to store stuff that can
    only be stored in an int. Also, it obviously doesn't make sense to use a large
    suitcase to carry just one set of clothes and nothing else. Similarly, it
    doesn't make sense to use a float to store something that could have easily
    been
    stored in an int.

    Look at the list below to see the types of variables in C.

    Type Size Range
    char 1 byte -128 to +127
    int 2 bytes -32768 to +32767
    short 2 bytes -32768 to +32767
    short int 2 bytes -32768 to +32767
    long 4 bytes -2147483648 to +2147483647
    long int 4 bytes -2147483648 to +2147483647
    float 4 bytes 3.4*10^-38 to 3.4*10^+38
    double 8 bytes 1.7*10^-308 to 1.7*10^+308

    Note: Some compilers have doubled the number of bytes used to store variables,
    so that a char uses 2 bytes, an int uses 4 and so on... This leads to a
    corresponding increase in range.
    And of course, any variable can be declared as unsigned in C to double it's
    positive range while removing it's negative range.
    Now, you might be wondering, what happens to a variable if you exceed the
    allowed range? Well, it's quite simple. The counting starts from the minimum
    value all over again. So, say you have a char variable having the value of 127
    and you add 1 to it, the new value of the variable is now -128.
    Note: This may not apply to your compiler because some compilers just keep the
    value at the maximum value when you try to exceed the range of the variable.
    (For example gcc 2.96)


    Rules and Guidelines for Naming Variables

    The rules for naming variables are as follows:
    1) A variable name MUST start with an alphabet.
    2) A variable name cannot contain special characters. (To be safe stick to
    alphabets, numbers and _ )
    3) A variable name cannot contain spaces.
    4) Duplicate variable names are NOT allowed, even if the variables they refer to
    are of different types.
    5) A variable name may not be the same as one of the reserved keywords of the C
    language (words like int, void, etc)
    6) Variable names (as everything else in C) are case sensitive so Variable,
    VARIABLE, variable and VaRiAbLe are different.

    While these are the rules for naming variables, it is also helpful to follow
    certain guidelines while naming variables. Some of the guidelines I follow are:
    1) Use descriptive names for your variables. For example, "prompt" is better
    than "p".
    2) Do not use the same name just by changing the case. For example, don't use
    "Prompt" and "prompt" in the same program.
    3) Do not give variables the same names as functions. For example, don't name a
    variable "printf". It leads to major confusion.

    You'll pick up certain other habits as you go along that'll help you a lot. Feel
    free to add them to this list.


    Getting Input from the user

    If you've ever used a DOS or *NIX program before, you'll know that getting user
    input is very important for any program to run. It isn't as obvious when using
    Windows, but yes, user input is vital even for most Windows programs. Face it,
    if we weren't able to give input to programs, how would we get them to do what
    we wanted? One of the most popular ways to get input from the user is to use
    the
    scanf() function. scanf stands for scan formatted (just as printf stands for
    print formatted). It's very similar to printf in the sense that it understands
    the same placeholders that printf does. Type this program into your editor and
    save it as input1.c

    Code:
    /*input1.c
    A program to demonstrate use of the scanf() function to get user input*/
    #include <stdio.h>
    void main()
    {
    	int i;
    
    	printf("Enter a number: ");
    	scanf("%d",&i);  //remember the ampersand(&) here
    	printf("\nYou entered %d\n",i);
    }
    Save. Compile. Fix errors. Run.
    The only new things in this program are in line 6 where you use scanf() and the
    // thing. The // thing is a comment. It's known as a C++ style comment and
    there's no need to close it. It automatically ends at the end of the line.

    The scanf statement is simple too. The %d tells it to expect an int after the
    ending quote. The only thing different with using placeholders in scanf is that
    you have to put in an ampersand(&) before the variable name. If you don't do
    that, you get a wierd error (under gcc it's "Segmentation Fault"). Also, when
    using scanf it is VERY important to see that the placeholder is the same as the
    type of variable.
    Another way of getting input is a function called getchar(). As the name
    suggests, getchar() is used to get character input from the users. getchar() is
    usually used to get input when you need to get a y/n answer from the user.
    Type this program and save it as input2.c

    Code:
    /*input2.c
    A program to demonstrate use of getchar()*/
    #include <stdio.h>
    void main()
    {
    	char prompt;
    	printf("Yes or No (y/n)?");
    	prompt=getchar();
    
    	printf("You said %c\n",prompt);
    }
    The good thing about the getchar() function used in this program is that unlike
    scanf, it isn't clunky. There's no ampersand or percent, just a simple
    equals(=)
    sign.

    That's it for this chapter. See you next time. Here's some assignments to tide
    you over until then.
    1) Change input1.c so that it reads a float value from the user. Make the
    corresponding changes to printf.
    2) Toy around with scanf() (remove the ampersand and other such mischiefs) and
    see what happens.

  2. #2
    Senior Member
    Join Date
    Oct 2001
    Posts
    638
    Nice tutorial. Quite impressive. One thing you could have added to make it a bit better is by giving some info on printing out variables with decimal places. I should also point out that ANSI C programs should define main as int main() not void main() and main should always return a value. For example:

    Code:
    int main() {
    
        float f = 333.454545;
        printf("%2.2f", f);
        return 0;
    }
    Anyways, great work. Keep it up. If you keep going at this rate, you'll have your own book! Have some greenies .
    OpenBSD - The proactively secure operating system.

  3. #3
    Senior Member
    Join Date
    Feb 2002
    Posts
    133
    You can also use:

    return EXIT_SUCCESS;

    which I was told is better practice. Why I don't know because the programs still run the same.
    If you don\'t learn the rules nobody can accuse of cheating.

  4. #4
    Antionline Herpetologist
    Join Date
    Aug 2001
    Posts
    1,165
    I should suppose that some header defines EXIT_SUCCESS to be 0. An exit with code 0 means that the program has exited normally. That's why the code's also called an errorlevel.
    Cheers,
    cgkanchi
    Buy the Snakes of India book, support research and education (sorry the website has been discontinued)
    My blog: http://biology000.blogspot.com

  5. #5
    Senior Member
    Join Date
    Feb 2002
    Posts
    133
    Yeah its the <std.lib> header thats needed.
    If you don\'t learn the rules nobody can accuse of cheating.

  6. #6
    Senior Member
    Join Date
    Feb 2002
    Posts
    133
    Sorry that was a typo. It should be <stdlib.h>
    If you don\'t learn the rules nobody can accuse of cheating.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •