Home | About | Comments | Lectures | Notice | Registration
C Programming
Main Page
Review
Lesson Two
Lesson Four (a)
Getting User Input
You Will Learn About :
The material provided on this site is part of a complete course in Mastering C Programming. C programming at introductory level is FREE.
scanf( ) is used to obtain data from the user as input to a program.
Here is an example of how scanf( ) is used to get an integer value:
scanf("%d",&variable_name);"
The correct specifier must be used to match with the correct data type.
char %c, int %d, float and double %f, string %s
Another important point to note is that an ampersand is needed before the variable name. The ampersand means the "the memory address of "
/* Program 3A - getting integer input with scanf() */
#include <stdio.h>
main()
{
int x, y, total;
printf("Enter a number\n"); /* User prompt */
scanf("%d",&x);
printf("Enter a second number\n");
scanf("%d",&y);
total = x + y;
printf("The sum is %d",total);
exit(0);
}
Instructions :
To use the printf( ) function to print an integer value requires the use of the specifier %d or %i which tells C exactly where within the print statement the value item must be placed.
Because intergers by definition cannot hold fractions, when we perform the division operation using integers the remainder is always lost. This is because a remainder represents a fraction.That is, if 5 is divided by 3 the computer will give 1 as the answer. It cannot represent the fraction using the two bytes of memory space allocated to integers. To get this program to generate accurate figures we should use the float datatype along with the %f specifier. This we will do in another program.
Test this program with the numbers given ( 5 and 3 ) and see for yourself.
/* program 3B - Integer division */
#include <stdio.h>
main()
{
int x, y, quo;
printf("Enter an integer dividend value \n");
scanf("%d",&x);
printf("Enter an integer divisor value \n");
scanf("%d",&y);
quo = x / y;
printf("The quotient is %d .There is no remainder value ",quo);
exit(0);
}
Instructions :
The Assignment
ASSIGNMENT THREE
|
The Tutor |
|
Home | About | Comments | Lectures | Notice | Registration