Learn C Programming
eBook - ePub

Learn C Programming

A beginner's guide to learning C programming the easy and disciplined way

Jeff Szuhay

  1. 646 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Learn C Programming

A beginner's guide to learning C programming the easy and disciplined way

Jeff Szuhay

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Get started with writing simple programs in C while learning the skills that will help you work with practically any programming language

Key Features

  • Learn essential C concepts such as variables, data structures, functions, loops, arrays, and pointers
  • Get to grips with the core programming aspects that form the base of many modern programming languages
  • Explore the expressiveness and versatility of the C language with the help of sample programs

Book Description

C is a powerful general-purpose programming language that is excellent for beginners to learn. This book will introduce you to computer programming and software development using C. If you're an experienced developer, this book will help you to become familiar with the C programming language.

This C programming book takes you through basic programming concepts and shows you how to implement them in C. Throughout the book, you'll create and run programs that make use of one or more C concepts, such as program structure with functions, data types, and conditional statements. You'll also see how to use looping and iteration, arrays, pointers, and strings. As you make progress, you'll cover code documentation, testing and validation methods, basic input/output, and how to write complete programs in C.

By the end of the book, you'll have developed basic programming skills in C, that you can apply to other programming languages and will develop a solid foundation for you to advance as a programmer.

What you will learn

  • Understand fundamental programming concepts and implement them in C
  • Write working programs with an emphasis on code indentation and readability
  • Break existing programs intentionally and learn how to debug code
  • Adopt good coding practices and develop a clean coding style
  • Explore general programming concepts that are applicable to more advanced projects
  • Discover how you can use building blocks to make more complex and interesting programs
  • Use C Standard Library functions and understand why doing this is desirable

Who this book is for

This book is written for two very diverse audiences.

If you're an absolute beginner who only has basic familiarity with operating a computer, this book will help you learn the most fundamental concepts and practices you need to know to become a successful C programmer.

If you're an experienced programmer, you'll find the full range of C syntax as well as common C idioms. You can skim through the explanations and focus primarily on the source code provided.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Learn C Programming un PDF/ePUB en línea?
Sí, puedes acceder a Learn C Programming de Jeff Szuhay en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2020
ISBN
9781789348637
Edición
1
Categoría
Computer Science
Categoría
Programming in C
Section 1: C Fundamentals
In this section, we're going to jump into writing simple programs as we explore the fundamentals of not only C but general programming.
This section comprises the following chapters:
  • Chapter 1, Running Hello, World!
  • Chapter 2, Understanding Program Structures
  • Chapter 3, Working with Basic Data Types
  • Chapter 4, Using Variables and Assignment
  • Chapter 5, Exploring Operators and Expressions
  • Chapter 6, Exploring Conditional Program Flow
  • Chapter 7, Exploring Loops and Iteration
  • Chapter 8, Creating and Using Enumerations
Running Hello, World!
Computer programming is about learning how to solve problems with a computer – about how to get a computer to do all the tedious work for us. The basic development cycle, or process of writing a computer program, is to determine the steps that are necessary to solve the problem at hand and then tell the computer to perform those steps. Our first problem, as we learn this process, is to learn how to write, build, run, and verify a minimal C program.
The following topics will be covered in this chapter:
  • Writing your first C program
  • Understanding the program development cycle
  • Creating, typing into a text editor, and saving your C program
  • Compiling your first C program
  • Running your program, verifying its result, and, if necessary, fixing it
  • Exploring different commenting styles and using them
  • Employing guided chaos, followed by careful observation for deeper learning
Let's get started!

Technical requirements

To complete this chapter and the rest of this book, you will need a running computer that has the following capabilities:
  • A basic text editor that is able to save unformatted plain text
  • A Terminal window that commands can be entered into via the command line
  • A compiler to build your C programs with
Each of these will be explained in more detail as we encounter them in this chapter.
The source code for this chapter can be found at https://github.com/PacktPublishing/Learn-C-Programming. However, please make every effort to type the source code in yourself. Even if you find this frustrating at first, you will learn far more and learn far more quickly if you do all the code entry for yourself.

