Code

C Language from Scratch — Lecture 1.2 of the CS50 course

C Language from Scratch — Lecture 1.2 of the CS50 course

Free Course: "Quick Start in Python"

Learn More

CS50 (Computer Science 50) is a renowned computer science course from Harvard and Yale Universities, considered one of the best resources for learning the basics of programming. Experienced developers recommend this course as the ideal introduction to programming. It covers key topics such as computer logic, algorithm fundamentals, programming in the Scratch visual environment, and working with arrays and memory. Students learn data structures and the fundamentals of programming languages, including C, Python, SQL, HTML, CSS, and JavaScript. The course also covers the Flask framework and many other important concepts, making it a versatile tool for beginners and those looking to expand their IT knowledge. CS50 is a course that provides a deep understanding of how computers work, covering aspects such as the processor and RAM. By the end of the course, you'll have mastered universal programming principles applicable to various languages, as well as learned how to interpret and analyze code written in different programming languages. This course will serve as a foundation for your further education and development in IT. We've published several articles based on the lessons in CS50. These materials will help you better understand the fundamentals of computer science and programming, and master the key concepts presented in the course. If you want to deepen your knowledge and skills, we recommend checking out our articles, which cover various topics and practical tasks from the CS50 course.

  • Fundamentals of Computer Science. Lecture 0.1
  • Programming in Scratch. Lecture 0.2
  • Getting Started with the C Programming Language. Lecture 1.1

First Steps in C Programming. Lecture 1.2. You are in the section dedicated to the basics of writing programs in C. In this lecture, we will cover the key concepts and syntax of the language that will help you create your first programs. After studying this information, you will be able to confidently begin your journey in programming and software development in C.

Why we translated CS50 and how each article in the course is organized

CS50 is the most popular course at Harvard University and is one of the leading massive open online courses on the edX platform. All course materials, including practical exercises, are provided free of charge. Students have the opportunity to purchase a certificate and additional benefits by paying for the course. CS50 covers the fundamentals of computer science and programming, making it an ideal choice for beginners and those looking to deepen their knowledge in this field.

We converted the video lectures into text format, added illustrations, and expanded some explanations. These materials are now available in the public domain. The original course is licensed under the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license. This means you can modify and redistribute it free of charge, provided you comply with the original license. Thus, you can use this series of materials in your work or public activities absolutely freely and at no additional cost, as long as you follow the license terms.

Each article from the CS50 series includes the following materials:

  • text translation of the video (sometimes half of the video, if the topic is extensive);
  • link to the original video in English;
  • diagrams and explanations;
  • links to more detailed materials on the topic of the article;
  • practical tasks.

Lectures are given by an experienced teacher with deep knowledge in his field. He shares his knowledge and experience, providing students with the opportunity to deepen their understanding of the topic. Each lesson is rich in useful information, which contributes to the development of critical thinking and analytical skills in students. Attending lectures will allow you not only to master theoretical aspects but also to apply them in practice. Participants have the opportunity to ask questions and participate in discussions, making the learning process interactive and engaging.

This American scientist and Harvard University professor is an authority in his field. His research and publications significantly influence the development of science and education. Given his academic degree and experience, the professor actively participates in international conferences, sharing his knowledge and achievements. Harvard University, as one of the world's leading educational institutions, provides a platform for the exchange of ideas and innovations, which strengthens its reputation in the academic community.

This lesson covers key topics and aspects that will be covered in detail. We will explore key concepts, methods, and practical examples to ensure a thorough understanding of the material. Each topic will be illustrated with illustrative examples to help reinforce the knowledge gained. This lesson is designed to develop the skills and competencies needed to successfully complete tasks in this area.

  • Code Writing in C and Creating a Calculator
  • Code Style
  • Integer Overflow
  • Conditional Statements
  • While Loops
  • For Loops
  • Creating Custom Functions
  • Creating a Game in C
  • Floating-Point Overflow
  • Data Type Conversion
  • Revisiting Overflow in Real Life

Code Writing in C and Creating a Calculator

In the previous lesson, we covered the syntax and key concepts of the C programming language. Now we will move on to practical exercises and look at how to write programs in this language. Open Visual Studio Code and create a file named calculator.c using the command line.

It will automatically open in the development environment. We'll start by including the cs50.h and stdio.h libraries. These libraries provide the necessary functions for working with user input and standard input/output, which is an important step in developing C programs. By including them, you'll be able to use functions that simplify data processing and user interaction.

