Back Next

Programming in C

Lesson 2


Course support : You can ask your course questions in Learnem support forums .

Please support us by visiting our support forums and asking your questions and answering questions of others.

2-1 Introduction

In previous lesson you learned about variables and printing output results on computer console. In this lesson we will learn how to get input values from console and output results after doing required calculations and processes.


2-2 Receiving input values from keyboard

Let's have an example that receives data values from keyboard.

Example 2-1:

#include<stdio.h>
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",c);
}

Output results:

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

* As scanf itself enters a new line character in receiving line we will not need to insert it in 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.

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 not to work as expected. For now 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. 


2-3 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] so we can work with these variables like other variables:

scores[0]=124;
scores[8]=1190;


Example 2-2:

Receive 3 scores of a student in an array and finally 
calculate his average.

#include<stdio.h>
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",sum,avg);
}

Output results:

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


2-4 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:

main()
{
char name[20];

printf("Enter your name : ");
scanf("%s",name);

printf("Hello, %s , how are you ?",name);
}

Output Results:

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

If user enters "Brian" then the first member will contain 'B' , second 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 snd its value is 0, however we show it with two characters )

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[0]='\0';

As we saw in above example placeholder for string variables is %s.

Also we will not use a '&' sign for receiving string values. we will understand the reason in future lessons.


2-5 Preprocessor

Preprocessor statements are those starting with '#' sign. An example is #include<stdio.h> 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 step, compiler starts its work.


2-6 #define preprocessor command

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

Example 2-4:

#include<stdio.h>

#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",QUOTE);
}

Output results:

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

As preprocessor step is performed before compilation step, compiler will see this program as below

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

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.


2-7 Variable limitations

variable limit for holding variable values is related to the amount of memory space it uses in system memory.
Also in different operating systems and compilers different amount of memory is allocated for specific variable types . For example int type will use 2 bytes in DOS but 4 bytes in windows environment.

If you are not sure of limitations of variable types in your system you must see your compiler information.

Also we can use sizeof() function to determine size of a variable or variable type.

Example 2-5:

main()
{
int i;
float f;

printf("Integer type uses %d bytes of memory.", sizeof(i));
printf("float type uses %d bytes of memory.", sizeof(float));
}

You see we can use both a variable and a variable type as a parameter to sizeof() function.

In this table you will see limitations of Turbo C and Microsoft C in DOS operating system.


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 also two kinds of variables from above types in C programming language. Signed and unsigned. Signed variables support negative numbers too while unsigned values only support positive numbers.

If signed variable is used above range will be divided by two. 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.


Exercises:

Course support: 
Paid students must send exercises to their tutor. Tutor will return corrected exercise to the student. Others can ask their  questions in Support forums in our web site.

http://www.learnem.com/forums


1- Write a program that asks for work hours, wage per hour and tax rate and outputs payable money for a person.

2- Using arrays write a program that receives tax rate, work hours and wage per hour for two persons in arrays and then calculates and outputs payable money for each of them.

3- Write a program that asks for your name and outputs 3 first characters of your name each in a separate line. 
Use %c as placeholder of a single character in printf format string.

============================================================ 

© 2000,2001 Siamak Sarmady and Learnem Group . All rights reserved. This text is licensed to be used on ProgrammingUni website. Any kind of reproduction, redistribution in any form is strictly prohibited without written permission of the writer. 

Back Next