Table of Contents
If we want to print some text on the screen in the C programming language, we use the printf function:
Let's write some code in C that asks the user what his name is and greets him:
Let's ask the user to input x and y variables of type int and compare the input numbers against each other:
Let's output

CS- Week 1

Jul 17, 2024 am 10:07 AM

Machines only understand binary. When we write a list of human-readable instructions for a computer, machines understand only what we now call machine code. This machine code consists of only 1's and 0's.
With a special program called Compiler
, we can turn the original code into machine code. We can judge good code according to 3 criteria:

correctness (
    does the code produce the desired result?
  • ), design (
  • is the code design or structure well structured?
  • ), style (
  • How nicely is the code written?
  • ).
  • Hello World!

If we want to print some text on the screen in the C programming language, we use the printf function:


The

printf function prints the text
#include <stdio.h>

int main(void)
{
    printf("salom, dunyo\n")
}
Copy after login
hello, world

. The special character in it tells the compiler that the next character is a special instruction. And the symbol n after it means "new line" (new line). The expression on the first line of code is a very special command that says we want to use the capabilities of a library called stdio.h. This library allows us to use the function printf.
Libraries
is a set of ready-made functions that we can use in our code. Variables

Let's write some code in C that asks the user what his name is and greets him:


The capabilities of the cs50.h library, specially developed for the CS50 course, are used throughout this course. One of them is the get_string function. The get_string function is used to retrieve the text entered by the user.
#include <cs50.h>
#include <stdio.h>

int main(void)
{
    string answer = get_string("Ismingiz nima? ");
    printf("Assalomu alaykum, %s\n", answer);
}
Copy after login
answer is a place reserved to remember a special user-entered text, which we call a variable. answer is of type

string
. Also, there are many other data types such as int, bool, char, etc. %s is a placeholder called format code
that tells the printf function to prepare to accept some string variable. There are also format codes for other data types, for example: %i - for
int
(integers). Conditional operators

Let's ask the user to input x and y variables of type int and compare the input numbers against each other:


Here we are creating two variables of type int (
#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int x = get_int("x ni kiriting: ");
    int y = get_int("y ni kiriting: ");

    if (x < y)
    {
        printf("x soni y sonidan kichik\n");
    }
}
Copy after login
integer

), variables x and y. Their values ​​are filled using the get_int function of the cs50.h library. Using the conditional operator, we compare the values ​​of x and y and display a message on the screen depending on the result.

Block diagram

is a way we can check how a computer program works. With this method we can check the efficiency of our code. Let's see the block diagram of our code above:

Conditional 1We can improve the program by coding as follows:


All possible cases are now considered. Let's see its block diagram:
#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int x = get_int("x ni kiriting: ");
    int y = get_int("y ni kiriting: ");

    if (x < y)
    {
        printf("x soni y sonidan kichik\n");
    }
    else if (x > y)
    {
        printf("x soni y sonidan katta\n");
    }
    else
    {
        printf("x soni y soniga teng\n");
    }
}
Copy after login


Conditional 2 Repetition operators

Let's output

"meow"

to the screen 3 times:

The code we wrote works correctly, but we can improve our program by avoiding repetitions:
#include <stdio.h>

int main(void)
{
    printf("meow\n");
    printf("meow\n");
    printf("meow\n");
}
Copy after login


In this, the variable i of type int is created and given the value 3. Then i < A while loop is created that lasts for a time of 3. Each time using the i++ expression, we increment i by one, and the loop stops when i = 3.
#include <stdio.h>

int main(void)
{
    int i = 0;
    while (i < 3)
    {
        printf("meow\n");
        i++;
    }
}
Copy after login
We can further improve the design of our program by using the for loop:



The

for loop takes three arguments.
#include <stdio.h>

int main(void)
{
    for (int i = 0; i < 3; i++)
    {
        printf("meow\n");
    }
}
Copy after login
The first argument: int i = 0 initializes our counter.