We'll create a simple calculator using the operators we learned in the previous lesson. This calculator will allow you to perform basic arithmetic operations such as addition, subtraction, multiplication, and division. We'll focus on creating an intuitive interface and providing functionality that will allow users to easily perform calculations. As we develop the calculator, we'll also explore how to use JavaScript to process user input and display results. In this way, we will not only create a useful tool but also consolidate our knowledge of working with arithmetic operations in programming.

To perform the addition operation, we will create variables x and y, and then print the result of their sum, that is, x + y. This is a basic operation used in programming to process numerical data. Proper declaration and use of variables allows you to effectively manage information and perform various calculations. In this case, we will focus on a simple example demonstrating how to add the values ​​​​of variables and print the final result.

The printf() function in the C programming language accepts a format string as its first argument, for example, «%i\n», which specifies the data display format. The second argument is the expression whose value will be displayed on the screen. This function allows flexible control over the output of information, providing the ability to format numbers, strings, and other data types. Using printf() is an important aspect of program development, as it allows users to obtain data in a readable form.

We've created a simple calculator that can add two numbers. After compiling, the program produces no errors. Let's launch the calculator and perform the addition operation 1 + 1.

Frame: CS50 / YouTube

Everything functions correctly.

We will make changes to the calculator code, adding a new variable z. This will expand the functionality of our calculator and improve its performance. Updating the code will make the calculation more flexible and efficient, which will increase user satisfaction. Correct use of the z variable will help in performing more complex mathematical operations and provide more accurate results.

By running the calculator and performing the operation 1 + 1, we will get the same result, which will be relevant for any other values ​​of the variables x and y. Using the z variable in the code is justified in those situations when it is necessary to save the result of addition for further calculations or reuse. This approach allows you to improve the structure of the code and increase its efficiency.

Code Style

Now let's consider the code writing style. The names of the x and y variables are appropriate in this example, as they are often used in mathematics. However, to improve the readability of the code, it is advisable to use more descriptive names, such as first_number and second_number. This will make the code more understandable for other developers and simplify its future maintenance. Correct variable naming is an important aspect of high-quality programming, promoting better code comprehension and facilitating its analysis.

Now let's add comments to the program. They will be useful for reminding us of the code's functionality when we return to it and forget something. Comment lines begin with two slashes. Comments are an important element in programming, as they make the code easier to understand both for the author and for other developers who may work with this code in the future. Using comments helps to better structure the program and simplifies the debugging process.

Comments do not affect the functionality of the program - they serve only for the convenience of developers. In small projects, their role may be insignificant, but as the code size increases, comments become important, helping to maintain an understanding of the program's structure and logic. They help you remember what task a particular section of code performs, which is especially important when working in a team or when returning to a project after a while. Proper use of comments improves code readability and makes it easier to maintain.

Tip: Most operating systems, including Linux, Windows, and macOS, support code completion. Using the up arrow key, you can view the command history and quickly select the desired command, instead of entering the same command repeatedly. This significantly improves efficiency and saves the developer time.

Integer Overflow

Now it's time to work with large numbers. Consider, for example, the numbers x and y equal 1,000,000,000. Let's enter these values ​​into the command line and analyze the output. Working with large numbers can be useful in various calculations and data analysis, so it is important to understand how they are handled in programming and what results can be obtained.

Frame: CS50 / YouTube

Everything worked out as expected That's what we planned.

Let the variables x and y be equal to 2,000,000,000. This value can be used in various calculations and models where high accuracy and a wide range are important. For example, in financial calculations, statistical analysis, or in tasks related to big data, such values ​​can be critical. Processing and analyzing data with such quantities requires the use of efficient algorithms and optimized approaches to avoid errors and delays in calculations.

Frame: CS50 / YouTube

It looks like an error occurred... A data overflow has occurred!

Testing the addition of two 1s proved unreliable. In the last example, the computer ran out of space to store bits. This problem occurs with various data types, such as string, int, float, and char, as they all use a limited number of bits to represent numbers and characters. Therefore, it is important to consider the limitations of data types when developing software to avoid errors and ensure the stability of applications.

Integers are stored using 32 bits, which allows values ​​in the range of -2³¹ to 2³¹-1 to be represented, or approximately -2,147,483,648 to 2,147,483,647. This allows for the storage of integers up to 4 billion. At first glance, this may seem sufficient for most tasks. However, some applications, such as big data processing or working with large numbers, may require more storage. In such cases, it is worth considering using 64-bit integers, which provide a significantly larger range of values.

