Practical C Programming - Chapter 5

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 function scanf is notorious for its poor end-of-line handling, which makes scanf 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 10Base 8Base 16
6060x6
90110x9
150170xF
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值