Introduction to programming in C. A practical approach.

1,996 348 800KB

English Pages [57] Year 2020

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Introduction to programming in C. A practical approach.

Table of contents :
Introduction to programming in C. A practical approach.
1.- Presentation
2.- The C language
4.- Your first program in C
6.- Phases of elaboration of a program. Hello World
8.- Description of the part of the program
9.- Exercises
10.- Variables and types of variables
11.- Basic concepts .. memory bits and bytes
12.- Variables. Integer and real
13.- Mathematical operations
14.- Conversion of types
15.- Example. Calculation of prices with VAT
16.- Making decisions
17.- Logical comparisons
18.- Relational operators and logical operators
19.- Selecting options
20.- Example: Basic calculator
21.- Advanced topics. Loops
22.- Arrays
23.- Text strings
24.- Exercises for the student
25.- Variables and Pointers
26.- Dynamic memory
27.- Structured programming
28.- Data structures
About the Author

Citation preview

Introduction to programming in C. A practical approach.

Enrique Vicente

This course in a electronic format is a compilation of the course "Introduction to programming in C. A practical approach" published in Udemy and which you can access with the following link

Introduction to programming in C. A practical approach. You can follow me on my blog https://evginformatica.blogspot.com where you will find courses of programming and web development, free courses, tutorials and much more ... Sincerely, Enrique Vicente García

Index Introduction to programming in C. A practical approach. 1.- Presentation 2.- The C language 4.- Your first program in C 6.- Phases of elaboration of a program. Hello World 8.- Description of the part of the program 9.- Exercises 10.- Variables and types of variables 11.- Basic concepts .. memory bits and bytes 12.- Variables. Integer and real 13.- Mathematical operations 14.- Conversion of types 15.- Example. Calculation of prices with VAT 16.- Making decisions 17.- Logical comparisons 18.- Relational operators and logical operators 19.- Selecting options 20.- Example: Basic calculator 21.- Advanced topics. Loops 22.- Arrays 23.- Text strings 24.- Exercises for the student 25.- Variables and Pointers 26.- Dynamic memory 27.- Structured programming 28.- Data structures About the Author

1.- Presentation Hello, I'm Enrique Vicente and I'm going to introduce you to the course "Introduction to programming. A practical approach". This course is aimed to computer enthusiasts who want to enter the exciting world of programming. This course is not recommended to computer scientists with a high level of knowledge because the concepts explained are introductory. Students at the end of the course will have a vision of how to learn to program in a language such as C, a versatile and portable language that will help them in the future to program in other languages such as C ++, C # or Java. They will also have the necessary concepts to understand what a computer program is and what difficulties they may encounter when developing a program and how to solve them. This course is based on examples and exercises that we will follow step by step to guide you in the world of programming.

Examples and exercises Students who are interested can obtain the course examples and additional exercises can sign up to the class Google Classroom https://classroom.google.com/ with the code lq5hhp Sign up and we can continue with more advanced topics, ask questions or consultations on the topics covered in the course. I would appreciate that the students who have finished the course to write a review giving their opinion and assessment of the course.

You can follow us on the blog https://evginformatica.blogspot.com where you will find free courses, tutorials and discounts on upcoming Udemy courses.

2.- The C language C is the ideal language to begin in the world of programming. It is a compact and very portable language since there are C compilers for many of the platforms of nowadays (Windows, Linux, Mac ...) The C language is used on many areas of programming real applications in the business world and is a good start to start professionally. Once this language is learned, it can serve as a basis for learning other languages such as C ++, C # or Java with an object orientation philosophy.

3.- Downloading and installation of the development environment Once this short introduction is done, we will present the programming environment that we will use throughout the course. We will need to download from the internet the tool Microsoft Visual Studio Community 2017 . We search in Google Visual Studio 2017 and download the Community version This development environment has several versions: one free, professional and business. The differences lie in the use that will be give. If we are going to start programming, we can do it with the Comunity version, if we are going to use the tool at work, the professional version is recommended since it provides more components and work tools. The business version is mainly for team work and allows code sharing among several programmers. Visual Studio is a development tool based on projects that can be in different languages. To be able to execute our examples we will install the C/C ++ package for console Once Visual Studio is installed, we must create project "Windows console application" called courseC in the folder c:\ The development environment offer many options, create projects, compile debug execute, .. we will see all that throughout the course.