Two billion plus two billion equals four billion. This simple mathematical operation demonstrates the basic principles of arithmetic and can be useful in a variety of fields, including finance and economics. Understanding the addition of large numbers is important for data analysis and making informed decisions.

Computers are capable of handling both positive and negative numbers. This means that they store values ​​in the range from -2,000,000,000 to 2,000,000,000. Because of this range, we may encounter unexpected results when performing addition operations.

To solve the overflow problem, you must use the long data type. In the program, you should change the type of the x and y variables from int to long, which will avoid the limitations associated with the size of integers. This change will ensure the program operates correctly when handling large values ​​and prevents possible overflow errors.

Launch the calculator to perform the necessary calculations. This tool allows you to quickly and accurately perform mathematical operations. Using the calculator, you can easily solve problems related to arithmetic, algebra, and other areas of mathematics. It will become an indispensable assistant for both students and professionals, providing a user-friendly interface and instant results. Make sure you use a calculator to increase your productivity in your studies or work.

Frame: CS50 / YouTube

Now everything worked out!

Using the long data type, we all are equally limited by the finite values ​​of numbers. This can create problems when designing a calculator that must process any input data. We will definitely return to this topic later for a more detailed discussion.

Adding two numbers, 2,000,000,000 and 2,000,000,000, results in 4,000,000,000. This process demonstrates a fundamental arithmetic operation—addition, which is key to mathematics. Adding large numbers is important in various fields, such as economics, finance, and statistics. For example, understanding the sum of numbers allows you to better analyze data and make informed decisions. Addition can be applied in budgeting, investment planning, and other financial tasks.

Conditional Statements

In this section, we will look at conditional statements in the C programming language. Conditional statements allow you to perform certain actions depending on the truth or falsity of a specified condition. In C, conditional statements are written using comparison operators and logical operators. The basic constructs used to work with conditions include the if statement, the else statement, and the switch statement. Each of these statements plays a key role in controlling the flow of a program, allowing the developer to implement decision-making logic. Conditional statements are an important part of C programming and help create more flexible and adaptive applications.

Let's add an else block to specify what actions should be performed if the condition is not met. The else block allows you to specify an alternative scenario, which makes the code more understandable and structured. This improves the readability and control of program logic, allowing developers to easily trace possible code execution paths. Including the else block makes the code more resilient to errors and helps avoid unexpected situations during program execution.

The C programming language has unique syntax features. Parentheses are used both to declare functions and to form logical expressions. In addition, the use of curly braces is optional if they contain only one line of code with appropriate indentation. However, I strongly recommend always using curly braces, as this significantly improves the readability and structure of the code. Clear organization of code promotes its better perception and facilitates subsequent maintenance.

If you need to describe a situation in which x is equal to y, the code will look like this:

The last condition can be excluded, since if the first two conditions are not met, the value of x can only be equal to the value of y.

Code optimization is an important part of web application development. Proper optimization improves performance, reduces page load times, and increases overall website performance. Key optimization techniques include minifying HTML, CSS, and JavaScript, removing unused code, and compressing files. Caching and image optimization are also important factors to consider, as they also contribute to faster loading times. Clean and optimized code not only benefits users but also search engines, which impacts a website's SEO ranking. Regularly checking and updating your code is essential to keep it current and effective. By removing the third condition, we reduce program execution time because there is no need to check this condition. It's important to remember that when writing code, you should consider not only its correctness but also its performance. Code optimization can improve program performance and reduce resource consumption, which is especially important when developing complex systems. Let's consider an important task: finding out how many points a user lost while completing the first set of problems in the CS50 course. Personally, I lost several points in 1996. Now let's compare the user's results with my losses.

We now understand how to use conditional expressions, but the code remains redundant. I've hard-coded the value 2—the number of points lost. If I need to change this number to 3, it's easy, but if the number of points is compared in several places in the code, for example, in two, three, or five, then we could make a mistake when replacing them. Therefore, it's important to avoid hard-coding numbers and use constants or variables to improve the readability and maintainability of the code. This approach will simplify changes and minimize the risk of errors.

To simplify working with numbers in a program, it is recommended to create a variable at the very beginning that will store this value. To avoid accidentally changing this variable during code execution, we declare it as a constant. A constant informs the compiler that the value of this variable cannot be changed in the future. This solution promotes better code organization and prevents potential errors related to changing values.

