Learning basic knowledge of C language I (printf,scanf, array)


Summary of the knowledge points of the introductory programming course that everyone who studies geek time can learn

First question digit output

requirement
  • Geek time: an introduction to programming that everyone can learn. Lecture 2, thinking problem: digit output
  • Calculate the number of digits in the decimal representation of an input integer?
  • Condition 1: how to implement when redundant output is allowed?
  • Condition 2: how to realize when only digital digits are allowed to be output
code implementation
//Code from geek space course
#include <stdio.h>
int main() {
    long long int n;
    scanf("%I64d", &n);
    printf(" has %I64d digits\n", printf("%I64d", n)); // Redundant output
    char output[50];
    int ret = sprintf(output, "%I64d", n);
    printf("%I64d\n", ret); // No redundant output
    printf("%s", output);
    return 0;
}
Summary and harvest
  1. Some new understandings of sprintf() and sscanf() functions
    1. Make good use of return values
      The return value of printf() function is the number of output characters, which is negative when expressing errors
      The meaning of the returned value of sprintf() is similar to that of printf
      scanf() returns the number of successfully assigned data items. If there is an error at the end of the file, EOF is returned
      eg:scanf("%d,%d", &a,&b)
      If ab is successfully read in, the return value of scanf is 2
      If only a succeeds, the return value is 1
      If none is successful, 0 is returned
      EOF is returned if an error is encountered or end of file is encountered
      The return value of sscanf() is similar to scanf
    2. The function of sscanf and sprintf: memory is distinguished by comparison with scanf and printf functions
      1. printf prints the format data on the screen, and sprintf prints the format data in a string. for example:
        printf("%s, %c, %d", x,y,z); //Print the value of xyz on the screen separated by commas
        sprintf(str, "%s, %c, %d", x,y,z); //Write xyz to the array str separated by commas.
        
      2. testcode(printf , sprintf)
        #include <stdio.h>
        int main()
        {
           char array[100];
           int num = 100;
           char testChar = 'B';
           char charArray[12] = "thank you!";
           printf("%s%c%d\n", charArray, testChar, num);
           sprintf(array, "%s%c%d", charArray, testChar, num);
           printf("%s", array);
           return 0;
        }
        
      3. The sscanf() function is similar to the scanf() function, which is used for input. The former takes the fixed string as the input source, and the latter takes the screen as the input source.
      		scanf("%d", &x);
      		char s[] = "hello, my friend";
      		sscanf(s, "%[a-z]", string);//string = hello
      
      1. testcode(scanf sscanf)
        /*Code part to be determined*/
  2. When printing printf or entering scanf long int, it is represented by format control character% I64d

The second question reads a line of string

requirement
  • To realize a program that reads a line of string and outputs relevant contents, think as follows:
  • Condition 1: how to implement if there is no space in the string?
  • Condition 2: how to implement if there is no space in the string? Consider a pure scanf implementation
code implementation
//from geek time Hu Guang
#include <stdio.h>
char str[100];
int main()
 {
    scanf("%[^\n]s", str);
    printf("%s\n", str);
    return 0;
}
Summary and harvest
  1. The code is very simple, focusing on the use of "% [^ \ n]s", where [] represents a set, that is, the input string will be output normally as long as it is not a newline character.
  2. strlen indicates the length of the string, excluding \ 0
  3. sizeof indicates the memory occupied by the string, including the memory occupied by \ 0.

Question 3 array recursion

requirement

Read an integer n in sequence. Assuming that n will not be greater than 1000, please output the number of 1 in the binary representation of each number from 1 to n

code implementation
#include <stdio.h>

