Project 1: Calculation of Average and Total Score for Students

Project Requirements

Input the scores of three students, and calculate their total score and average score.

Project Analysis

  1. First, you must learn how to input scores and output the results.
  2. Second, you must perform the calculation of the total score and average score on the inputted scores.

Therefore, this project will be introduced in two tasks.

Task 1: Input and Output of Student Scores

I. Task Presentation

A class took an exam and the results need to be outputted as required.

II. Specific Implementation

From the program segment below, it can be analyzed that:

  1. First, you need to understand the structure of the C language.
  2. Second, you need to understand the running environment of the C language.
  3. Third, you need to know how to define variables, input, and output statements.
#include "stdio.h"
main()
{
    int x,y,z;              // Define three variables x, y, z
    printf("Please input the scores of three students");
    scanf("%d%d%d",&x,&y,&z); /* Input the scores of three students */
    printf("Output the scores of three students");
    printf("x=%d,y=%d,z=%d\n",x,y,z); // Output the values of the three variables x, y, z
}                       // End of function body
    

Program Execution Result:

C:\Documents and Setti...
Please input the scores of three students 87 88 91
Output the scores of three students x=87,y=88,z=91
    

Relevant Knowledge

(I) Structure of a C Program

#include "stdio.h"  // File Preprocessing
main()              // Main Function
{
    int x,y;        // Data Declaration Part
    x=1;            // Statement Part
    y=x+2;          // Statement Part
    printf("x=%d\ny=%d\n",x,y); // Statement Part
}
    

(II) C Program Running Environment and Method

Click on [File][New], and in the dialog box that appears, click on [File][C++Source File] with the mouse, then change the directory where the file is saved (if necessary), enter the file name, and click [OK].

Enter the program. After the program input is complete, click the **Build** button or press F7 to compile and link. If there are no errors, click the **Execute/Run** button or press Ctrl+F5.

(File -> New, selecting C++ Source File, and console output.)

(III) Data Types

Data types in C language can be divided into:

【Variables】

【Variable Definition and Initialization】

Data type VariableName [= InitialValue], VariableName2 = InitialValue2 ......];

Example:

int x=1,y=2,z=3;
float a=1.1,b=1.2,c=-0.1;
char ch1='A',ch2='*';
        

(IV) Formatted Output — printf() Function

General format of the printf() function:

printf("format string"[, output list]);

  1. Commonly used format strings include:
    1. Format specifiers:
      • %d Signed decimal integer.
      • %f Signed decimal floating-point format (default 6 decimal places).
(1) printf("I am a student\n"); // No output item (only outputting the string and a newline)
(2) printf("%d",1+2);          // Output the value of 1+2
(3) printf("a=%d b=%d\n",1,1+3); // Output the value of 1 and the value of 1+3
(4) printf("%d %f\n",1.212,5); Try it yourself!
        /* %d expects an integer, but receives a float (1.212). %f expects a float, but receives an int (5). */
    

【Example 1-3】Formatted Output.

#include "stdio.h"
main()
{
    int x=1,y=2,z=3;    /* Define three integer variables x, y, z, and initialize them to 1, 2, 3 */
    float a=1.1,b=2.3;
    char c1='A',c2='B'; /* Define two character variables c1, c2, and initialize them to 'A' and 'B' */

    printf("Output x,y,z values\n");  // Output "Output x,y,z values" followed by a newline
    printf("x=%d,y=%d,z=%d\n",x,y,z); // Output "x=1,y=2,z=3" followed by a newline

    printf("Output a,b values\n");
    printf("a=%f,b=%f\n",a,b);

    printf("Output c1,c2 values\n");
    printf("c1=%c,c2=%c\n",c1,c2);
}
    

Program Execution Result is:

Output x,y,z values
x=1,y=2,z=3
Output a.b values
a=1.100000,b=2.300000
Output c1.c2 values
c1=A,c2=B
    

