CS 158A - Input, Output and Arrays in 'C'
Input
'scanf' is probably the best known function in 'C' to input data. It follows the same format as printf(used to output). It is defined in stdio.h
Say, you would like to input an integer and a float:
#include <stdio.h>
int main(void)
{
int number;
float decimal;
printf("\nPlease input a integer: ");
scanf("%d",&number);/*the & sign is required before the variable, we will discuss this later*/
printf("\nNow, input a float: ");
scanf("%f",&decimal);
printf("\nOK, you just typed in %d and %f",number,decimal);
}
Output
We have already talked about output using printf. Below, we will discuss how to use printf to result in custom and formatted output.
Say we have integers 101000 and 10 and would like the following output:
101000 10
We would do:
#include <stdio.h>
int main(void)
{
int number1=101000,number2=10;
printf("%6d\n%6d",number1,number2); /*%6d = an integer right justified with width 6/*
}
Say we have floats 1.2 and 1.23 and we would like the following output:
1.20
1.23
We would do:
#include <stdio.h>
int main(void)
{
float number1=1.2,number2=1.23;
printf("%4.2f\n%4.2f",number1,number2); /*%4.2f means an output of width 4 in which there can be 2 decimal places*/
}
You can type 'man printf ' at the unix prompt for more info.
Arrays
Say you would like to input 100 integers... certainly it wouldnt be clever to declare 100 variables!
In such cases we use arrays:
int my_array[100]; is a declaration for an array. This gives us the following variables:
my_array[0], my_array[1], my_array[2] ................. my_array[99]. Keep in mind 'C' counts starting from zero, and therefore the last array, in this case my_array[100] is not usable.
Below is an example which inputs 10 integers using arrays:
#include <stdio.h>
int main(void)
{
int my_array[10], i;
for(i=0;i<10;i++)
{
printf("\nPlease input an integer: ");
scanf("%d",&my_array[i]);
}
}
-END-