In programming languages ​​such as C, there is an important rule: constant names should be written in capital letters. This rule improves the readability of the code and helps developers quickly identify constant values. Using capital letters for constants is a common practice, which also promotes consistency in the code. Following this rule makes the code more understandable and easier to maintain.

Let's create a program to check whether the number entered by the user is even or odd. We will use the syntax and methods we have already mastered. This program will help users determine which category the number entered belongs to, which is a useful task in programming.

According to mathematical definitions, a number is considered even if, when divided by two, the remainder is zero. An odd number, in turn, gives a remainder of one when divided by two. To calculate the remainder of a division, you can use the % operator. This operator allows you to determine the remainder that remains after dividing one number by another. For example, by using the % operator with a number and a divisor of two, you can easily determine whether the number is even or odd.

In the C programming language, the «==» sign denotes equality, while the «=» sign is used for value assignment. This distinction may seem unusual, but it has been established for a long time, and developers need to keep this rule in mind when writing code. Other languages, such as JavaScript, use the «===» operator for strict comparison, which is also worth keeping in mind when switching between programming languages. Understanding these differences will help you avoid mistakes and improve the quality of your code.

Now let's develop a program that asks the user to agree with a certain statement. The user must respond with a single character, for example, ‘y’ for «yes» or ‘n’ for «no». All other characters will be ignored.

The program looks like this:

If the user chooses to answer Y or N, we need to account for this in the code by adding a logical OR. In C, two vertical bars || are used to denote a logical OR. This way, we will be able to handle both answer options, which will make the program more flexible and robust to user input. This will allow the program to respond correctly to different answer options and improve user experience.

There is an alternative to this solution: converting input characters to lowercase can eliminate the need to use characters like ||. This approach will be discussed in future lectures.

In this example, we use single quotes to denote characters because we are working with the char data type. This is different from working with strings, which are denoted by double quotes and are of the string type. It is important to remember that char variables store only a single character, while strings can contain sequences of characters. Using correct quotation marks is critical for the correct operation of the program and its logic.

While Loops

In this section, we will look at how to organize loops in the C language. Recall that in the previous lesson we learned how to make a cat meow. Now we will create a program that demonstrates the use of loops in C. Loops allow you to repeat certain actions, which makes the code more efficient and understandable. Let's move on to writing a program that uses loops to solve the problem.

The current text contains repetitive elements that need to be eliminated. For this, we can use loops. One of the easiest ways to implement this is by using loops, which contributes to more efficient and structured code. Loops allow you to process data more compactly, avoiding duplication and improving readability. Optimizing code with loops not only simplifies logic but also improves program performance.

A logical expression that defines the loop execution condition is specified within parentheses. The loop will continue to run as long as this condition is true; as soon as it becomes false, the loop execution stops. If you want the loop to run indefinitely, you can use an always-true condition, for example (1 == 1) or (2 > 1). In the C programming language, the logical constants true and false are used to denote true and false values.

To ensure the correct operation of the loop, it is important to introduce a counter. In C and many other programming languages, it is common to use the variable i as a counter, starting with the initial value 0. This convention promotes better understanding of the code and makes it easier to read.

We have the opportunity to improve this program by using so-called syntactic sugar. This will make the code more readable and easier to work with, which in turn will increase developer productivity. Syntactic sugar doesn't add new functionality, but it significantly simplifies the process of writing and understanding code. Implementing such improvements can lead to more efficient use of resources and reduced development time.

The expression i = i + 1 was replaced with i = i++. Such changes don't affect the program's functionality, but they do allow for shorter and more compact code. It's important to remember that using shorthand can improve code readability, but requires careful consideration to avoid potential errors related to the specifics of the increment operator.

In this section, we'll examine the program's algorithm in detail. An algorithm is a sequence of steps a program performs to achieve a given goal. Each stage of the algorithm plays an important role in the overall process and influences the final result. We'll analyze the key elements of the algorithm, their interrelations, and optimal implementation methods. Understanding the algorithm will help users interact with the program more effectively and solve problems.

  • We start by initializing the variable i.
  • Then the computer checks the condition i < 3. If it is true, then everything inside the curly braces is executed, namely, the program prints meow.
  • The value of i is incremented by one.
  • Now the computer rechecks the condition to make sure i has not become greater than 3. If it has not, it executes everything inside the block.
  • After three repetitions, the condition will become false and the loop execution ends.
  • The computer moves on to the commands following the loop.