(V) Formatted Input — scanf() Function

  1. The function of scanf() is to receive formatted input from the keyboard.
  2. Example formats: (Guess and try!!!)

    scanf("%d,%d",&a,&b); vs scanf("%d %d",&a,&b); vs scanf("%d%d",&a,&b);

Whitespace characters (also known as ordinary characters) in the format string (e.g., space, newline, tab) will match any combination of whitespace characters in the input.

Non-whitespace characters in the format string (e.g., `,` or `:`) must be inputted exactly as they are in the format string when entering data.

Input Item Address List:

Consists of the starting addresses of several input items, separated by commas between adjacent item addresses.

The method to represent the starting address of a variable is: &VariableName

The "&" is the address operator. For example, in Example 1-1, "&x" in scanf("%d%d%d",&x,&y,&z) refers to the starting address of variable x in memory. Its function is to input three integers from the keyboard and store them starting at the memory units of &x, &y, &z, respectively, i.e., assign the three integers to x, y, and z.

[Example 1-4] Two people, A and B, scored 87 and 76 in a math exam. Please input the codename and scores of A and B, and output the scores.

Analysis: This problem requires inputting and outputting both integer scores (%d) and character codes (%c). When using scanf to read characters after a number, any non-whitespace separator in the format string (e.g., :) must be matched in the input.

#include "stdio.h"
main()
{
    char c1,c2;
    int x,y;

    printf("Please input A's score and codename (e.g., 87:A): ");
    scanf("%d:%c",&x,&c1);

    printf("Please input B's score and codename (e.g., 76:B): ");
    scanf("%d:%c",&y,&c2);

    printf("Output A's code and score: \n");
    printf("%c:%d\n",c1,x);

    printf("Output B's code and score: \n");
    printf("%c:%d\n",c2,y);
}
    

Program Execution Result:

Please input A's score and code: 87:A
Please input B's score and code: 76:B
Output A's code and score:
A:87
Output B's code and score:
B:76
    

Knowledge Expansion

1. Escape Characters

The escape character "\n" has been mentioned, which is a newline.

Another common escape character is "\t", which horizontally tabs to the next output field.

【Example 1-5】Using escape characters to control output effect.

#include "stdio.h"
main()
{
    printf("%d\t%d\t%d\n",1,2,3);
}
    

Program Execution Result is shown in the figure:

1       2       3
    

2. Formatted Output (Advanced)

Previously, we learned the general format of the output statement: printf("format string"[, output list]);

Commonly used format string representations are as follows:

【Example 1-6】Use of the Type Conversion Character 'd'.

#include 
main()
{
    int a=123;
    long b=123456;

    /* Output value of int type data 'a' using four different formats */
    printf("a=%d,a=%5d,a=%-5d,a=%2d\n",a,a,a,a);

    /* Output value of long type data 'b' using four different formats */
    printf("b=%ld,b=%8ld,b=%-8ld,b=%2ld\n",b,b,b,b);

    printf("a=%ld\n",a); // Output int type data 'a' using %ld
    printf("b=%d\n",b); // Output long type data 'b' using %d
}
    

Program Execution Result:

a=123,a=  123,a=123  ,a=123
b=123456,b=  123456,b=123456  ,b=123456
a=123
b=123456
    

Analysis of Example 1-6

【Example 1-7】Use of the Type Conversion Character 'f'.

#include "stdio.h"
main()
{
    float f=123.456;
    double d1,d2;
    d1=111111.11111111;
    d2=222222.22222222;

    printf("f=%f,f=%12f,f=%12.2f,f=%-12.2f,f=%.0f,f=%.2f\n",f,f,f,f,f,f);
    printf("d1+d2=%f\n",d1+d2);
}
    

Analysis:

3. Single Character Input and Output

(1) Single Character Output — putchar() Function

【Example 1-8】Format and usage of the putchar() function.

#include "stdio.h"
main()
{
    char ch1,ch2,ch3;
    ch1='S';
    ch2='u';
    ch3='n';

    putchar(ch1); putchar(ch2);  // Output ch1, ch2 values
    putchar(ch3); putchar('\n'); // Output ch3 value and newline

    putchar(ch1); putchar('\n'); // Output ch1 value and newline

    putchar('u'); putchar('\n'); // Output character 'u' and newline

    putchar(ch3); putchar('\n'); // Output ch3 value and newline
}
    

