Arrays, Qualifiers, and Reading Numbers
Strings
C does not allow one array to be assigned to another.
char sam[4];
sam = "sam"; // error
The standard function fgets
can be used to read a string from the keyboard. fgets
includes the end-of-line in the string.
fgets(name, sizeof(name), stdin);
Multidimensional Arrays
int matrix[2][4];
matrix[1][2] = 10;
Reading Numbers
scanf
provides a simple and easy way of reading numbers that almost never work. The functionscanf
is notorious for its poor end-of-line handling, which makesscanf
useless for all but an expert.
LOL
Instead, we use fgets to read a line of input and sscanf to convert the text into numbers. (The name sscanf stands for “string scanf”. sscanf is like scanf, but works on strings instead of the standard input.)
#include <stdio.h>
char line[100]; /* line of input data */
int height; /* the height of the triangle */
int width; /* the width of the triangle */
int area; /* area of the triangle (computed) */
int main()
{
printf("Enter width height? ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d %d", &width, &height);
area = (width * height) / 2;
printf("The area is %d\n", area);
return (0);
}
Initializing Variables
C allows variables to be initialized in the declaration statement.
int counter = 0;
int code[3] = {0, 1, 2};
/*
if an insufficient amount of numbers are present, C will initialize the extra elements to zero.
*/
int another_code[3] = {0};
/*
if no dimension is given, C will determine the dimension from the number of elements in the initialization list.
*/
int some_code[] = {1,2,3,4,5};
int matrix[2][4] =
{
{1,2,3,4},
{10,20,30,40}
}
// strings
char name[] = {'S','a','m','\0'};
// or
char name[] = "Sam";
// or
char name[50] = "Sam";
// which is equivalent to
char name[50];
strcpy(name, "Sam");
Types of intergers
The long
qualifier informs C that we wish to allocate extra storage for the integer. If we are going to use small numbers and wish to reduce storage, we use the qualifier short
.
- int
- long
- short
- signed
- unsigned
signed long int number;
All int declarations default to signed. On the contrary, char declarations do not default to signed, the default is compiler dependent.
Types of Floats
- float
- double
- long double
The qualifier long double denotes extended precision. On some systems, this is the same as double; on others, it offers additional precision. All types of floating -point numbers are always signed.
Hexadecimal and Octal Constants
Base 10 | Base 8 | Base 16 |
---|---|---|
6 | 06 | 0x6 |
9 | 011 | 0x9 |
15 | 017 | 0xF |