Writing your first C program

We will begin with one of the simplest, most useful programs that can be created in C. This program was first used to introduce C by its creators, Brian W. Kernighan and Dennis M. Ritchie, in their now-classic work, The C Programming Language, published in 1978. The program prints a single line of output – the greeting Hello, world! – on the computer screen.
This simple program is important for a number of reasons. First, it gives us a flavor of what a C program is like, but more importantly, it proves that the necessary pieces of the development environment – the Operating System (OS), text editor, command-line interface, and compiler – are installed and working correctly. Finally, it gives us the first taste of the basic programming development cycle. In the process of learning to program and, later, actually solving real problems with programming, you will repeat this cycle often. It is essential that you become both familiar and comfortable with this cycle.
This program is useful because it prints something out to the Terminal, also known as the console, telling us that it actually did something – it displays a message to us. We could write shorter programs in C but they would not be of much use. We would be able to build and run them but would have little evidence that anything actually happened. So, here is your first C program. Throughout this book, and during the entirety of your programming experience, obtaining evidence of what actually happened is essential.
Since Kernighan and Ritchie introduced the Hello, world! program over 40 years ago, this simple program has been reused to introduce many programming languages and used in various settings. You can find variations of this program in Java, C++, Objective-C, Python, Ruby, and many others. GitHub, an online source code repository, even introduces their website and its functions with a Hello World beginner's guide.

Hello, world!

Without further ado, here is the Hello, world! C program. It does no calculations, nor does it accept any input. It only displays a short greeting and then ends, as follows:
#include <stdio.h>

int main()
{
printf( "Hello, world!\n" );
return 0;
}
Some minor details of this program have changed since it was first introduced. What is here will build and run with all C compilers that have been created in the last 20 years.
Before we get into the details of what each part of this program does, see if you can identify which line of the program prints our greeting. You may find the punctuation peculiar; we will explain this in the next chapter. Notice how some punctuation marks come in pairs, while others do not. There are five paired and five unpaired punctuation marks in all. Can you identify them? (We are not counting the punctuation in the message "Hello, world!".)
There is another pairing in this simple program that is not obvious at this time, but one that we will explore further in the next chapter. As a hint, this pairing involves the lines int main() and return 0;.
Before we jump into creating, compiling, and running this program, we need to get an overview of the whole development process and the tools we'll be using.

Understanding the program development cycle

There are two main types of development environments:
  • Interpreted: In an interpreted environment such as Python or Ruby, the program can be entered line by line and run at any point. Each line is evaluated and executed as it's entered and the results are immediately returned to the console. Interpreted environments are dynamic because they provide immediate feedback and are useful for the rapid exploration of algorithms and program features. Programs entered here tend to require the interpreting environment to be running as well.
  • Compiled: In a compiled environment such as C, C++, C#, or Objective-C, programs are entered into one or more files, then compiled all at once, and if no errors are found, the program can be run as a whole. Each of these phases is distinct, with separate programs used for each phase. Compiled programs tend to execute faster since there is a separate, full compilation phase, and can be run independently of the interpreting environment.
As with shampoo, where we are accustomed to wet hair, lather, rinse, and repeat, we will do the same with C – we will become familiar with the edit, compile, run, verify, and repeat cycle.

Edit

Programs are generated from text files whose filenames use predefined file extensions. These are known as source files, or source code files. For C, the .c file extension indicates a C source code file. An .h extension (which is present in our Hello, world! program) indicates a C header file. The compiler looks for .c and .h files as it encounters them and because each has a different purpose, it treats each differently as well. Other languages have their own file extensions; the contents of a source code file should match the language that the compiler expects.
To create and modify C files, you will need a plain text editor. This is a program that allows you to open, modify, and save plain text without any formatting such as font size, font family, font style, and much more. For instance, on Windows, Notepad is a plain text editor while Word is not. The plain text editor should have the following capabilities:
  • File manipulation: Open a file, edit a file, save the file and any changes that have been made to it, and save the file with another name.
  • The ability to navigate the file: Move up, down, left, right, to the beginning of the line, end of the line, beginning of the file, end of the file, and so on.
  • Text manipulation: Insert text, delete text, insert line, delete line, selection, cut, copy, paste, undo/redo, and so on.
  • Search and replace: Find text, replace text, and so on.