Program Execution Result:

Sun
S
u
n
    

Note: The putchar() function can only be used for outputting a single character, and can only output one character at a time. From a functional perspective, the printf() function can completely replace putchar(); using putchar() also requires the preprocessor command #include "stdio.h" at the beginning of the program.

(2) Single Character Input — getchar() Function

【Example 1-9】Format and usage of the getchar() function.

#include "stdio.h"
main()
{
    char ch;

    printf("Please input a character: ");
    ch=getchar();           // Input a character from the keyboard and assign it to variable ch

    putchar(ch);putchar('\n');  // Output the value of ch and a newline

    putchar(getchar());     // Input a character from the keyboard and output it
    putchar('\n');
}
    

Format of getchar(): getchar();

Function of getchar(): Inputs a single character from the keyboard. From a functional perspective, the scanf() function can completely replace getchar().

Note: The getchar() function can only be used for single character input, and can only input one character at a time. Similarly, using getchar() also requires the preprocessor command #include "stdio.h" at the beginning of the program.

4. String Constants

A string constant is a sequence of characters enclosed in double quotes. For example, "How do you do." is a string constant. In the C language, the system automatically appends a null character '\0' at the end of every string constant as a marker for the end of the string.

Please note the difference between a character constant and a string constant. For instance, 'a' is a character constant, occupying one byte in memory; while "a" is a string constant, occupying two bytes of storage space, one of which is used to store '\0'. Two consecutive double quotes "" is also a string constant, called the "null string," but it still occupies one byte of storage space for '\0'.

Note:

  1. The string terminator '\0' occupies memory space but is not counted in string length testing, nor is it outputted.
  2. The string terminator '\0' is a byte with value 0 used to mark the end of C-style strings (many library functions such as printf("%s") and strlen() stop at the first \0). Note that the compiler automatically appends a terminating '\0' byte to each string literal.
  3. Octal escapes: a backslash \ followed by 1 to 3 octal digits (0–7) is interpreted as a single byte. For example, "\067" denotes octal 67 (decimal 55, the character '7'), so the literal "abc\067de" actually represents "abc7de" — six visible characters plus the compiler-added terminator \0. By contrast, "\0" alone denotes the zero byte (the null character).
  4. Because octal escapes can include multiple digits, be careful: "\01" or "\007" are parsed as octal 1 and octal 7, not as the two characters '\' and '0'. To avoid ambiguity, you can use hexadecimal escapes like "\xhh" (for example "\x30") or split the string into separate parts.
  5. Examples to illustrate:
    • "abc\067de" → stored bytes: 'a','b','c','7','d','e','\0' ; strlen returns 6, sizeof returns 7.
    • "abc\0de" → stored bytes: 'a','b','c',0,'d','e','\0' ; strlen returns 3 (stops at the embedded \0), sizeof returns 7 (includes all bytes plus the literal terminator).

【Example 1-10】Which of the following data is a string constant?

(A) 'A'      (B) "house"      (C) How do you do      (D) $asd

Analysis: A string constant is a sequence of characters enclosed in a pair of double quotes. The answer is ??

Practice Exercise

【Example 1-10】If the variables are of type float, and you use the statement scanf("%f%f%f", &a, &b, &c); to assign 10.0 to a, 22.0 to b, and 33.0 to c, which of the following four answers (A, B, C, D) is incorrect?

Please write a complete C program to make the execution result as follows:

A. 10<Enter> 22<Enter> 33

B. 10.0,22.0,33.0<Enter>

C. 10.0<Enter> 22.0 33.0<Enter>

D. 10 22<Enter> 33<Enter>

Complete Program:

#include "stdio.h"
main()
{
    float a,b,c;
    scanf("%f%f%f", &a, &b, &c);
    printf("a=%.1f,b=%.1f,c=%.1f\n", a, b, c);
}
        