Note. If you work with another operating system other than Windows, you can try running the examples on https://repl.it where you can do tests in several languages, including C.

4.- Your first program in C In this section we will talk about concepts such as machine language, source language and how to translate from one to the other. We will learn the different phases that we must follow to make a computer program and then we will make our first program.

5.- Interpreted and compiled languages Any program written on a computer must be translated into the machine language. The machine language is a language that depends on the type of CPU and the manufacturer and there are numerous versions. As the machine language is very complicated and variable depending on the platform there are some languages (more similar to English) that indicate the sequence of steps to follow (program). These languages are called source code languages and are those used to define the programs of a computer. Once code in source language, we must pass it through a translator that translates it into machine language, which is what the computer really knows. There are three types of translations depending on how the machine language is generated from the source code.

Interpreted languages The translator reads the source program line by line, translates it and the computer executes it. With this option the development of a program is faster at the time of writing but has the disadvantage that more errors occur and these are more difficult to correct. Examples of these types of languages are JavaScript or PHP.

Compiled languages After editing the program, this is translated in its entirety (compilation). At this moment, the syntactic errors that can occur due to the structure of the

program are shown to the operator. With this option, the development slows down because each time the program is changed, it must be compiled, while the treatment of errors is simpler and easier to debug. Compiled language examples are C, C ++

Mixed languages These are languages that are compiled into an intermediate language and then interpreted into machine language. They have the same advantages as the compiled languages but are more portable and can be run on machines with different operating systems. Examples C # or Java

6.- Phases of elaboration of a program. Hello World Now we are going to make our first program in C Open the VIsualStudio and go to File - Open project - courseC Copy the following piece of code: /* firstprogram.c */ #include "pch.h" #include int main () { printf ("Hello world! \n"); } Yes, we execute it, we will see a screen with the text Hello World ... The phases that we will follow to make our programs are Phase 1. Define the problem to be solved and elaborate an algorithm (steps to follow) In this phase we must define clearly what we want make with our program, what inputs you will receive and what outputs you will produce. We must also indicate in natural language (Spanish, English ...) what steps the program should follow to achieve the objective set. These steps to follow are what we call the Algorithm of our program.

Phase 2. Editing the program Once we know what to do, we have to think about how to translate that functionality into our chosen programming language, in this case C. Then we will write our program in C in the editor of VIsual Studio. You can edit the program with simple text editors such as Notepad but integrated environments have multiple advantages such as indentation (which allows us to better visualize our program) or associate colors to different functionalities (to see at a glance the key words, types of data, etc) Phase 3. Compilation Once the program has been edited, we compile it and see if syntactic errors occur. Syntactic errors occur because the compiler does not understand some line that we have introduced in the source language. The compiler is responsible for translating the source code in C in machine language.

Phase 4. Linking If our project consists of several files or modules, in the linking process, external references are grouped and resolved. If our program uses external functionalities of the compiler or the operating system at this time, references to external sources are added. After the linking process, an executable file (.exe in Windows) is produced. Phase 5. Execution

