[] Data structure and algorithm study notes - "algorithm notes" -2

Select structure

  • For if statement, or if the conditional expression is "= 0", there is a Faithfulness wording "= 0!":
    (! = N-0) is rewritten as if if (n-)
  • The switch statement format
switch(表达式){
	case 常量表达式1:
	    …
	    break;
	case 常量表达式2:
	    …
	    break;
	    ……
	default:
	    …
 }

If you do not break, it will be fully implemented.

Exercise:
examples 4-1 Roots of a quadratic equation

Description Title find a quadratic equation ax2 + bx + c = 0 the roots, the three coefficients a, b, c input from the keyboard, and a can not be zero, but does not guarantee b2-4ac> 0.
The variables involved in the program are double. Input separated by a space of three coefficients of a quadratic equation, the double type double output
branch output two root follows (note that the end of the wrap): r1 = r2 = root when a first output of the second root results, representing the width 7, wherein the fractional part 2.
If the equation has no real roots, one line of output information follows (note that the end of the wrap): No real roots!

#include <cstdio>
#include<cmath>

int main()
{
	double a, b, c, p;
	scanf("%lf %lf %lf", &a, &b, &c);
	p =( b * b) - (4 * a*c);
	if (a != 0 && p >= 0)
	{
		printf("r1=%7.2f\nr2=%7.2f", (-b + sqrt(p)) / (2 * a), (-b - sqrt(p)) / (2 * a));
	}
	else
	{
		printf("No real roots!");
	}
	return 0;
}

Comparative examples 4-2 to exchange real-valued

Description Title two real numbers from the keyboard input, the output value of the two numbers in accordance with the ascending order of generations. Enter two real numbers separated by spaces. Output
from small to large outputs of the two real numbers, the middle separated by spaces, the decimal front, after large numbers. Decimal 2 decimal places. The end of the output line breaks.

#include <cstdio>

int main()
{
	double a, b, c;
	scanf("%lf %lf", &a, &b);
	if (a > b)
	{
		c = a;
		a = b;
		b = c;
	}
	printf("%.2f %.2f\n", a, b);
	return 0;
}

Comparative examples 4-3 exchanged three real values, and sequentially outputs

Description Title
input from the keyboard 3 real numbers a, b, c, to exchange by comparing the minimum value is stored in a variable, the maximum value stored in the variable c, the intermediate value stored in the variable b, and in ascending order of the output of these three digits a, b, c.
Wrap the end of the output.
Input
Input separated by a space of three real
output
in ascending order of the output of the three real numbers, separated by a space intermediate, minimum front, after a maximum value. Decimal 2 decimal places.
Note wrap at the end.

#include "stdafx.h"
#include <cstdio>

int main()
{
	double a, b, c,d;
	scanf("%lf %lf %lf", &a, &b,&c);
	if (a > b)
	{
		d = a;		a = b;		b = d;
	}
	if (b > c)
	{
		d = b;		b = c;		c = d;
	}
	if (a>b)
	{
		d = a;		a = b;		b = d;
	}
	printf("%.2f %.2f %.2f\n", a, b,c);
	return 0;
}

Exercises selecting the maximum value of three integers 4-4

Title Description
There are three integers a, b, c, a keyboard input, wherein the output of the maximum number.
Enter
three integers separated by spaces.
Output
the maximum number of three, at the end of wrapping.

#include <cstdio>

int main()
{
	int a, b, c,max;
	scanf("%d %d %d", &a, &b,&c);
	max = a;
	if (max < b)
		max=b;
	if (max < c)
		max = c;
	printf("%d\n",max);
	return 0;
}

Problem 4-10-1 Bonus Calculation

Title Description
an enterprise commission bonuses based on profits. Profit I less than or equal 100,000, can provide bonuses of 10%; when the profit of more than $ 100,000, less than 200,000 yuan (100000 <I <= 200000) , below 100,000 membered partially based upon 10% commission, higher than 100,000 Percent element portion is 7.5%; 200000 <I <= 400,000 when less than 200,000 yuan portion commission based upon the above method (hereinafter the same), in which more than 5% of the 200,000 yuan commission; 400000 <I <= 600000 yuan, in which more than 400,000 yuan of 3% commission; 600000 <I <= 1000000, the part higher than 600,000 yuan commission is 1.5%; I> when 1 million yuan, more than one million yuan portion 1% commission.
Output from the keyboard month profit I, seeking to be made a few bonus, bonus to the minutes.
Required to achieve with the if statement.
Enter
corporate profits, decimal, double, double type
output
should send a few bonus, 2 decimal places, the end of the wrap.