Analysis:

  1. The statement scanf("%f%f%f", &a, &b, &c) requires the numbers to be separated by either a space or a newline when entering the data. Therefore, answers A, C, and D are all correct, and only B is incorrect. If the input data format were 10.0,22.0,33.0<Enter>, the input statement should be written as: scanf("%f,%f,%f", &a, &b, &c);.
  2. Since the values of a, b, c are real numbers (float), the variable definition is correct, and the output statement must ensure one decimal place is preserved (%.1f).
Show Answer

Answer: B.

Practice Exercise

【Example 1-11】What is the reason why the input function scanf(“%d”,k) cannot correctly obtain a value for the float type variable k?

Show Answer

Analysis: Since k is a real type variable, the format string should be “%f”, and the address operator & is missing before the variable.

Correct Answer Format: scanf("%f",&k);

【Example 1-12】Read the following program. If the input data format is: 12,34, what is the correct output result ( )?

#include "stdio.h"
main()
{
    int a,b;
    scanf("%d%d", &a,&b);
    printf("a+b=%d\n",a+b);
}
    

A. a+b=46      B. Syntax Error      C. a+b=12      D. Undefined Value

Show Answer

Analysis: The input statement scanf("%d%d", &a,&b) requires the two input numbers to be separated by a space or a newline. However, the problem specifies the two numbers are separated by a comma. This causes the value of b to be an undefined value. Therefore, the result is undefined.

Answer: D.

Practice Exercise

【Example 1-13】Given the following program, if the required values for x1, x2, y1, y2 are 10, 20, A, B, respectively, what is the correct data input? Please complete the program by adding printf() statements after the given program segment.

// Reference Program:
#include "stdio.h"
main()
{
    int x1, x2;
    char y1, y2;
    scanf("%d%d", &x1,&x2);
    scanf("%c%c", &y1,&y2);
    printf("x1=%d,x2=%d\n", x1,x2);
    printf("y1=%c,y2=%c\n", y1,y2);
}
    
Answer

10 20AB — that is, a space between the two integers, then immediately the characters A and B with no intervening whitespace.

Behavior of the original code:

  • scanf("%d%d", &x1,&x2) reads two integers and leave out whitespace character.
  • scanf("%c%c", &y1,&y2) reads the next two characters exactly — it does not skip whitespace. Therefore any space or newline remaining in the buffer becomes y1.

Task 2: Calculation of Total Score and Average Score

I. Task Presentation

A class took an exam. Now, the scores of several students need to be inputted into the computer, their average and total scores calculated, and then outputted as required.

II. Specific Implementation

First, arithmetic operations and arithmetic expressions;

Second, assignment operations and assignment expressions;

Additionally, it is necessary to master C language's unique operations and operators that are not demonstrated in this task but are often used in C programs.

#include "stdio.h"
main()
{
    int x,y,z;
    float sum,avg;      // Define float variables sum and avg

    printf("Please input the scores of three students: ");
    scanf("%d%d%d",&x,&y,&z); /* Input */

    sum=x+y+z;          // Assign the value of x+y+z to a variable sum
    avg=sum/3;          // Assign the value of sum/3 to variable avg

    printf("Please output the total score and average score of the three students: ");
    printf("sum=%.2f,avg=%.2f\n",sum,avg); // Output sum and avg values (2 decimal places)
}
    

Program Execution Result:

Please input the scores of three students 78 81 93
Please output the total score and average score of the three students sum=252.00,avg=84.00
    

III. Relevant Knowledge

(I) Arithmetic Operations and Arithmetic Expressions

1. Five Basic Arithmetic Operators

+ (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulo/Remainder)

Here, it is necessary to specifically mention:

(1) Regarding the Division Operation /

(2) Regarding the Modulo/Remainder Operation %

(I) Arithmetic Operations and Arithmetic Expressions

2. Expressions and Arithmetic Expressions

(1) Concept of an Expression

A sequence of operands (constants, variables, and functions) connected by operators and parentheses, conforming to the C language syntax rules, is called an expression.