Second argument: i < 3 - checked condition.
Finally, the i++ argument means that every time our number i increases by one.
We can also create our own function:


void means that the function does not return any value. In parentheses (void) - means that the function does not accept any parameters.
void meow(void)
{
    printf("meow\n");
}
Copy after login
We will use this created meow function inside the main function:


#include 

void meow(void);

int main(void)
{
    for (int i = 0; i < 3; i++)
    {
        meow();
    }
}

void meow(void)
{
    printf("meow\n");
}
Copy after login

meow funksiyasini asosiy funksiya ichida chaqira olishimiz uchun funksiya prototipi kodning yuqori qismida void meow(void) sifatida berilgan.

Arifmetik operatorlar va akstraksiya

Keling, C tilida kalkulyator yasaymiz:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    // x qiymati kiritilsin
    int x = get_int("x: ");

    // y qiymati kiritilsin
    int y = get_int("y: ");

    // Qo'shish amalini bajarish
    printf("%i\n", x + y);
}
Copy after login

get_int funktsiyasi yordamida foydalanuvchidan butun son bo'lgan x va y o'zgaruvchilariga qiymat berishi so'ralyabdi. Keyin printf funksiyasi butun son uchun format kodi - %i belgisi yordamida x + y qiymatini chop etadi.

Arifmetik operatorlar kompilyator tomonidan qo'llab-quvvatlanadigan matematik operatsiyalardir. C tilida arifmetik operatorlarga quyidagilar kiradi:

  • + - qo'shish uchun;
  • - - ayirish uchun;
  • * - ko'paytirish uchun;
  • / - bo'linish uchun;
  • % - bir sonni ikkinchi songa bo'lgandagi qoldiqni hisoblash uchun.

Abstraksiya - bu muammoni kichik-kichik bo'laklarga bo'lib hal qilish orqali kodimizni soddalashtirish san'ati.
Biz yuqoridagi kodimizni quyidagicha abstraktlashimiz mumkin:

#include <cs50.h>
#include <stdio.h>

int add(int a, int b);

int main(void)
{
    // x qiymati kiritilsin
    int x = get_int("x: ");

    // y qiymati kiritilsin
    int y = get_int("y: ");

    // Qo'shish amalini bajarish
    printf("%i\n", add(x, y));
}

int add(int a, int b)
{
    return a + b;
}
Copy after login

Bunda parametr sifatida a va b butun sonlarini qabul qilib oladigan va ularning yig'indisini qaytaradigan alohida add funksiyasi e'lon qilingan va asosiy funksiya ichida argument sifatida x va y butun sonlarini olib add(x, y) funksiyamiz chaqirilyabdi.

Kommentlar (izohlar)

Kommentlar - kompyuter dasturining asosiy qismlari bo'lib, yozgan kodimiz nima vazifa bajarayotganini ifodalovchi, boshqa dasturchilarga, shuningdek o'zimizga tushunarli hamda qisqa qilib qoldirgan izohlarimizdir. Kommentni yozish uchun shunchaki ikkita // beligisidan foydalanamiz:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    // Musbat butun son kiritilsin
    int n;
    do
    {
        n = get_int("Musbat butun son kiriting: ");
    }
    while (n < 1);
}
Copy after login

Ma'lumot turlari