The following capabilities are handy but not essential:
  • Automatic indentation
  • Syntax coloring for the specific programming language
  • Automatic periodic saving
Almost any plain text editor will do. Do not get too caught up in the features of any given text editor. Some are better than others; some are free, while others are costly, and may not immediately be worth the expense (perhaps later, one or more might be worthwhile but not at this time), and none will do 100% of what you might want them to do.
Here are some free plain text editors worth installing on your computer and trying out:
  • Everywhere:Nano, which runs in a Terminal; a moderate learning curve.
  • Linux/Unix:
    • Vim, or vi: Runs in a Terminal; a moderate learning curve. It is on every Linux/Unix system, so it's worth learning how to use its basic features.
    • gedit: A powerful general-purpose editor.
    • Emacs: An everything and the kitchen sink editor; a very large learning curve.
  • Windows:
    • Notepad: Very simple – sometimes too simple for programming – but included in every Windows system.
    • Notepad++: A better version of Notepad with many features for programming.
  • macOS only: BBEdit (free version), which is a full-featured GUI programming text editor.
There are many, many text editors, each with its own strengths and weaknesses. Pick a text editor and get used to it. Over time, as you use it more and more, it will become second nature.

Compile

The compiler is a program that takes input source code files – in our case, .c and .h files – translates the textural source code found there into machine language, and links together all the predefined parts needed to enable the program to run o...

Índice

  1. Title Page
  2. Copyright and Credits
  3. Dedication
  4. About Packt
  5. Contributors
  6. Preface
  7. Section 1: C Fundamentals
  8. Running Hello, World!
  9. Understanding Program Structure
  10. Working with Basic Data Types
  11. Using Variables and Assignment
  12. Exploring Operators and Expressions
  13. Exploring Conditional Program Flow
  14. Exploring Loops and Iteration
  15. Creating and Using Enumerations
  16. Section 2: Complex Data Types
  17. Creating and Using Structures
  18. Creating Custom Data Types with typedef
  19. Working with Arrays
  20. Working with Multi-Dimensional Arrays
  21. Using Pointers
  22. Understanding Arrays and Pointers
  23. Working with Strings
  24. Creating and Using More Complex Structures
  25. Section 3: Memory Manipulation
  26. Understanding Memory Allocation and Lifetime
  27. Using Dynamic Memory Allocation
  28. Section 4: Input and Output
  29. Exploring Formatted Output
  30. Getting Input from the Command Line
  31. Exploring Formatted Input
  32. Working with Files
  33. Using File Input and File Output
  34. Section 5: Building Blocks for Larger Programs
  35. Working with Multi-File Programs
  36. Understanding Scope
  37. Appendix
  38. Other Books You May Enjoy
Estilos de citas para Learn C Programming

APA 6 Citation

Szuhay, J. (2020). Learn C Programming (1st ed.). Packt Publishing. Retrieved from https://www.perlego.com/book/1636276/learn-c-programming-a-beginners-guide-to-learning-c-programming-the-easy-and-disciplined-way-pdf (Original work published 2020)

Chicago Citation

Szuhay, Jeff. (2020) 2020. Learn C Programming. 1st ed. Packt Publishing. https://www.perlego.com/book/1636276/learn-c-programming-a-beginners-guide-to-learning-c-programming-the-easy-and-disciplined-way-pdf.

Harvard Citation

Szuhay, J. (2020) Learn C Programming. 1st edn. Packt Publishing. Available at: https://www.perlego.com/book/1636276/learn-c-programming-a-beginners-guide-to-learning-c-programming-the-easy-and-disciplined-way-pdf (Accessed: 14 October 2022).

MLA 7 Citation

Szuhay, Jeff. Learn C Programming. 1st ed. Packt Publishing, 2020. Web. 14 Oct. 2022.