A single constant or variable can be regarded as a special case of an expression. Expressions consisting of single constants or variables are called simple expressions; others are called complex expressions.

(2) Concept of an Arithmetic Expression

The operators in the expression are all arithmetic operators. Examples: 3+2*5, (x+y)/2+3, 5%2+3 are all arithmetic expressions.

3. Operator Precedence and Associativity

(1) The precedence of arithmetic operators is: first *, /, %, then +, -.

(2) Operations within parentheses are performed first.

(I) Arithmetic Operations and Arithmetic Expressions

4. Data Type Conversion

High    double ← float
        ↑
        long
        ↑
        unsigned
        ↑
Low     int ← char,short
    

Example:

(II) Assignment Operations and Assignment Expressions

1. Assignment Operation

The assignment symbol "=" is the assignment operator, and its function is to assign the value of an expression to a variable.

The general form of the assignment operator is: Variable = Assignment_Expression

Examples of incorrect usage:

2. Compound Assignment Operations

x+=3      is equivalent to x=x+3
x+=5+8    is equivalent to x=x+(5+8)
x*=y+2    is equivalent to x=x*(y+2)
x/=x+y    is equivalent to x=x/(x+y)
x/=8      is equivalent to x=x/8
x%=7      is equivalent to x=x%7
x%=(4-2)  is equivalent to x=x%(4-2)
    

【Example 1-16】Read the following program.

#include "stdio.h"
main()
{
    int x,y,z;
    float a,b,c; // Define three single-precision float variables a,b,c

    x=1; // Assign 1 to variable x, so x's value is 1
    y=2;
    z=3;

    a=1.1; // Assign 1.1 to variable a, so a's value is 1.1
    b=2.1;
    c=3.5;

    x=x+y+z; // Assign x+y+z value to variable x. x = (1+2+3), so x=6
    printf("x=%d\n",x);

    y*=y+1; // Assign y*(y+1) to y. y = 2*(2+1), so y=6
    printf("y=%d\n",y);

    z=(int)a%(int)b; // z=1%2, so z=1
    printf("z=%d\n",z);

    a+=a+b+c; // a=a+(a+b+c). a = 1.1+(1.1+2.1+3.5), so a=9.9
    printf("a=%f\n",a);
}
    

Program Execution Result:

x=6
y=6
z=1
a=9.900000
    

(III) C Language Unique Operations and Operators

1. Increment (++) and Decrement (--) Operations

Function: The increment operation increases the value of a single variable by 1; the decrement operation decreases it by 1.

Usage and Rules:

Increment and decrement operators have two forms of usage:

1) Prefix Operation: The operator is placed before the variable: ++x or --x.

First, the variable's value is incremented (or decremented) by 1, and then the changed value participates in the subsequent expression calculation.

#include "stdio.h"
main()
{
    int x=2,y,z;
    printf("x=%d\n",x); // Output: x=2

    y=++x; // x is incremented first (x=3), then assigned to y (y=3)
    printf("x=%d y=%d\n",x,y); // Output: x=3 y=3

    ++x; // x is incremented (x=4)
    printf("x=%d\n",x); // Output: x=4

    y=++x+2; // x is incremented first (x=5), then x+2 (5+2=7), then assigned to y (y=7)
    printf("x=%d y=%d\n",x,y); // Output: x=5 y=7

    z=--x; // x is decremented first (x=4), then assigned to z (z=4)
    printf("x=%d z=%d\n",x,z); // Output: x=4 z=4

    --x; // x is decremented (x=3)
    printf("x=%d\n",x); // Output: x=3
}
    

Postfix Operation — Variable++ and Variable--

Note: The increment and decrement operators cannot be used with constants or expressions.

Example: 5++, --8, ++(a+b) are all incorrect.

2) Postfix Operation: The operator is placed after the variable: x++ or x--.

First, the variable's *original value* participates in the expression calculation, and then the variable's value is incremented (or decremented) by 1.