In this phase we can execute the executable program and see if the results match what we expected. If we detect any error we must return to the edition and make the necessary changes. In this phase, runtime errors may occur due to the fact that some variable takes a value outside its limits or errors in the logic of the program. Phase 6. Debugging In case of errors in runtime or the expected functionality is not done correctly, we can debug the program in our programming environment. Some useful tools are . the option to execute the program step by step . tell the program to stop the execution in a line of the given code. . display of the value of the variables in real time. Phase 7. Testing and maintenance The program must be tested in all possible cases, in case of detecting failures we must go again to the editing phase Once the program is working correctly it goes to the Exploitation phase where it is executed in its real environment (pej on the client's computer that requested the program) Then the program enters its maintenance phase, where the client will ask us for new features or modify the program because some functionality is not to his liking.

7.- Modification of the program, comments and error control We will modify our first program and we will see its effect, compile, link and execute. We can add comments to our program with /* */or with // Everything written in a comment will be ignored by the compiler. It is recommended to comment our programs for a better follow-up and subsequent maintenance of the code. We can put comments to the first example. Now we remove the semicolon from the end of the printf and compile. When compiling our program if it has syntactic errors, the IDE will show them to us so we can solve them. The program can not be run until all errors have been resolved.

8.- Description of the part of the program . Comments We can put comments to indicate the name of the program, its operation, what entrances and exits will have, etc. /* firstprogram.c */ . Preprocessing #include "pch.h" #include These lines tell the compiler where to find the definition of functions not defined in this module. Pch.h is the so-called precompiled header and is a precompiled version of the external definitions and is used to make the compilation process faster. . Function main int main () Every program in C must include the main function that is the entry point for our program. . Keywords Our C program will contain a series of reserved keywords of the language that can not be used as names of other variables or functions. . External functions printf and arguments The printf function is an external function defined in the iostream module and added

by the compiler in the linking phase. . Control characters pej \n The sequence \n is used to indicate a line break.

9.- Exercises Write a program that writes your name and surnames in separate lines. Investigate how to write on the screen the following text The programmer said "C is a good language".

10.- Variables and types of variables In the next section we will talk about what variables are and what types of variables we can find in C. We will learn how to define variables in our program and do mathematical operations between them.

11.- Basic concepts .. memory bits and bytes Both the program and the data it uses are stored in the computer's memory. The memory of the computer is a sequence of "boxes" to store a value of 0 or a value of 1. These "boxes" are the bits and is the minimum unit of information that a computer can store. To improve access to memory these bits can be grouped from 8 to 8 forming a byte. The computer's memory is expressed in multiples of one byte 1 kilobyte (or 1KB) is 1,024 bytes. 1 megabyte (or 1MB) is 1,024 kilobytes, which is 1,048,576 bytes. 1 gigabyte (or 1GB) is 1,024 megabytes, which is 1,073,741,841 bytes

12.- Variables. Integer and real Variable A variable is a memory area of 1 or several bytes to which a name is associated so that it can be referenced in our program. Whole variables Are those variables that store an integer without decimals. variables are of type int IntegerPej are integers -10, 5, 23000 Example /* using integers */ #include int main (void) { /* declare the variable age as of integer type */ int age ; /* assignment of an integer value to the variable */ age = 35; /* show age by screen */ printf ("My age is% d.", age); return 0; }

Names of variables The names we can give to variables is a combination of numbers and letters. Variables can not start with a number

Pej. Var1, age, name55Integer Character variables Are those variables that store a character Characters varibles are of type char pej car = 'A'; Real Variables These are variables that can store numbers with decimals. The decimal point is expressed with. (not with, as in Spanish) Real variables are of type float pej 2.9 34.89 Example /* using real */ #include int main (void) { /* declare variable as an integer value */ float myvariable; /* assignment of a real value to the variable */ myvariable = 12.75; /* display the variable by screen */ printf ("My variable is% f.", myvariable); return 0; }

13.- Mathematical operations Assignment To assign a value to a variable we can use variable = value; Operations +, -, *,/ pej sum = var1 + var2; subtraction = value - 10; product = 20 * 22; division = 12.2/2.5;

14.- Conversion of types Implicit conversion If in an arithmetic expression there is a real this is converted to a real value pej float vreal; int ventera; ventera = 5; vreal = ventera * 10.5; Explicitly conversion Sometimes for clarity in the code we can force conversion from one type to another pej float vactual; int ventera; ventera = 5; vreal = (float) ventera * 10.5;

15.- Example. Calculation of prices with VAT /* vat.c */ int main (void) { /* declare variables */ float price_less; float price_with_vat; int vat; /* assignment of values, request of data to the user */ printf ("Enter the price without VAT:"); scanf_s ("% f", & price_less); printf ("\nEnter the vat to apply:"); scanf_s ("% d", & vat); price_with_iva = price_less * vat/100; /* show data on screen */ printf ("\nThe price with VAT is% .2f \n", price_with_vat); return 0; } First we declare the variables that we are going to use, price_less and price_with_vat as real and VAT as integer. Then we ask the user to enter the price values without VAT and VAT. To request a data to the user we can use the function scanf_s or scanf depending on the compiler version. Once we request the data, we calculate the price with VAT and show it on the screen.

16.- Making decisions In this section we will discuss how we can make decisions to define the flow of our program. We will learn the different sentences in C to make choices depending on conditions.

17.- Logical comparisons In our programs we will have to make decisions about choosing between several options, decide which code to execute depending on a comparison between values. For this the C language provides us with several sentences to choose the execution of some instructions or others depending on evaluations . The if statement Used to evaluate expressions and if it is true to execute the next block of instructions. E.g. Suppose we have to write on the screen if your age is less than or greater than 20. int age age = 26; if (age = 20) printf ("older age 20 ...");

The if - else statement Same as the if statement but if the expression to evaluate is missing, the elseblock is executed Eg. Another way to code the previous example is with the if-else statement

int age age = 26; if (age = 15 && age 18)) { printf ("you are a minor ..."); }