#include <cstdio>

int main()
{
	double I,bonus;
	scanf("%lf", &I);
	if (I <= 100000)	
		bonus = I * 0.1;
	if (I > 100000 && I <= 200000)
		bonus = 10000 + (I - 1000000 * .075);
	if (I > 200000 && I <= 400000)
		bonus = 100000 * 0.175 + (I - 200000)*.05;
	if (I > 400000 && I <= 600000)
		bonus = 100000 * 0.225 + (I - 400000)*.03;
	if (I >600000 && I <=1000000)
		bonus = 100000 * 0.255 + (I - 600000)*.015;
	if (I > 1000000)
		bonus = 100000 * 0.27 + (I - 1000000)*0.01;
	printf("%.2f\n", bonus);
	return 0;
}

Loop structure

  • while statement:
while(条件){
……
}//注意这里没有分号
  • do while statement
do{
	…
}while(条件);//注意这里有分号
  • for statement
for(表达式A;表达式B;表达式C){
	…
}//注意这里没有分号

In addition, C language does not allow expression A variable defined in a for statement, but C ++ can.

  • break / continue statement

Exercise:
examples 5-1-1 successive natural numbers summing

Seeking 1 + 3 + 2 + ... + 100
required to achieve a while statement
input
no
output
requirements and, at the end of line feed output.

#include <cstdio>

int main()
{
	int sum=0,i=1;
	while(i<=100)
	{
		sum += i;
		i++;
	} 
	printf("%d\n", sum);
	return 0;
}

Examples 5-1-2 successive natural numbers summing

Description Title
seek 1 + 2 + 3 + ... + 100, i.e. seeking
requirements for do ... while statement to achieve
input
without
outputting
the calculation result, the output end note wrap.

#include <cstdio>

int main()
{
	int sum=0,i=1;
	do
	{
		sum += i;
		i++;
	} while (i <= 100);
	printf("%d\n", sum);
	return 0;
}

Examples 5-1-3 successive natural numbers summing

Description Title
seek 1 + 2 + 3 + ... + 100, i.e. seeking
required to achieve a statement for
input
no
output
calculation result, the output end of the wrapping.

#include <cstdio>

int main()
{
	int sum=0;
	for (int i = 1; i <= 100; i++)
	{
		sum += i;
	}
	printf("%d\n", sum);
	return 0;
}

Examples 5-1-4 successive natural numbers summing

Title Description
enter a positive integer N, seeking 1 + 2 + ... + N, i.e. seek
is required in a program break statement.
Input
data input requirements must be a positive integer.
Output
result of the calculation, and continuously, the output end of the natural numbers N wrap.

#include <cstdio>

int main()
{
	int sum=0,i=1,N;
	scanf("%d", &N);
	while(1)
	{
		if (i > N)	break;
		else
		{
			sum += i;
			i++;
		}
	} 
	printf("%d\n", sum);
	return 0;
}

Examples 5-1-5 successive natural numbers summing

Description Title
programming requirements 1 + 2 + 3 + ... and the procedures required to obtain a positive integer so that the sum is greater than the minimum of 1000.
Input
No
Output
Output Enable 1 + 2 + 3 + ... + N> 1000 smallest positive integer N, the output end of the wrapping.

#include <cstdio>

int main()
{
	int sum=0,i=1;
	while(1)
	{
		if (sum <= 1000)
		{
			sum += i;
			i++;
		}
		else
		{
			printf("%d\n", i-1);
			break;
		}
	} 
	return 0;
}

Examples 5-6 matrix output

Title following matrix describes the output 4 * 5
. 1. 3 4 5 2
2 4 10. 8. 6
. 3. 6. 9 15 12 is
4 16. 8 12 is 20 is
required to achieve the cycle, each line of output 5 note numbers, each representing three characters width, right justified.