You can start the loop not from 0, but, for example, from 1. In this case, in order for the loop body to be executed three times, you need to change the loop condition. This will allow you to control the number of iterations and adapt the execution logic to your requirements. Properly setting the initial value and loop condition is an important aspect of programming that affects the efficiency and correctness of your code.

Please note the correct spelling of the "less than or equal to" sign: the "less than" sign comes first, followed by the "equal to" sign, with no spaces between them. The correct representation of this symbol looks like this: <=.

You can set the i variable to 2, 10, or any other number by changing the condition. However, it is preferable to follow the basic principles and start counting from zero and gradually increment the counter until the desired value is reached. This approach ensures better readability and understanding of the code.

If you plan to count down, start by setting i to 3. Decrease this value until it reaches 0. This approach will help you effectively organize the counting process and track progress.

To solve this problem, you can use the for loop. This tool allows you to efficiently repeat certain actions, which makes it ideal for tasks that require iteration. Using the for loop simplifies data processing and optimizes the code, ensuring its clarity and readability.

for Loops

The for loop is widely used in C and other programming languages. By using it, we can organize our code more efficiently. An example of using a for loop might look like this:

Consider the content enclosed in parentheses.

  • First, we initialize the counter: i = 0.
  • Then, the condition that will be checked each time we go through the loop is initialized. We check whether i is less than 3 or not.
  • And lastly, we increment the counter by 1.

The for and while loops perform similar functions, but have their own peculiarities. In the for loop, the variable i is declared within parentheses, which limits its scope to that loop only. This means that once the loop ends, i will no longer be accessible. In contrast, in the while loop, the variable i is declared outside the parentheses, which allows it to retain its value even after the loop ends. Understanding these differences is important for properly managing variables and their scope in your code.

Creating Custom Functions

Let's create our own function in C, which we'll call meow(). After adding this function, our program will look like this:

The void meow(void) command specifies that the function takes no input parameters and does not return any values. The main purpose of this function is to print numbers and strings to the screen. Using this function can be useful for displaying information to the user or for debugging code, which makes it an important tool in programming.

In the C programming language, the function declaration must be placed at the beginning of the program. This differs from other languages, such as Python, where functions can be placed anywhere in the code. Proper organization of code in C helps to make it understandable and structured, which makes debugging and further development easier.

In the body of the for loop, we added a call to the meow() function. Now let's change it so that it meows multiple times. To do this, we'll move the for loop inside the function and pass the number of meows through the n argument. Since n will be an integer, we need to specify that its type is int.

The n argument was added to the declaration of the meow() function instead of an empty value. This change allows the function to accept a value, which expands its capabilities and makes the code more versatile. Now the meow() function can use the passed argument to perform various tasks, which increases its functionality and adaptability in various usage scenarios.

Let's create a function that will accept arguments and return a value. This is quite simple to implement in the C language. A function can have different types of return values, which makes it a universal tool for data processing. First, we'll define a function prototype, specifying the return type and parameter types. Then we'll implement the function that will perform the necessary calculations and return the result. This allows us to create more complex and reusable function calls, which improves the readability and maintainability of the code.

Let's create a program that will calculate the price of a product taking into account a discount. The program will take the original product price and the discount amount, and then calculate the final price with the discount applied. This approach will help users easily determine how much they will save on their purchase.

Here is the pricing information: "regular" is the regular price of the product, and "sale" is the discounted price that is currently in effect.

Let's create a custom function that takes the original price and returns the discounted price. This function will make it easy to calculate the final price of the product after applying the discount, which is convenient for online stores and services offering discounts on their products. Optimizing price offers with this function will help improve the user experience and increase the competitiveness of the business.

We converted all variables to floating-point numbers. This allows for greater calculation accuracy and improved data processing in our project. Using floating-point numbers ensures more flexible management of numeric values ​​and avoids errors associated with integer division.

The discount() function does not display the calculated value on the screen, but passes it back to the calling function. The return keyword is used for this. This allows the return value to be used for further calculations or display in the program.

Functions can take multiple arguments, including two, three, or more. Consider the discount() function, which takes the discount amount as an argument. This allows you to set any discount amount, rather than being limited to 15%. Using different discount values ​​makes the function more flexible and versatile for various application scenarios.

Our function successfully calculates the price of a product taking into account the discount, which you can set yourself. This allows you to easily adapt the price depending on current offers and promotions. Use our feature to calculate an accurate price with customized discounts.

Creating a Game in C