#include "stdio.h"
main()
{
    int x=2,y,z;
    printf("x=%d\n",x); // Output: x=2

    y=x++; // x's original value (2) is assigned to y, then x is incremented (x=3)
    printf("x=%d y=%d\n",x,y); // Output: x=3 y=2

    x++; // x is incremented (x=4)
    printf("x=%d\n",x); // Output: x=4

    y=(x++)+2; // x's original value (4) + 2 = 6 is assigned to y, then x is incremented (x=5)
    printf("x=%d y=%d\n",x,y); // Output: x=5 y=6

    z=x--; // x's original value (5) is assigned to z, then x is decremented (x=4)
    printf("x=%d z=%d\n",x,z); // Output: x=4 z=5

    x--; // x is decremented (x=3)
    printf("x=%d\n",x); // Output: x=3
}
    

Practice Exercise

【Example 1-19】Input the radius of a circle, and calculate its area and circumference. Use π = 3.14.

Analysis: Based on the radius, we need to calculate the area and circumference. Therefore, three variables need to be defined: radius (r), area (s), and circumference (c). Considering that the input radius might be a decimal, all three variables should be defined as float (single-precision floating-point type).

// C Code
#include "stdio.h"
main()
{
    float r,s,c;

    printf("Please input the radius of the circle r: ");
    scanf("%f",&r);

    s=3.14*r*r;
    c=2*3.14*r;

    printf("The area of the circle s is: %f\n",s);
    printf("The circumference of the circle c is: %f\n",c);
}
    

Program Execution Result (Input r: 1):

Please input the radius of the circle r: 1
The area of the circle s is: 3.140000
The circumference of the circle c is: 6.280000
    

Symbolic Constants

#define PI 3.14

This defines a symbolic constant PI with a value of 3.14. The naming rules for symbolic constants are the same as for variable names, but conventionally, symbolic constants are represented by uppercase letters.

#include "stdio.h"
#define PI 3.14 // Define a symbolic constant PI with a value of 3.14
main()
{
    float r,s,c;

    printf("Please input the radius of the circle r: ");
    scanf("%f",&r);

    s=PI*r*r;
    c=2*PI*r;

    printf("The area of the circle s is: %f\n",s);
    printf("The circumference of the circle c is: %f\n",c);
}
    

【Example 1-20】Input the lengths of the three sides of a triangle, and calculate its perimeter and area.

Analysis: Clearly, three variables a, b, c need to be defined for the side lengths, and two variables for the perimeter (cc) and area (s). The calculation of the area requires Heron's formula: s = sqrt(l*(l-a)*(l-b)*(l-c)), where l is the semi-perimeter. We also need to define a variable l for the semi-perimeter. The square root is calculated using the sqrt() function, which requires including the math.h header at the beginning of the program.

Answer
    #include "stdio.h"
    #include "math.h" // For the square root function sqrt()
    main()
    {
            int a,b,c;
            float cc,l,s; // cc for perimeter, l for semi-perimeter, s for area

            printf("Please input the lengths of the three sides a, b, c: ");
            scanf("%d%d%d",&a,&b,&c);

            cc = a + b + c;
            l  = cc / 2.0f; // use 2.0f to ensure float division

            s = sqrt(l * (l - a) * (l - b) * (l - c));

            printf("The perimeter of the triangle cc is: %f\n", cc);
            printf("The area of the triangle S is: %f\n", s);
    }
        

Program Execution Result (Input: 3 4 5):

Please input the lengths of the three sides a,b,c: 3 4 5
The perimeter of the triangle cc is: 12.000000
The area of the triangle S is: 6.000000
    

【Example 1-21】Find the real roots of the equation ax2 + bx + c = 0. Please input a, b, c from the keyboard, where a ≠ 0 and b2 - 4ac > 0.

Analysis: First, consider the variables to be defined: a, b, c, x1, x2, and the discriminant disc = b2 - 4*a*c. Then calculate the roots using the quadratic formula: x = (-b ± sqrt(disc)) / (2*a). Finally, output the results.