#include <cstdio>

int main()
{
	for(int i=1;i<=4;i++)
		for (int j = 1; j <= 5; j++)
		{
			if (j%5)
				printf("%3d", i*j);
			else
				printf("%3d\n", i*j);
		}
	return 0;
}

Examples 5-7 to find pi pi approximation

Title described
by the following equation π / 4 = 1-1 / 3 + 1 / 5-1 / 7
seeking pi PI approximation, until it finds an absolute value of a far less than 10-6 (without the accumulation).
The overall result of the required output width accounts 10, wherein an 8-bit fractional part.
When the program using floating-point data, defined as double double.
If you need to calculate the absolute value, may be used math functions fabs C language library provides, as required absolute value of x, compared with fabs (x).
Input
No
Output
approximation PI = ratio of the circumference of the
result output representing the total width of 10, wherein the fractional 8 is a part.
Wrap the end of the output.
...

#include <cstdio>
#include<cmath>

int main()
{
	double i=0,pi=0;
	while ((1 / (2*i+1)) >= 1E-6)//注意这里的1E-6
	{
		pi += (pow(-1,i)/( 2*i+1));//pow 最好两个参数都为double
		i++;
	}
	printf("PI=%10.8f\n", 4 * pi);
	return 0;
}

Examples 5-8 Fibonacci series

Title Description
enter a positive integer n, the number n of required Fibonacci sequence.
Fibonacci sequence features: first and second number of 1,1. 3 from the first number, is outlined in front and two numbers. That is:
the input requirements positive integer n is not more than 50. The
input 50 a positive integer not exceeding n number of output Fibonacci sequence, the output end of the wrapping.

#include <cstdio>
#include<cmath>

int main()
{
	int n, output,a=1,b=1;
	scanf("%d", &n);
	if (n <= 50)
	{
		if (n == 1 || n == 2)	printf("1\n");
		else
		{
			for (int i = 3; i <= n; i++)
			{
				output = a + b;
				a = b;
				b = output;
			}
			printf("%d\n", output);
		}
	}
}

Problem 5-10 sequence summing scores
Title Description

We have the following sequence of fraction
2 / 1,3 / 2,5 / 3,8 / 5,13 / 8,21 / 13 ... and this calculated front 20 of the series.
And obtained before 20 the number of columns.
Please The data type is defined as a double.
Input no output after the decimal point six decimal places, the output end of the wrapping.

int main()
{
	double mun, den=3,a=2,b=3,output=(double)2/1+(double)3/2;
	for (int i = 3; i <= 20; i++)
	{
		mun = a + b;
		a = b;
		b = mun;
		output += (mun / den);
		den = b;
	}
	printf("%.6f\n", output);
}

Array

  • If you want to give the whole array of Du Fu initial value 0, you can have the following form:
int a[10]={0};
int a[10]={};
  • If the size of the array is relatively large (about 10 ^ 6 levels), you need to define outside the main function, or make the program quit unexpectedly because of smaller local variables within the function space application stack from the system, allowing the application; and spatial functions global variables from the external application static memory, allows larger application.
  • memset-- each element in the array is assigned the same value
    format: memset (array name, value, sizeof (array name));
    Usually there are two functions can be achieved: memset / fill;
    using memset to add string.h;
    recommendations Fu beginner 0 or -1, since memset use the "byte assignment";
    if you want to assign another number (such as 1), is recommended to use Fill;
    execution speed is greater than memset fill.
    Example:
#include "stdafx.h"
#include <cstdio>
#include<cstring>

int main()
{
	int a[5] = { 1,2,3,4,5 };
	memset(a, 0, sizeof(a));
	for (int i = 0; i < 5; i++) 
	{
		printf("%10d", a[i]);
	}
	printf("\n");
	memset(a, -1, sizeof(a));
	for (int i = 0; i < 5; i++)
	{
		printf("%10d", a[i]);
	}
	printf("\n");
	memset(a, 1, sizeof(a));
	for (int i = 0; i < 5; i++)
	{
		printf("%10d", a[i]);
	}
	printf("\n");
}

Output Results:
0 0 0 0 0
-1 -1 -1 -1 -1
16,843,009 1,684,300,916,843,009 1,684,300,916,843,009
Press any key to continue.

  • Initialize an array of characters in two ways:
char str[15]={'G','O','O','D',' ','S','T','O','T','Y','!'};
char str[15]="GOOD STORY!";//注意单双引号的差别

Note that the second method is limited to initialize other places in the program can not be assigned directly to the entire string

  • Character array input function: scanf / getchar / gets
  • String array output functions: printf / putchar / puts
  • scanf "% s" space identified as the end of the string, without &;
  • getchar / putchar character input single output, line breaks can be used to absorb
    Example:
int main()
{
	char str[5][5];
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			str[i][j] = getchar();
		}
		getchar();//这句可以把输入中每行末尾的换行符吸收掉!!!
	}
	putchar('\n\n\n');
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			putchar(str[i][j]);
		}
		putchar('\n');//注意单引号
	}
}

Results absorbent newline result output = input, will absorb no line breaks misrecognized
Here Insert Picture Description
Here Insert Picture Description

  • gets used to enter his string, as a newline end,
    therefore, if you want to use the scanf gets, need to use the line feed scanf absorbent getchar

  • output puts his string, and followed by a newline

  • Storing character array embodiment of
    the one-dimensional / two-dimensional array at the end of the second dimension has a null character \ 0 represents the end of the string stored;
    null character \ 0 or when using scanf gets input character string is automatically added to the behind the character string, and occupies one bit;
    the puts / identification is through the printf \ 0 to end of the string as output.
    Char array need only \ 0 as the end, int not required;
    \ 0 is not a space;
    length character array at least over a certain length than the actual storage of the string;
    if not a function scanf% s gets function or input string ( such as the use getchar), please enter each string must be in after adding "\ 0", otherwise printf and pufs output string will not be recognized because a lot of garbled output end of the string.

  • string.h header file function
    Memset / strlen / strcmp / strcpy / strcat
    strlen (character array): to give a number of characters in the first array \ 0 before the character;
    strcmp (an array of characters, character array 2): comparison, a small returns negative, large positive number equal to 0,1;
    strcpy (an array of characters, character array 2): the character array 2 includes an end character "\ 0" to 1 copy together;
    strcat (an array of characters, character array 2 ): 2 to 1 behind the

  • stdio.h header file function
    sscanf / sprintf
    can be regarded as Scanf + String / + Sring the printf
    sscanf (character array 1, "format", character string & 2); an array of characters to write the contents of the address 2 is located;
    sprintf (character array 1, "format", character string 2); 2 writes the string 1 the string array;

Example:

#include "stdafx.h"
#include <cstdio>
#include<cstring>

int main()
{
	int n;
	char str[100] = "123";
	sscanf(str, "%d", &n);
	printf("%d\n", n);
	return 0;
}

Output: 123

int main()
{
	int n=123;
	char str[100];
	sprintf(str, "%d", n);
	printf("%s\n", str);
	return 0;
}

Output: 123;

printf sscanf and can input and output formats complex
example:
the contents of the character array str by: the format "% d% lf,% s " is written int variables n, double-type variable db, char array str2, and then they are combined in reverse order of str3

#include "stdafx.h"
#include <cstdio>
#include<cstring>

int main()
{
	int n;
	double db;
	char str1[100]="2019:3.14,hello",str2[100],str3[100];
	sscanf(str1, "%d:%lf,%s", &n, &db, str2);
	printf("n=%d,\ndb=%f,\nstr2=%s\n", n, db, str2);
	sprintf(str3, "%s:%lf,%d", str2, db, n);
	printf("str3=%s", str3);
	return 0;
}

Output:
n-= 2019,
DB = 3.140000,
str2 = Hello
Str3 = Hello: 3.140000,2019 Press any key to continue.

Practice
exercises 6-4 insertion order

There has been described a topic array row good sequence, it requires the input of a number, according to the law of the original sorted to insert it into the array.
Suppose the length of the array 10, the array number of the first nine (9 number which requires input from the keyboard, to input brought to meet a large input order) has been sorted in ascending.
Input from the keyboard and then an integer, the integer number 9 is inserted into this order in the front, so that the final number of 10 is still ordered from small to large.
Input of the first input line number 9 integers separated by spaces, the requirements in ascending order of input.
A second input line of integer
output 10 from small to large outputs this number, the number of each row.