Ma'lumotlar turlari o'zgaruvchida saqlanishi mumkin bo'lgan ma'lumotlar turini belgilaydi. Misol uchun, o'zgaruvchilar raqamlar, belgilar yoki mantiqiy qiymatlarni saqlashi mumkin. O'zgaruvchining turi kompyuterga ushbu ma'lumotlarni qanday boshqarishni aytadi.
C tilidagi umumiy maʼlumotlar turlari:

  • bool: rost (true) yoki yolg'on (false) kabi mantiqiy qiymatlarni saqlashi mumkin.
  • char: faqat bitta belgini saqlashi mumkin.
  • float: o'nlik qiymatlari bo'lgan haqiqiy son.
  • int: kasrsiz butun son.
  • long: int dan kattaroq butun sonni saqlashi mumkin, chunki u ko'proq bit ishlatadi.
  • string: belgilar ketma-ketligini saqlashi mumkin (masalan, so'z).

Har bir turning o'ziga xos chegaralari bor. Misol uchun, xotiradagi cheklovlar tufayli int ning eng yuqori qiymati 4294967295 bo'lishi mumkin. Agar biz int ni uning eng yuqori qiymatidan o'tkazib sanashga harakat qilsak, bu o'zgaruvchida noto'g'ri qiymat saqlanishiga (integer overflow) olib keladi.
Xotirani noto'g'ri ishlatish kodimizdagi xatolar yoki muammolarga olib kelishi mumkin. Muammolarni oldini olish uchun biz to'g'ri ma'lumot turidan foydalanayotganimizga ishonch hosil qilishimiz kerak.

Ushbu maqolada CS50x 2024 manbasidan foydalanilgan.

The above is the detailed content of CS- Week 1. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

C# vs. C  : Learning Curves and Developer Experience C# vs. C : Learning Curves and Developer Experience Apr 18, 2025 am 12:13 AM

There are significant differences in the learning curves of C# and C and developer experience. 1) The learning curve of C# is relatively flat and is suitable for rapid development and enterprise-level applications. 2) The learning curve of C is steep and is suitable for high-performance and low-level control scenarios.

The C   Community: Resources, Support, and Development The C Community: Resources, Support, and Development Apr 13, 2025 am 12:01 AM

C Learners and developers can get resources and support from StackOverflow, Reddit's r/cpp community, Coursera and edX courses, open source projects on GitHub, professional consulting services, and CppCon. 1. StackOverflow provides answers to technical questions; 2. Reddit's r/cpp community shares the latest news; 3. Coursera and edX provide formal C courses; 4. Open source projects on GitHub such as LLVM and Boost improve skills; 5. Professional consulting services such as JetBrains and Perforce provide technical support; 6. CppCon and other conferences help careers

C   and XML: Exploring the Relationship and Support C and XML: Exploring the Relationship and Support Apr 21, 2025 am 12:02 AM

C interacts with XML through third-party libraries (such as TinyXML, Pugixml, Xerces-C). 1) Use the library to parse XML files and convert them into C-processable data structures. 2) When generating XML, convert the C data structure to XML format. 3) In practical applications, XML is often used for configuration files and data exchange to improve development efficiency.

What is static analysis in C? What is static analysis in C? Apr 28, 2025 pm 09:09 PM

The application of static analysis in C mainly includes discovering memory management problems, checking code logic errors, and improving code security. 1) Static analysis can identify problems such as memory leaks, double releases, and uninitialized pointers. 2) It can detect unused variables, dead code and logical contradictions. 3) Static analysis tools such as Coverity can detect buffer overflow, integer overflow and unsafe API calls to improve code security.

Beyond the Hype: Assessing the Relevance of C   Today Beyond the Hype: Assessing the Relevance of C Today Apr 14, 2025 am 12:01 AM

C still has important relevance in modern programming. 1) High performance and direct hardware operation capabilities make it the first choice in the fields of game development, embedded systems and high-performance computing. 2) Rich programming paradigms and modern features such as smart pointers and template programming enhance its flexibility and efficiency. Although the learning curve is steep, its powerful capabilities make it still important in today's programming ecosystem.

How to use the chrono library in C? How to use the chrono library in C? Apr 28, 2025 pm 10:18 PM

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

The Future of C  : Adaptations and Innovations The Future of C : Adaptations and Innovations Apr 27, 2025 am 12:25 AM

The future of C will focus on parallel computing, security, modularization and AI/machine learning: 1) Parallel computing will be enhanced through features such as coroutines; 2) Security will be improved through stricter type checking and memory management mechanisms; 3) Modulation will simplify code organization and compilation; 4) AI and machine learning will prompt C to adapt to new needs, such as numerical computing and GPU programming support.

See all articles