Now let's apply our knowledge to creating a small game. Think of Super Mario Bros.: coins were hidden behind question marks in the sky, which the player could collect. This gameplay design element adds excitement and encourages exploration of the game's locations. Using mechanics like these, we can develop unique levels where players have to find hidden objects and earn bonuses for doing so.

David in front of his slides during the course. Here he explains the rules of the game Mario. Frame: CS50 / YouTube

At this point, we can't create a vibrant and rich world for the game. Instead, let's just print a few question marks to reflect uncertainty and anticipation.

Improving the Program Using For Loops

For loops are a powerful tool for optimizing program code. They allow you to efficiently repeat certain actions, which is especially useful when working with arrays and collections of data. By using for loops, you can significantly reduce the number of lines of code and improve its readability. Using for loops in your program not only simplifies the logic but also improves performance, allowing you to perform multiple operations in minimal time.

Use for loops to automate routine tasks, such as processing data, performing calculations, or generating reports. This will allow you to focus on more important aspects of development, speeding up the process of writing and debugging code. Implementing for loops in your program is a step towards more efficient and organized code.

After the for loop completed, we printed a newline character \n. It is impossible to use it inside a loop, since each question mark would be displayed on a separate line. This limitation must be taken into account when working with output formatting in loops to preserve the desired appearance of the information.

Let's complicate our program by adding the ability to prompt the user for the number of question marks to display on the screen. To do this, we will get acquainted with the do while loop. This loop is similar to the while loop, but differs in that the condition is checked after the loop body is executed, rather than before. This ensures that the loop body is executed at least once, which can be useful in certain programming situations.

The do while loop is a convenient programming tool when certain actions need to be performed at least once, regardless of the condition. The main feature of this loop is that the condition is checked after the code block is executed, which guarantees its execution even if the condition initially turns out to be false. This makes the do while loop particularly useful in situations where you need to, for example, prompt the user for input until a valid value is entered. Using a do while loop allows you to effectively manage program execution flows, providing flexibility and control over process logic.

The user is unlikely to enter values ​​​​n = 0 or n = -100, as these do not have logical meaning. When the value of n becomes greater than or equal to 1, the program will terminate the current loop, and control will pass to the next command. This ensures efficient execution of the algorithm and minimizes the likelihood of errors during operation.

In this part of the game, Mario descends into a dungeon where he encounters a wall of bricks. This wall is an important element of the gameplay, as the player must find a way to destroy it. To do this, Mario can use his skills and abilities, such as jumping or special power-ups that help overcome obstacles. The dungeons in the game offer unique challenges and puzzles, which makes the process more fun and exciting. It's important to explore your environment to find different ways to interact with objects, such as brick walls, which opens up new possibilities for leveling up.

David in front of his slides while teaching the course. We see a wall of bricks—an obstacle for Mario. Frame: CS50 / YouTube.

Let's create a square fragment similar to the one shown in the image. Since this square depicts bricks, we will use the # symbol to render it.

To arrange the bricks in multiple rows, you need to use a nested loop. The example program demonstrates this approach.

The first loop is designed to count the lines from top to bottom, while the second loop sequentially displays the characters of each line on the screen, simulating the work of an old typewriter. This approach allows you to create the effect of gradually appearing text, which can improve the user experience and make interaction with the content more engaging.

Run the program and look at the results. Here's what we got:

Frame: CS50 / YouTube

The square is not perfect because the # symbol is shorter than its width. This is due to the specifics of the font used. Nevertheless, we can consider the problem solved.

Floating-Point Overflow

Let's return to our calculator and consider the problem of overflow when working with large numbers. This time, we'll focus on floating-point numbers. To do this, we'll change the variable type from integers (int) to floating-point numbers (float) and use division instead of addition. This will allow us to handle large values ​​more efficiently and avoid possible errors associated with overflow. Using floating-point numbers opens up new possibilities for precise calculations and expands the functionality of our calculator.

We'll add a new variable, float z, to the code, which will be equal to the result of dividing x by y, and display its value on the screen. This will allow us to see the result of the operation and better understand how variables are used in programming.

Let's run the calculator, setting the values ​​x = 2 and y = 3. This simple calculation will allow us to perform various mathematical operations, such as addition, subtraction, multiplication, and division. Using these values, we can obtain results for the following expressions: x + y, x - y, x * y, and x / y. These operations are the basis for understanding more complex mathematical concepts and allow you to solve problems more effectively.

Frame: CS50 / YouTube

We received the answer as a number with six decimal places. The computer returns the result with this precision by default.