int main(void){
	int array[1001];
	int number,i;
	
	scanf("%d", &number);
	array[0] = 0;
	for(i=1; i<=number; i++){
		array[i] = array[i & (i - 1)] + 1; 
	}
	for(i = 1; i<=number; i++){
		if(i!=1) printf(" ");
		printf("%d", array[i]);
	}
	printf("\n");
	return 0;
}
Summary and harvest
  1. It seems to have no rules. Maybe the first idea is to count each number. In other words, judge whether the binary code at the end of the number is 1, and then carry out shift operation to count the number of 1. Although it is feasible, it is not efficient. I just wanted to do this at the beginning.
  2. Slowly found that the essence of similar problems is to find mathematical laws, just like the arithmetic problems encountered in primary school, calculating the sum of 0-100 numbers, some people add one by one, some people first look at the laws, and then calculate them quickly. The efficiency between the two is very different. This is an ability that can be exercised!
  3. Find rules
123456789
000100100011010001010110011110001001

If you want to use recursion, you have to find out the practice between two adjacent numbers. You can use the previous number to represent the latter number. Now observe the relationship between binary numbers between N and n-1. There are two cases:

  1. )If the binary end of n is 1 (i.e. odd), n-1 changes the last bit of n to 0
  2. )If the binary end of n is 0 (i.e. even), then n-1 changes the last bit 1 of n to 0, and then each bit is 1
  3. )Through the above observation and analysis, we understand that a common feature is that n-1 makes the last 1 of N become 0, and then all the zeros after the last 1 become 1. At this time, it is easy to observe by comparing N and N-1 that the last 1 of N and its subsequent bits are different from the bits corresponding to n-1. At this time, it is not abrupt to introduce the concept of bitwise AND &, That is, n & (n-1) actually represents one less than the number of 1 in the binary of N;
  4. )Here, recursion comes in handy. If the number of 1 in the binary of number n is stored in arry[n], then if you want to know 2, you have to know 2 & 1, 3 have to know 3 & 2 first, and so on. The initial condition is known, that is, the number of 1 in the binary of 0 is 0, then recursion is formed.

Question 4 multiple problem

requirement

Title Requirements: design a program to remove multiples
Specific contents:

  1. Read in two integers n and m, where the size of n will not exceed 10 and the size of M will not exceed 10000;
  2. Then read in n different positive integers and output all numbers that cannot be divided by any of the n positive integers (range: 1 - m);
code implementation
#include<stdio.h>
int main(void){
	int array[10001];
	int i, j, k;
	int valueA,valueB, num;
	scanf("%d%d", &valueA, &valueB);
	printf("Please enter the number: ");
	for(i=0; i<valueA; i++){
		scanf("%d", &num);
		if(num == 1){
			printf("there is no number!\n");
			return 0;
		}
		for(j = num; j <= valueB; j += num){
			array[j] = 1;
		}
	}
	for(k=1; k<=valueB; k ++){
		if(array[k] != 1)
			printf("%d ", k);
	}
	printf("\n");
	return 0;
} 
Summary and harvest
  1. If the problem is complicated, always consider some things such as minimum common multiple and maximum common divisor. There may be some good methods, but the cart before the horse. First, implement it according to your own ideas, and then optimize it.
  2. For me, the biggest difficulty of the problem is that the code does not know how many numbers will be divided before it is input. As a result, after all inputs are completed, it is impossible to accurately output the results, and it is likely to be output repeatedly.
  3. Using the array, after each integer is input, its multiple is marked, and then output uniformly after the input is completed.
  4. So finally, please pay attention to the use of arrays.

Question 5

requirement

Title: program for printing and outputting floating point data n digits after the decimal point
requirement:

code implementation
#include<stdio.h>

int main(void){
	char string[100];
	int num = 0;
	double value = 0;
	
	scanf("%lf%d", &value, &num);
	sprintf(string, "%%.%dlf\n", num);
	printf(string, value);
	return 0;
} 
Summary and harvest
  1. Understand the last two points in the course. Only when you try to program yourself and encounter problems, can you deeply understand the meaning of what others say. Otherwise, it will only be a paragraph and you will never have your own understanding Feelings from Xiaobai.
  2. Understand that string information can be stored in character array. Character array is "variable" and string is "value";
  3. sscanf and sprintf functions essentially do the conversion between various data types with string as the intermediate value.

Keywords: C Programming string array printf

Added by nitediver on Tue, 25 Jan 2022 13:06:17 +0200