#include <cstdio>
#include<cstring>

int main()
{
	int a[15],b;
	//scanf("%d %d %d %d %d %d %d %d %d",)
	for (int i = 0; i <= 8; i++)
	{
		scanf_s("%d",&a[i]);
	}
	getchar();
	scanf_s("%d", &b);
	for (int i = 0; i <= 8; i++)
	{
		if (a[i] > b)
		{
			for (int j = 8; j >=i; j--)
			{
				a[j + 1] = a[j];
			}
			a[i] = b;
			break;
		}
	}
	for (int i = 0; i <= 9; i++)
	{
		printf("%d\n", a[i]);
	}
	return 0;
}

Exercise 6-5 array elements Retrograde

Description Title of a length value of the integer array 10 in the reverse order to re-store.

Such as: the original sequence is 1,2,3,4,5,6,7,8,9,0, required to 0,9,8,7,6,5,4,3,2,1

Input 10 separated by spaces integer from the keyboard.

This output number 10 in the reverse order, each number per line.

#include <cstdio>
#include<cstring>

int main()
{
	int a[10],b[10];
	for (int i = 0; i <= 9; i++)
	{
		scanf_s("%d", &a[i]);
		b[9 - i] = a[i];
	}
	//getchar();
	for (int i = 0; i <= 9; i++)
	{
		printf("%d\n", b[i]);
	}
	return 0;
}

Exercise 6-6 Pascal's Triangle

Enter required following format Pascal's Triangle

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Up to 10 layers Output

Input contains only a positive integer n, the number of layers Pascal triangles to be output. Corresponding to the output to the input, output a corresponding number of layers of Pascal's triangle, an integer between each layer separated by a space

#include <cstdio>
#include<cstring>

int main()
{
	int a[10][10],n;
	scanf_s("%d", &n);
	a[0][0] = 1;
	printf("%d\n", a[0][0]);
	for (int i = 2; i <= n; i++)
	{
		for(int j=1;j<=i;j++)
			if (j == 1 )
			{
				a[i - 1][j - 1] = 1;
				printf("%d ", a[i - 1][j - 1]);
			}
			else if (j == i)
			{
				a[i - 1][j - 1] = 1;
				printf("%d\n", a[i - 1][ j - 1]);
			}
			else
			{
				a[i - 1][ j - 1] = a[i - 2][ j - 2] + a[i - 2][ j - 1];
				printf("%d ", a[i - 1][j - 1]);
			}
		
	}
	return 0;
}

Exercise 6-12 decryption

Title Description one line message has been enciphered by the following rules:

A–>Z a–>z

B–>Y b–>y

C–>X c–>x

… …

I.e., becomes the first letter of the alphabet 26, the i-th letter becomes the (26-i + 1) th letter, non-letter characters unchanged. According to the password required translation back to the original text, and output.

After the text input line outputs the decrypted ciphertext, a separate line.

#include <cstdio>
#include<cstring>

int main()
{
	char str[100],str1[100];
	scanf_s("%s", str,100);
	int n;
	n = strlen(str);
	for (int i = 0; i <= n; i++)
	{
		if (str[i] >= 65 && str[i] <= 90)
			str1[i] =26- (str[i] -65)+64;
		else if (str[i] >= 97 && str[i] <= 122)
			str1[i] = 26 - (str[i] - 97)+96;
		else
			str1[i] = str[i];
		printf("%c", str1[i]);
	}
	return 0;
}

Exercise 6-13 string comparison

Title Description Compares two strings s1 and s2 of the size, if s1> s2, outputs a positive number; if s1 = s2, and outputs 0; if s1 <s2, a negative output.

Requirements: not strcpy function; two string gets function reads.

For example: "A" as compared with "C", because "A" < "C", the output should be negative, and because the "A" and "C" of the ASCII code difference is 2, the output should be "-2."

Similarly: "And" and the "Aid" comparison, the results of comparison of the second character, "n" ratio "i" is five, and therefore should output "5"

2 lines of character strings input

Output an integer, which represents the difference of the two string comparison, a separate line.