19.- Selecting options If we are considering selecting an option of several possible, we can do it in two ways . with if-else blocks . with the switch Eg. To show on screen if you are 20.30 or 40 years old. /* options */ #include int main (void) { /* declare variables */ int age; /* assignment of an integer value to the variable */ age = 35; /* select options with if-else */ printf ("Age with if-else ... \n"); if (age == 20) printf ("I am 20 years old."); else if (age == 30) printf ("I am 30 years old."); else if (age == 40) printf ("I am 40 years old."); else

printf ("Age indeterminate ...."); /* select options with switch */ printf ("\nAge with switch ... \n"); switch (age) { case 20: printf ("I am 20 years old."); break; case 30: printf ("I am 30 years old."); break; case 40: printf ("I am 40 years old."); break; default: printf ("Indeterminate age ...."); } return 0; }

20.- Example: Basic calculator Problem definition Write a basic calculator. The user will enter the operation in the form x op y and the computer will show the result of the operation. e.g. 10.2 + 5.5 20.8-2.5 Definition of the algorithm . we must define two variables, number1 and number 2 and the operation to be performed (+, -, *,/) . the user will be asked for the numbers and the operation in x and p format . the program will calculate the result of the operation and display it on the screen

/* calculator */ #include "pch.h" #include int main (void) { //operands float number1 = 0.0; float number2 = 0.0; /* operation +, -, *,/*/ char operation = 0; printf ("\nEnter the operation ... \n"); scanf_s ("% f", & number1);

scanf_s ("% c", & operation, 1); scanf_s ("% f", & number2); /* calculate the result */ switch (operation) { case '+': printf ("Result:% f \n", number1 + number2); break; case '-': printf ("Result:% f \n", number1 - number2); break; case '*': printf ("Result:% f \n", number1 * number2); break; case '/': if (number2 == 0) printf ("Division by zero. \n"); else printf ("Result:% f \n", number1/number2); break; default: printf ("\n \nOperation not allowed ... \n"); break; } return 0; }

21.- Advanced topics. Loops In the next section on how to implement repetitions in our code. We will define what the arrays are and finally we will treat the text strings. Loops Sometimes we are faced with the situation of having to repeat an action a number of times or until a condition is met. In C the repetition of a series of actions is called Loop and can be of several types Loop For It is used to repeat a number of times an action (example loopfor.c) Eg. Show screen numbers from 1 to 10 /* loopfor */ #include int main (void) { int i; for (i = 1; i