To reduce the number of decimal places to two, you need to change the output format in the last command. This will achieve the desired result and improve the readability of the presented data. Proper number formatting is important to ensure the accuracy and clarity of the information.

Let's launch the program and begin the process. The program is designed to perform specific tasks, which allows you to optimize your workflow and increase efficiency. Make sure all the necessary components are installed and functioning correctly. Once launched, you will be able to take advantage of all the features this software offers. Adjust the settings to suit your requirements for best results.

Frame: CS50 / YouTube

Now let's extract 50 characters after the period.

Launch the calculator. This tool will help you quickly and accurately calculate the necessary parameters. Use the calculator to obtain up-to-date data to help you make decisions. Note the user-friendly interface and ease of use, making the calculation process quick and efficient. Use the calculator for various calculations to optimize your time and efforts.

Frame: CS50 / YouTube

Not only do we have difficulty adding up billions, but we are also unable to get an accurate result when dividing two numbers. This problem highlights the limitations faced not only by ordinary people but also by modern computing systems. It is important to understand that the accuracy of mathematical operations can depend on many factors, including the algorithms used and the representation of numbers.

A phenomenon similar to addition overflow occurs—a program returns an incorrect result if the number of bits used to store an integer exceeds the specified limits. This is not surprising, since the set of integers is infinite, and their length has no fixed boundaries. Integer overflow is a common problem in programming that can lead to errors and incorrect application operation. Therefore, it is important to be aware of the limitations when working with integers and apply methods to prevent such situations.

In this case, we are talking about floating-point numbers. The set of real numbers is uncountable, and the length of these numbers can be infinite. Limited computer memory makes it difficult to work with such numbers. However, in the scientific community, there are methods and algorithms that can improve the accuracy of calculations and efficiently work with floating-point numbers. These solutions incorporate various approaches to representing numbers and optimizing computational processes, making them indispensable in scientific research and engineering calculations.

Data Type Conversion

During program execution, a computer can change the type of data it processes. Consider the variables x and y, defined as integers, while the variable z will be represented as a floating-point number. This allows for efficient management of different data types and their use in calculations, providing flexibility and precision in information processing.

Run the program with the given variable values. Let's set x to 2 and y to 3.

Frame: CS50 / YouTube

The result was unexpected. In fact, the expected value is a never-ending decimal fraction of 0.6666666666, and so on. However, in the C programming language, when dividing an integer by an integer, the result is also an integer. This means that the fractional part that is less than 1 is discarded. This process is called truncation, and it is what causes the result to be 0 when the dividend is less than the divisor.

Consider the following example. Let x = 4 and y = 3. When dividing 4 by 3, the result is a never-ending decimal fraction of 1.33333, and so on. Now let's fire up the calculator and do this division.

Frame: CS50 / YouTube

The computer divided 4 by 3 using integer division, and as a result The result was 1.0000. The fractional part of the number was truncated, which is typical for integer operations.

To solve this problem, we use a technique known in C and other programming languages ​​as type conversion. This allows us to correctly change the data type, ensuring the correct interpretation of values ​​and minimizing errors. Type conversion plays a key role in programming, allowing developers to work with different data formats and ensuring compatibility between them. It is important to use type conversion wisely to avoid information loss and ensure software stability.

In this section, we tell the computer to treat int variables as floating-point numbers. Now let's run our calculator and divide 2 by 3 again.

Frame: CS50 / YouTube

The result becomes more accurate, but the error is still English: present.

More on Overflow Problems

In the first lecture, we looked at three bits that allow us to represent numbers from 0 to 7, which corresponds to binary code from 000 to 111. Then I asked a question about how we can express the number 8. One of the students suggested adding a fourth bit. This is indeed correct, since with the fourth bit, the number 8 can be represented in binary as 1000.

If you do not have the ability to add a fourth bit, adding 1 to the number 111 results in 000. This phenomenon is called overflow. In this situation, the number 8 cannot be represented in three bits, and the result of the operation is padding with zeros. Overflow is an important concept in programming and digital logic because it affects computation and data representation in finite systems.

The problem in question may seem unusual, but many have encountered it before. One notable example is the Y2K issue. On January 1, 2000, computers were required to update their clocks. Many systems, especially those designed many years ago, stored only the last two digits of the year in their dates to save memory. Therefore, the year 2000 would only display 00. If a program prefixed such a date with 19, the system would revert to 1900 instead of advancing to 2000. This issue highlights the importance of good programming practices and keeping legacy systems up-to-date to avoid similar errors in the future.