#include <cstdio>
#include<cstring>

int main()
{
	char str1[100], str2[100];
	gets_s(str1);
	gets_s(str2);
	int n = strlen(str1),output;
	for (int i = 0; i <= n; i++)
	{
		if (str1[i] != str2[i])
		{
			output = str1[i] - str2[i];
			printf("%d", output);
		}
	}
	return 0;
} 

Examples 6-1 reverse output array element

Description Title 10 integer input from the keyboard, stored in an integer array of length 10, it is required to reverse 10 the number of the input output.

The input is: 0,1,2,3,4,5,6,7,8,9 output 9,8,7,6,5,4,3,2,1,0
input integer 10 to input output space delimited integers reverse outputs 10, one row for each number.

#include <cstdio>
#include<cstring>


int main()
{
	int a[10], b[10];
	for (int i = 0; i <= 9; i++)
	{
		scanf_s("%d", &a[i]);
		b[9 - i] = a[i];
	}
	//getchar();
	for (int i = 0; i <= 9; i++)
	{
		printf("%d\n", b[i]);
	}
	return 0;
}

Examples 6-2 array Fibonacci series problem solving

Title Description Features Fibonacci sequence: first and second number of 1,1. 3 from the first number, is outlined in front and two numbers. which is:

20 request output before the Fibonacci number.

Inputs Outputs 20 before the Fibonacci number, each number per line.

#include <cstdio>
#include<cstring>


int main()
{
	int a[20];
	a[0] = 1;
	a[1] = 1;
	printf("%d\n", a[0]);
	printf("%d\n", a[1]);
	for (int i = 2; i <= 19; i++)
	{
		a[i] = a[i - 1] + a[i - 2];
		printf("%d\n", a[i]);
	}
	return 0;
}

Bubble sort example 6-3

Description Title integer input from the keyboard 10, sorted (ascending) 10 by the number of these bubbling method. Input 10 separated by spaces integer output
sequentially outputted sorted ten integers, each number per line.

#include <cstdio>
#include<cstring>


int main()
{
	int a[10],b;
	for (int i = 0; i <= 9; i++)
	{
		scanf("%d", &a[i]);
	}
	for (int i = 0; i <= 8; i++)
	{
		for (int j = 0; j <= 8 - i; j++)
		{
			if (a[j] > a[j + 1])
			{
				b = a[j];
				a[j] = a[j + 1];
				a[j + 1] = b;
			}
		}
	}
	for (int i = 0; i <= 9; i++)
		printf("%d\n", a[i]);
	return 0;
}

Examples 6-4 matrix transpose

2 will be described in a title three rows of the matrix (two-dimensional array) interchanging rows and columns, the memory array further in three rows and two columns.

Requirements to integer data as an example to answer.

2 input data lines, each line three integers, separated by spaces. Matrix, output line after 3 interchanging rows, each row 2 data, separated by spaces.

#include <cstdio>
#include<cstring>


int main()
{
	int a[2][3],b[3][2];
	for (int i = 0; i <= 1; i++)
	{
		for (int j = 0; j <=2; j++)
		{
			scanf("%d", &a[i][j]);
			b[j][i] = a[i][j];
		}
	}
	for (int i = 0; i <= 2; i++)
	{
		for (int j = 0; j <= 1; j++)
		{
			if (j)	printf("%d\n", b[i][j]);
			else    printf("%d ", b[i][j]);
		}

	}
	return 0;
}

Selecting the maximum value string examples 6-9

3 Description Title string input from the keyboard, which is determined by the maximum.
3 input lines each are a string.

Output line, three input string greatest.

#include <cstdio>
#include<cstring>


int main()
{
	char str1[100], str2[100],str3[100],max[100];
	scanf("%s", str1);
	scanf("%s", str2);
	scanf("%s", str3);
	if (strcmp(str1, str2) <= 0)	sscanf(str2, "%s", max);
	else sscanf(str1, "%s", max);
	if(strcmp(max, str3) <= 0)	sscanf(str3, "%s", max);
	printf("%s", max);
	return 0;
}
Published 43 original articles · won praise 4 · Views 1225

Guess you like

Origin blog.csdn.net/weixin_42176221/article/details/99682341