Abstraction is the paradigm of specific examples to a more general context, and abstraction is very important for computer science. Taking our learning function as an example, it is actually observed that some operations are used repeatedly, and we abstract it into a functional module so that it can be called more than once. You can see
Http://en.wikipedia.org/wiki/Abstraction_principle_ (computer_programming).
Now we have a group of numbers, int arr[n] = {1, 2, 3, 4, 5}; You want the output format as follows
1 2 3) 4 5
Onlinejudge's topic generally requires 5 with no spaces followed by a newline. So the following code does not work:
1#include <stdio.h>2 #defineN 53 intMainvoid)4 {5 intI, arr[n] = {1,2,3,4,5};6 for(i =0; i < N; i++)7printf"%d", Arr[i]);8printf"\ n");9 return 0;Ten}
I wrote the following code, the first element is handled separately, the next element has a space before it, and then a newline.
1#include <stdio.h>2 #defineN 53 intMainvoid)4 {5 intI, arr[n] = {1,2,3,4,5};6printf"%d", arr[0]);7 for(i =1; i < N; i++)8printf"%d", Arr[i]);9printf"\ n");Ten return 0; One}
is not feeling refreshing, yes, a small function incredibly divided into three kinds of situations. Perhaps the last element should be treated differently, see the code below
1#include <stdio.h>2 #defineN 53 intMainvoid)4 {5 intI, arr[n] = {1,2,3,4,5};6 for(i =0; I < N-1; i++)7printf"%d", Arr[i]);8printf"%d\n", Arr[n-1]);9 return 0;Ten}
There's really a printf missing, only two cases. Can it be unified again? Note that the spaces and line breaks are characters and can be abstracted as follows:
You want to pick a separator character after each output element
1#include <stdio.h>2 #defineN 53 intMainvoid)4 {5 intI, arr[n] = {1,2,3,4,5};6 for(i =0; i < N; i++)7printf"%d%c", arr[i], i = = N-1?'\ n':' ');8 return 0;9}
%c is an excellent abstraction, ascending from specific spaces and newline characters. We soon realized that if we wanted to output
1,2,3,4,5
You only need to change the space to a comma. This means
The specific character may change, and the delimiter is the higher-level abstraction of the problem.
Practical Guide for Beginners Programming (4)-Learn abstract by a simple example