#include "stdio.h"
#include "math.h"
main()
{
    float a,b,c,disc,x1,x2;

    printf("Please input the coefficients a, b, c of the equation: ");
    scanf("%f%f%f",&a,&b,&c); // Input a, b, c

    disc=b*b-4*a*c;           // Calculate the discriminant and assign it to disc

    x1=(-b+sqrt(disc))/(2*a); // Calculate the roots
    x2=(-b-sqrt(disc))/(2*a);

    printf("The roots of the equation are x1=%f, x2=%f\n",x1,x2); // Output x1, x2 values
}
    

Program Execution Result (Input: 1 2 1):

Please input the coefficients a,b,c of the equation: 1 2 1
The roots of the equation are x1=-1.000000, x2=-1.000000
    

Computational Approximation for Quadratic Equations: Iterative Root Finding

Alternative Method: Instead of using the quadratic formula, we can use computational methods to approximate the roots of ax2 + bx + c = 0 by iteratively narrowing down the possible solution space. This method is especially useful when exact formulas are difficult to apply or when we want to demonstrate algorithmic thinking.

Numerical Approximation Approach

We'll use a simple incremental search method:

  1. Define a range of x values to test (e.g., from -1000 to 1000)
  2. For each x value, calculate f(x) = ax2 + bx + c
  3. Look for x values where f(x) is close to zero (within a small tolerance)
  4. The x values that produce f(x) ≈ 0 are approximate roots of the equation
#include "stdio.h"
#include "math.h"

main()
{
    float a, b, c;
    float x, fx, tolerance = 0.01;  // Tolerance for approximation
    float start = -100.0, end = 100.0, step = 0.001;  // Search parameters
    int found = 0;

    printf("Please input the coefficients a, b, c of the equation: ");
    scanf("%f%f%f", &a, &b, &c);

    printf("Searching for roots in range [%.1f, %.1f] with step %.3f\n", start, end, step);

    // Iterative search for roots
    for(x = start; x <= end; x += step) {
        fx = a*x*x + b*x + c;  // Calculate f(x) = ax^2 + bx + c

        if(fabs(fx) < tolerance) {  // Check if f(x) is close to 0
            printf("Approximate root found at x = %.3f, f(%.3f) = %.6f\n", x, x, fx);
            found = 1;
        }
    }

    if(!found) {
        printf("No roots found within the specified range and tolerance.\n");
        printf("Try adjusting the range or tolerance parameters.\n");
    }
}
    

Program Execution Result (For equation: x2 + 2x + 1 = 0):

Please input the coefficients a, b, c of the equation: 1 2 1
Searching for roots in range [-100.0, 100.0] with step 0.001
Approximate root found at x = -1.000, f(-1.000) = 0.000000
    

Note: This iterative method is computationally more intensive than the quadratic formula but demonstrates an important computational thinking approach. In practice, more sophisticated methods like Newton-Raphson are used for faster convergence.

【Example 1-22】Input a lowercase letter from the keyboard, and output the letter in uppercase form and its corresponding ASCII code.

Analysis: Since a lowercase letter is to be inputted and converted to an uppercase letter, two character variables need to be defined. The conversion formula between lowercase and uppercase letters is: lowercase_letter = uppercase_letter + 32 (based on ASCII values). Thus, uppercase_letter = lowercase_letter - 32. Finally, output the results.

#include "stdio.h"
main()
{
    char c1,c2; // Define two character variables c1, c2

    printf("Please input a lowercase letter: ");
    scanf("%c",&c1); // Input the lowercase letter

    c2=c1-32; // Calculate the corresponding uppercase letter

    // Output the original letter and its corresponding uppercase letter and ASCII value
    printf("Original letter is %c, Uppercase letter is %c\n",c1,c2);
    // To output the ASCII code, cast the char to an int with %d format specifier
    printf("ASCII code of %c is %d, ASCII code of %c is %d\n", c1, c1, c2, c2);
}
    

Program Execution Result (Input: a):

Please input a lowercase letter: a
Original letter is a, Uppercase letter is A
ASCII code of a is 97, ASCII code of A is 65