Getting input, Arrays, Character Strings and Preprocessors



Part–2: Getting input, Arrays, Character Strings and Preprocessors
n previous lesson you learned about variables and printing output results on computer console. This lesson discusses more about variables and adds important concepts on array of variables, strings of characters and preprocessor commands. We will also learn more on getting input values from console and printing output results after performing required calculations and processes. After this lesson you should be able to develop programs which get input data from user, do simple calculations and print the results on the output screen.

Receiving input values from keyboard
Let's have an example that receives data values from keyboard.
Example 2-1: example2-1.c
#include
main()
{
int a,b,c;
printf("Enter value for a :");
scanf("%d",&a);
printf("Enter value for b :");
scanf("%d",&b);
c=a+b;
printf("a+b=%d\n",c);
system("pause");
}

Output results:
Enter value for a : 10
Enter value for b : 20
a+b=30

As scanf itself enters a new line character after receiving input, we will not need to insert another new line before asking for next value in our second and third printf functions.

General form of scanf function is :
scanf("Format string",&variable,&variable,...);

Format string contains placeholders for variables that we intend to receive from keyboard. A '&' sign
comes before each variable name that comes in variable listing. Character strings are exceptions from this rule. They will not come with this sign before them. We will study about character strings in this lesson.

Important: You are not allowed to insert any additional characters in format string other than
placeholders and some special characters. Entering even a space or other undesired character will cause your program to work incorrectly and the results will be unexpected. So make sure you just insert placeholder characters in scanf format string.

The following example receives multiple variables from keyboard.
float a;
int n;
scanf("%d%f",&n,&a);

Pay attention that scanf function has no error checking capabilities built in it. Programmer is responsible for validating input data (type, range etc.) and preventing errors.

Variable Arrays
Arrays are structures that hold multiple variables of the same data type. An array from integer type holds
integer values.
int scores[10];

The array "scores" contains an array of 10 integer values. We can use each member of array by specifying its index value. Members of above array are scores[0],...,scores[9] and we can work with these
variables like other variables:
scores[0]=124;
scores[8]=1190;

Example 2-2: example2-2.c
Receive 3 scores of a student in an array and finally calculate his average.
#include
main()
{
int scores[3],sum;
float avg;
printf("Enter Score 1 : ");
scanf("%d",&scores[0]);
printf("Enter Score 2 : ");
scanf("%d",&scores[1]);
printf("Enter Score 3 : ");
scanf("%d",&scores[2]);
sum=scores[0]+scores[1]+scores[2];
avg=sum/3;
printf("Sum is = %d\nAverage = %f\n",sum,avg);
system("pause");
}

Output results:
Enter Score 1 : 12
Enter Score 2 : 14
Enter Score 3 : 15
Sum is = 41
Average = 13.000000

Character Strings
In C language we hold names, phrases etc in character strings. Character strings are arrays of characters. Each member of array contains one of characters in the string. Look at this example:
Example 2-3: example2-3.c
#include
main()
{
char name[20];
printf("Enter your name : ");
scanf("%s",name);
printf("Hello, %s , how are you ?\n",name);
system("pause");
}

Output Results:
Enter your name : Brian
Hello, Brian, how are you ?

If user enters "Brian" then the first member of array will contain 'B' , second cell will contain 'r' and so on. C determines end of a string by a zero value character. We call this character as "NULL" character and show it with '\0' character. (It's only one character and its value is 0, however we show it with two characters to remember it is a character type, not an integer)

Equally we can make that string by assigning character values to each member.
name[0]='B';
name[1]='r';
name[2]='i';
name[3]='a';
name[4]='n';
name[5]=0; //or name[5]='\0';

As we saw in above example placeholder for string variables is %s. Also we will not use a '&' sign for receiving string values. For now be sure to remember this fact and we will understand the reason in future lessons.

Preprocessor
Preprocessor statements are those lines starting with '#' sign. An example is #include
statement that we used to include stdio.h header file into our programs.

Preprocessor statements are processed by a program called preprocessor before compilation step takes place. After preprocessor has finished its job, compiler starts its work.

#define preprocessor command
#define is used to define constants and aliases. Look at this example:

Example 2-4: example2-4.c
#include
#define PI 3.14
#define ERROR_1 "File not found."
#define QUOTE "Hello World!"
main()
{
printf("Area of circle = %f * diameter", PI );
printf("\nError : %s",ERROR_1);
printf("\nQuote : %s\n",QUOTE);
system("pause");
}

Output results:
Area of circle = 3.140000 * diameter
Error : File not found.
Quote : Hello World!

Preprocessor step is performed before compilation and it will change the actual source code to below
code. Compiler will see the program as below one:

#include
main()
{
printf("Area of circle = %f * diameter", 3.14 );
printf("\error : %s","File not found.");
printf("\nQuote : %s","Hello World!\n");
system("pause");
}

In brief #define allows us to define symbolic constants. We usually use uppercase names for #define
variables. Pay attention that we do not use ';' after preprocessor statements.

Variable limitations
Variable limit for holding values is related to the amount of memory space it uses in system memory. In different operating systems and compilers different amount of memory is allocated for specific variable types. For example int type uses 2 bytes in DOS but 4 bytes in windows environment. Limitations of variable types are mentioned in your compiler documentation. If oue program is sensitive to the size of a variable (we will see examples in next lessons), we should not assume a fixed size for them. We should instead use sizeof() function to determine size of a variable or variable type (and we should do t).

Example 2-5: example2-5.c
#include
main()
{
int i;
float f;
printf("Integer type uses %d bytes of memory.\n", sizeof(i));
printf("float type uses %d bytes of memory.\n", sizeof(float));
system("pause");
}

You see we can use both a variable and a variable type as a parameter to sizeof() function. Below table shows variable limitations of Turbo C and Microsoft C in DOS operating system as an example.

Bytes              used               Range
char                1                      256
int                    2                      65536
short               2                      65536
long                2                      4 billion
float                4                      6 digits * 10e38
double                        8                      10 digits * 10e308

We have two kinds of variables from each of the above types in C programming language: signed and unsigned. Signed variables can have negative values too while unsigned values only support positive numbers.

If a signed variable is used, high boundary will be divided by two. This is because C will divide the
available range to negative and positive numbers. For example signed int range is (-32768,+32767).

You can declare a variable as “signed” or “unsigned” by adding "signed" or "unsigned" keywords before type name.

Example:
signed int a;
unsigned int b;
a=32700;
b=65000;

We are allowed to assign values larger than 32767 to variable "b" but not to variable "a". C programming language may not complain if we do so but program will not work as expected. Alternatively we can assign negative numbers to "a" but not to "b".

Default kind for all types is signed so we can omit signed keyword if we want a variable to be signed.

Loading
Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Flying Twitter Bird Widget By ICT Sparkle