Fortunately, a significant amount of code had been patched by then, largely resolving the issue. However, there is a possibility that it could reoccur on January 19, 2038. Some software systems represent time as the number of seconds since midnight, January 1, 1970. However, older systems use a 32-bit signed integer to store seconds. The longest possible date that this format can represent is 03:14:07, January 19, 2038. Therefore, it is important to take this date into account when developing and updating software to avoid similar problems in the future.

After the specified date, the data field may take a negative value. Negative numbers can be interpreted by programs as a date in 1901. This means that any calculations based on a date after January 19, 2038, may end up with incorrect results.

Today, the cost of hardware has decreased significantly compared to several decades ago, and computer performance has increased. This makes hardware limitations less critical for users.

The error can also occur in popular software applications. Let's look at an example of a small program that converts dollars to pennies.

Let's run the program and enter several values ​​for the amount variable. This will allow us to test the functionality and ensure the algorithm is working correctly. By changing the value of the amount variable, we can observe how the program responds to different inputs. This is an important step in debugging and optimizing code, helping to identify potential errors and improve performance. The selection of values ​​for the amount variable can include both positive and negative numbers, as well as zero, which expands the testing range.

Frame: CS50 / YouTube

When entering a value of amount equal to 4.2, the program produces an incorrect result. While an error of one tenth may seem insignificant in a supermarket, it can have serious consequences in financial transactions or scientific measurements. Calculation errors can lead to unreliable data, which, in turn, can affect important decisions. Therefore, it is important to pay attention to the accuracy of calculations and ensure that data is handled correctly in software. Let's try to correct this error. Consider a situation where a computer stores the amount of 4 dollars and 19.99999 cents. To eliminate the inaccuracy, we will round the result. To do this, we will include the math.h library of mathematical functions and apply the round() function, which is available in this library. Using the round() function will help obtain the correct value, avoiding problems associated with floating point. This will ensure more accurate calculations and improve the processing of financial data in our application.

Let's run the program again.

Frame: CS50 / YouTube

The text was successfully Fixed.

It's important to remember these aspects. Unfortunately, even experienced programmers sometimes neglect these details. Our goal in training is not only to teach you how to program, but also to give you a deeper understanding of the processes occurring "under the hood" of software code. This knowledge will allow you to become a more qualified specialist and improve the quality of your projects.

Errors in technology can have serious consequences, and society sometimes pays a high price for them. A striking example is the situation with a bug in the Boeing aircraft control system, which became known several years ago. This system required a regular reboot every 248 days. Otherwise, during flight, it could go into failsafe mode, which in turn would lead to a generator shutdown and a potential disaster. Such incidents highlight the importance of rigorous testing and monitoring of systems that ensure air transport safety.

The issue arose because software used a 32-bit number to track tenths of a second, which affected the generators' electrical power parameters. After 248 days, an overflow occurred, leading to a power outage. Boeing's solution was to use a 32-bit operating system. The company has now released a patch that addresses this vulnerability, ensuring stable system operation and preventing outages.

As the number of portable devices and hardware increases, we face increasing challenges. Each new gadget brings not only convenience but also potential complications, such as compatibility, security, and the need for regular updates. The more technologies we use, the more important it is to understand how to manage them effectively and minimize the difficulties that arise.

Summary

Today's lecture covered important aspects of the topic. We discussed key points that will help you better understand the subject. The main focus was on the main concepts and methods that can be applied in practice. We looked at examples illustrating theoretical principles and answered questions that arose during the discussion. It is important to remember that a deep understanding of the material requires constant study and practice. We hope that the knowledge gained will be useful in your future work.

  • If you plan to use the result of a calculation in your code repeatedly, save it in a separate variable.
  • You can press the up arrow in the code editor to see the entire command history and select the one you need, instead of typing the same thing repeatedly. This will speed up your work.
  • Be aware of the overflow problem when working with int and float data types—they all use a finite number of bits for representation. Use the long data type to avoid this problem.
  • In C, a function declaration is always placed at the beginning of a program. In some other programming languages, such as Python, functions can be declared anywhere in the code.
  • To round numbers correctly, use the round() function from the math.h library of mathematical functions.

Learn more about programming and coding in our Telegram channel. Subscribe to stay up to date with the latest news and interesting materials.

Read also:

  • Starting to learn the C programming language. CS50 in Russian. Lecture 1.1
  • Fatality: The 5 Most Expensive Bugs in History
  • Floating-Point Numbers: What They Are and How They Work