Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

The C Programming Handbook for Beginners

.The #include part of #include is a preprocessor command that tells the C compiler to include a file.Specifically, it tells the compiler to include the stdio.h header file.Header files are external libraries.This means that some developers have written some functionality and features that are not included at the core of the C language.By adding header files to your code, you get additional functionality that you can use in your programs without having to write the code from scratch.The stdio.h header file stands for standard input-output.It contains function definitions for input and output operations, such as functions for gathering user data and printing data to the console.Specifically, it provides functions such as printf() and scanf().So, this line is necessary for the function we have later on in our program, printf(), to work.If you don't include the stdio.h file at the top of your code, the compiler will not understand what the printf() function is.Next, int main(void) {} is the main function and starting point of every C program.It is the first thing that is called when the program is executed.Every C program must include a main() function.The int keyword in int main(void) {} indicates the return value of the main() function.In this case, the function will return an integer number.And the void keyword inside the main() function indicates that the function receives no arguments.Anything inside the curly braces, {}, is considered the body of the function – here is where you include the code you want to write. Any code written here will always run first.This line acts as a boilerplate and starting point for all C programs. It lets the computer know where to begin reading the code when it executes your programs.In C programming, comments are lines of text that get ignored by the compiler.Writing comments is a way to provide additional information and describe the logic, purpose, and functionality of your code.Comments provide a way to document your code and make it more readable and understandable for anyone who will read and work with it.Having comments in your source code is also helpful for your future self. So when you come back to the code in a few months and don't remember how the code works, these comments can help.Comments are also helpful for debugging and troubleshooting. You can temporarily comment out lines of code to isolate problems.This will allow you to ignore a section of code and concentrate on the piece of code you are testing and working on without having to delete anything.There are two types of comments in C:Single-line comments start with two forward slashes, //, and continue until the end of the line.Here is the syntax for creating a single-line comment in C:Any text written after the forward slashes and on the same line gets ignored by the compiler.Multi-line comments start with a forward slash, /, followed by an asterisk, *, and end with an asterisk, followed by a forward slash.As the name suggests, they span multiple lines.They offer a way to write slightly longer explanations or notes within your code and explain in more detail how it works.Here is the syntax for creating a multi-line comment in C:Inside the function's body, the line printf("Hello, World!\n"); prints the text Hello, World! to the console (this text is also known as a string).Whenever you want to display something, use the printf() function.Surround the text you want to display in double quotation marks, "", and make sure it is inside the parentheses of the printf() function.The semicolon, ;, terminates the statement. All statements need to end with a semicolon in C, as it identifies the end of the statement.You can think of a semicolon similar to how a full stop/period ends a sentence.Did you notice the \n at the end of printf("Hello, World!\n");?It's called an escape sequence, which means that it is a character that creates a newline and tells the cursor to move to the next line when it sees it.In programming, an escape sequence is a combination of characters that represents a special character within a string.They provide a way to include special characters that are difficult to represent directly in a string.They consist of a backslash, \, also known as the escape character, followed by one or more additional characters.The escape sequence for a newline character is \n.Another escape sequence is \t. The \t represrents a tab character, and will insert a space within a string.In the previous section, you wrote your first C program:Any code you write in the C programming language is called source code.Your computer doesn’t understand any of the C statements you have written, so this source code needs to be translated into a different format that the computer can understand. Here is where the compiler you installed earlier comes in handy.The compiler will read the program and translate it into a format closer to the computer’s native language and make your program suitable for execution.You will be able to see the output of your program, which should be Hello, world!.The compilation of a C program consists of four steps: preprocessing, compilation, assembling, and linking.The first step is preprocessing.The preprocessor scans through the source code to find preprocessor directives, which are any lines that start with a # symbol, such as #include .Once the preprocessor finds these lines, it substitutes them with something else.For example, when the preprocessor finds the line #include , the #include tells the preprocessor to include all the code from the stdio.h header file.So, it replaces the #include line with the actual contents of the stdio.h file.The output of this phase is a modified version of the source code.After preprocessing, the next step is the compilation phase, where the modified source code gets translated into the corresponding assembly code.If there are any errors, compilation will fail, and you will need to fix the errors to continue.The next step is the assembly phase, where the assembler converts the generated assembly code statements into machine code instructions.The output of this phase is an object file, which contains the machine code instructions.The last step is the linking phase.Linking is the process of combining the object file generated from the assembly phase with any necessary libraries to create the final executable binary file.Now, let’s go over the commands you need to enter to compile your main.c file.In Visual Studio Code, open the built-in terminal by selecting "Terminal" -> "New Terminal".Inside the terminal, enter the following command:The gcc part of the command refers to the C compiler, and main.c is the file that contains the C code that you want to compile.Next, enter the following command:The ls command lists the contents of the current directory.The output of this command shows an a.out file – this is the executable file containing the source code statements in their corresponding binary instructions.The a.out is the default name of the executable file created during the compilation process.To run this file, enter the following command:This command tells the computer to look in the current directory, ./, for a file named a.out.The above command generates the following output:You also have the option to name the executable file instead of leaving it with the default a.out name.Say you wanted to name the executable file helloWorld.If you wanted to do this, you would need to enter the following command:This command with the -o option (which stands for output) tells the gcc compiler to create an executable file named helloWorld.To run the new executable file that you just created, enter the following command:This is the output of the above command:Note that whenever you make a change to your source code file, you have to repeat the process of compiling and running your program from the beginning to see the changes you made.In this chapter, you will learn the basics of variables and data types – the fundamental storage units that allow you to preserve and manipulate data in your programs.By the end of this chapter, you will know how to declare and initialize variables.You will also have learned about various data types available in C, such as integers, floating-point numbers, and characters, which dictate how information is processed and stored within a program's memory.Finally, you'll have learned how to receive user input in your programs, and how to use constants to store values that you don't want to be changed.Variables store different kind of data in the computer's memory, and take up a certain amount of space.By storing information in a variable, you can retrieve and manipule it, perform various calculations, or even use it to make decisions in your program.The stored data is given a name, and that is how you are able to access it when you need it.Before you can use a variable, you need to declare it – this step lets the compiler know that it should allocate some memory for it.C is a strongly typed language, so to declare a variable in C, you first need to specify the type of data the variable will hold, such as an integer to store a whole number, a floating-point number for numbers with decimal places, or a char for a single character.That way, during compilation time, the compiler knows if the variable is able to perform the actions it was set out to do.Once you have specified the data type, you give the variable a name.The general syntax for declaring variables looks something like this:Let's take the following example:In the example above, I declared a variable named age that will hold integer values.When it comes to variable names, they must begin either with a letter or an underscore.For example, age and _age are valid variable names.Also, they can contain any uppercase or lowercase letters, numbers, or an underscore character. There can be no other special symbols besides an underscore.Lastly, variable names are case-sensitive. For example, age is different from Age.Once you've declared a variable, it is a good practice to intialize it, which involves assigning an initial value to the variable.The general syntax for initialzing a variable looks like this:The assignment operator, =, is used to assign the value to the variable_name.Let's take the previous example and assign age a value:I initialized the variable age by assigning it an integer value of 29.With that said, you can combine the initialization and declaration steps instead of performing them separately:The values of variables can change.For example, you can change the value of age without having to specify its type again.Here is how you would change its value from 29 to 30:Note that the data type of the new value being assigned must match the declared data type of the variable.If it doesn't, the program will not run as expected. The compiler will raise an error during compilation time.Data types specify the type of form that information can have in C programs. And they determine what kind of operations can be performed on that information.There are various built-in data types in C such as char, int, and float.Each of the data types requires different allocation of memory.Before exploring each one in more detail, let’s first go over the difference between signed and unsigned data types in C.Signed data types can represent both positive and negative values.On the other hand, unsigned data types can represent only non-negative values (zero and positive values).Wondering when to use signed and when to use unsigned data types?Use signed data types when you need to represent both positive and negative values, such as when working with numbers that can have positive and negative variations.And use unsigned data types when you want to ensure that a variable can only hold non-negative values, such as when dealing with quantities.Now, let's look at C data types in more detail.The most basic data type in C is char.It stands for "character" and it is one of the simplest and most fundamental data types in the C programming language.You use it to store a single individual character such as an uppercase and lowercase letter of the ASCII (American Standard Code for Information Interchange) chart.Some examples of chars are 'a' and 'Z'.It can also store symbols such as '!', and digits such as '7'.Here is an example of how to create a variable that will hold a char value:Notice how I used single quotation marks around the single character.This is because you can't use double quotes when working with chars.Double quotes are used for strings.Regarding memory allocation, a signed char lets you store numbers ranging from [-128 to 127], and uses at least 1 byte (or 8 bits) of memory.An unsigned char stores numbers ranging from [0 to 255].An int is a an integer, which is also known as a whole number.It can hold a positive or negative value or 0, but it can't hold numbers that contain decimal points (like 3.5).Some examples of integers are 0, -3,and 9.Here is how you create a variable that will hold an int value:When you declare an int, the computer allocates at least 2 bytes (or 16 bits) of memory.With that said, on most modern systems, an int typically allocates 4 bytes (or 32 bits) of memory.The range of available numbers for a signed int is [-32,768 to 32,767] when it takes up 2 bytes and [-2,147,483,648 to 2,147,483,647] when it takes up 4 bytes of memory.The range of numbers for an unsigned int doesn't include any of the negative numbers in the range mentioned for signed ints.So, the range of numbers for unigned ints that take up 2 bytes of memory is [0 to 65,535] and the range is [0 to 4,294,967,295] for those that take up 4 bytes.To represent smaller numbers, you can use another data type – the short int. It typically takes up 2 bytes (or 16 bits) of memory.A signed short int allows for numbers in a range from [-32,768 to 32,767].An unsigned short int allows for numbers in a range from [0 to 65,535].Use a short when you want to work with smaller integers, or when memory optimisation is critically important.If you need to work with larger integers, you can also use other data types like long int or long long int, which provide a larger range and higher precision.A long int typically takes up at least 4 bytes of memory (or 32 bits).The values for a signed long int range from [-2,147,483,648 to 2,147,483,647].And the values for an unsigned long int range from [0 to 4,294,967,295].The long long int data type is able to use even larger numbers than a long int. It usually takes up 8 bytes (or 64 bits) of memory.A signed long long int allows for a range from [-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807]And an unsigned long long int has a range of numbers from [0 to 18,446,744,073,709,551,615].The float data type is used to hold numbers with a decimal value (which are also known as real numbers).It holds 4 bytes (or 32 bits) of memory and it is a single-precision floating-point type.Here is how you create a variable that will hold a float value:A double is a floating point value and is the most commonly used floating-point data type in C.It holds 8 bytes (or 64 bits) of memory, and it is a double-precision floating-point type.Here is how you create a variable that will hold a double value:When choosing which floating-point data type to use, consider the trade-off between memory usage and precision.A float has less precision that a double but consumes less memory.Use a float when memory usage is a concern (such as when working with a system with limited resources) or when you need to perform calculations where high precision is not critical.If you require higher precision and accuracy for your calculations and memory usage is not critical, you can use a double.Format codes are used in input and output functions, such as scanf() and printf(), respectively.They act as placeholders and substitutes for variables.Specifically, they specify the expected format of input and output.They tell the program how to format or interpret the data being passed to or read from the scanf() and printf() functions.The syntax for format codes is the % character and the format specifier for the data type of the variable.Let's take the following example:In the example above, age is the variable in the program. It is of type int.The format code – or placeholder – for integer values is %i. This indicates that an integer should be printed.In the program's output, %i is replaced with the value of age, which is 29.Here is a table with the format specifiers for each data type:Earlier you saw how to print something to the console using the printf() function.But what happens when you want to receive user input? This is where the scanf() function comes in.The scanf() function reads user input, which is typically entered via a keyboard.The user enters a value, presses the Enter key, and the value is saved in a variable.The general syntax for using scanf() looks something similar to the following:Let's break it down:Let's take a look at an example of scanf() in action:In the example above, I first have to include the stdio.h header file, which provides input and output functions in C.Then, in the main() function, I declare a variable named number that will hold integer values. This variable will store the user input.Then, I prompt the user to enter a number using the printf() function.Next, I use scanf() to read and save the value that the user enters.The format specifier %i lets the computer known that it should expect an integer input.Note also the & symbol before the variable name. Forgetting to add it will cause an error.Lastly, after receiving the input, I display the received value to the console using another printf() function.As you saw earlier on, variable values can be changed throughout the life of a program.With that said, there may be times when you don’t want a value to be changed. This is where constants come in handy.In C, a constant is a variable with a value that cannot be changed after declaration and during the program's execution.You can create a constant in a similar way to how you create variables.The differences between constants and variables is that with constants you have to use the const keyword before mentioning the data type.And when working with constants, you should always specify a value.The general syntax for declaring constants in C looks like this:Here, data_type represents the data type of the constant, constant_name is the name you choose for the constant, and value is the value of the constant.It is also best practice to use all upper case letters when declaring a constant’s name.Let’s see an example of how to create a constant in C:In this example, LUCKY_NUM is defined as a constant with a value of 7.The constant's name, LUCKY_NUM, is in uppercase letters, as this is a best practice and convention that improves the readability of your code and distinguishes constants from variables.Once defined, it cannot be modified in the program.If you try to change its value, the C compiler will generate an error indicating that you are attempting to modify a constant.Operators are essential building blocks in all programming languages.They let you perform various operations on variables and values using symbols.And they let you compare variables and values against each other for decision-making computatons.In this chapter, you will learn about the most common operators in C programming.You will first learn about arithmetic operators, which allow you to perform basic mathematical calculations.You will then learn about relational (also known as comparisson operators), which help you compare values.And you will learn about logical operators, which allow you to make decisions based on conditions.After understanding these fundamental operators, you'll learn about some additional operators, such as assignment operators, and increment and decrement operators.By the end of this chapter, you will have a solid grasp of how to use different operators to manipulate data.Arithmetic operators are used to perform basic arithmetic operations on numeric data types.Operations include addition, subtraction, multiplication, division, and calculating the remainder after division.These are the main arithmetic operators in C:Let's see examples of each one in action.The addition operator adds two operands together and returns their sum.The subtraction operator subtracts the second operand from the first operand and returns their difference.The multiplication operator multiplies two operands and returns their product.The division operator divides the first operand by the second operand and returns their quotient.The modulo operator returns the remainder of the first operand when divided by the second operand.The modulo operator is commonly used to determine whether an integer is even or odd.If the remainder of the operation is 1, then the integer is odd. If there is no remainder, then the integer is even.Relational operators are used to compare values and return a result.The result is a Boolean value. A Boolean value is either true (represented by 1) or false (represented by 0).These operators are commonly used in decision-making statements such as if statements, and while loops.These are the relational operators in C:Let’s see an example of each one in action.The equal to operator checks if two values are equal.It essentially asks the question, "Are these two values equal?"Note that you use the comparisson operator (two equal signs – ==) and not the assignment operator (=) which is used for assigning a value to a variable.The result is 1 (true), because a and b are equal.The not equal to operator checks if two values are NOT equal.The result is 1 (true), because a and b are not equal.This operator compares two values to check if one is greater than the other.The result is 1 (true), because a is greater than b.This operator compares two values to check if one is less than the other.The result is 0 (false), because a is not less than b.This operator compares two values to check if one is greater than or equal to the other.The result is 1 (true), because a is equal to b.This operator compares two values to check if one is less than or equal the other.The result is 1 (true), because a is less than b.Logical operators operate on Boolean values and return a Boolean value.Here are the logical operators used in C:Let's go into more detail on each one in the following sections.The logical AND (&&) operator checks whether all operands are true.The result is true only when all operands are true.Here is the truth table for the AND (&&) operator when you are working with two operands:Let's take the following example:The result of (10 == 10) && (20 == 20) is true because both operands are true.Let's look at another example:The result of (10 == 20) && (20 == 20) is false because one of the operands is false.When the first operand is false, the second operand is not evaluated (since there's no point - it's already determined that the first operand is false, so the result can only be false).The logical OR (||) operator checks if at least one of the operands is true.The result is true only when at least one of the operands is true.Here is the truth table for the OR (||) operator when you are working with two operands:Let's look at an example:The result of (10 == 20) || (20 == 20) is true because one of the operands is true.Let's look at another example:The result of (20 == 20) || (10 == 20) is true because one of the operands is trueIf the first operand is true, then the second operator is not evaluated.The logical NOT (!) operator negates the operand.If the operand is true, it returns false.And if it is false, it returns true.You may want to use the NOT operator when when you want to flip the value of a condition and return the opposite of what the condition evaluates to.Here is the truth table for the NOT(!) operator:Let's look at an example:The result of !(10 == 10) is false.The condition 10 == 10 is true, but the ! operator negates it so the result is false.And let's look at another example:The result of !(10 == 20) is true.The condition 10 == 20 is false, but the ! operator negates it.The assignment operator is used to assign a value to a variable.In the example above, the value 10 is assigned to the variable num using the assignment operator.The assignment operator works by evaluating the expression on the right-hand side and then storing its result in the variable on the left-hand side.The type of data assigned should match the data type of the variable.Compound assignment operators are shorthand notations.They allow you to modify a variable by performing an operation on it and then storing the result of the operation back into the same variable in a single step.This can make your code more concise and easier to read.Some common compound assignment operators in C include:Let’s see an example of how the += operator works:In the example above, I created a variable named num and assigned it an initial value of 10.I then wanted to increment the variable by 5. To do this, I used the += compound operator.The line num += 5 increments the value of num by 5, and the result (15) is stored back into num in one step.Note that the num += 5; line works exactly the same as doing num = num + 5, which would mean num = 10 + 5, but with fewer lines of code.The increment ++ and decrement -- operators increment and decrement a variable by one, respectively.Let’s look at an example of how to use the ++ operator:The initial value of the variable num is 10.By using the ++ increment operator, the value of num is set to 11.This is like perfoming num = num + 1 but with less code.The shorthand for decrementing a variable by one is --.If you wanted to decrement num by one, you would do the following:The initial value of the variable num is 10.By using the -- increment operator, the value of num is now set to 9.This is like perfoming num = num - 1.The examples you have seen so far all execute line by line, from top to bottom.They are not flexible and dynamic and do not adapt according to user behavior or specific situations.In this chapter, you will learn how to make decisions and control the flow of a program.You get to set the rules on what happens next in your programs by setting conditions using conditional statements.Conditional statements take a specific action based on the result of a comparisson that takes place.The program will decide what the next steps should be based on whether the conditions are met or not.Certain parts of the program may not run depending on the results or depending on certain user input. The user can go down different paths depending on the various forks in the road that come up during a program's life.First, you will learn about the if statement – the foundational building block of decision-making in C.You will also learn about the else if and else statements that are added to the if statement to provide additional flexibility to the program.You will then learn about the ternary operator which allows you to condense decision-making logic into a single line of code and improve the readability of your program.The most basic conditional statement in C is the if statement.It makes a decision based on a condition.If the given condition evaluates to true only then is the code inside the if block executed.If the given condition evaluates to false, the code inside the if block is ignored and skipped.The general syntax for an if statement in C is the following:Let's look at an example:In the above code, I created a variable named age that holds an integer value.I then prompted the user to enter their age and stored the answer in the variable age.Then, I created a condition that checks whether the value contained in the variable age is less than 18.If so, I want a message printed to the console letting the user know that to proceed, the user should be at least 18 years of age.When asked for my age and I enter 16, I'd get the following output:The condition (age 5).If x is greater than 5, the condition evaluates to true. And when the condition is true, the value assigned to y will be 100.If the condition evaluates to false, the value assigned to y will be 200.So, since x is greater than 5 (x = 10), y is assigned the value 100.In this chapter you will learn about loops, which are essential for automating repetitive tasks without having to write the same code multiple times.Loops allow you to execute a specific block of code instructions repeatedly over and over again until a certain condition is met.You will learn about the different types of loops, such as the for , while and do-while loops, and understand their syntax and when you should use each one.You will also learn about the break statement, which allows you to control the execution flow within loops in specific ways.A for loop allows you to execute a block of code repeatedly based on a specified condition.It's useful when you know how many times you want to repeat a certain action.The general syntax for a for loop looks like this:Let's break it down:Let's see an example of how a for loop works.Say you want to print the numbers from 1 to 5 to the console:Output:In the example above, I first initialize the loop control variable i with a value of 1.The condition i at the top of your file.To calculate the length of a string, use the strlen() function:Output:The strlen() function will return the number of characters that make up the string.Note that the result does not include the null terminator, \0.To copy one string into another one, you can use the strcpy() function.You may want to copy a string in C when you need to make changes to it without modifying it. It comes in handy when you need to keep the original string's content intact.The general syntax for the strcpy() function looks like this:The strcpy() function copies original_string into destination_string, including the null terminator ('\0').One thing to note here is that you need to make sure the destination array has enough space for the original string:Output:The strcpy() function copies the original string into an empty array and returns the copied string, which also includes the null terminator character ('\0').You can concatenate (add) two strings together by using the strcat() function.The general syntax for the strcat() function looks something like the following:The strcat() function takes the original string and adds it to the end of destination string.Make sure that the destination_string has enough memory for the original_string.Something to note here is that strcat() does not create a new string.Instead, it modifies the original destination_string, by including the original_string at the end.Let's see an example of how strcat() works:Output:To compare two strings for equality, you can use the strcmp() function.The general syntax for the strcmp() function looks like this:The strcmp() function compares string1 with string2 and returns an integer.If the return value of strcmp() is 0, then it means the two strings are the same:If the return value of strcmp() is less than 0, then it means the first word comes before the second:And if the return value of strcmp() is greater than 0, then it means the first word comes after the second one:While this handbook has covered a wide range of topics, there is still so much to learn, as programming is so vast.Once you have built a solid foundation with the basics of C programming, you may want to explore more advanced concepts.You may want to move on to learning about functions, for example. They allow you to write instructions for a specific task and reuse that code throughout your program.You may also want to learn about pointers. Pointers in C are like arrows that show you where a specific piece of information is stored in the computer's memory.Then, you may want to move on to learning about structures. They're like custom data containers that allow you to group different types of information under one name.Lastly, you may want to learn how to work with files. Working with files in C allows you to read from and write to files. This is useful for tasks like saving user data, reading configuration settings, or sharing data between different programs.These suggestions are not a definitive guide – just a few ideas for you to continue your C programming learning journey.If you are interested in learning more, you can check out the following freeCodeCamp resources:This marks the end of this introduction to the C programming language.Thank you so much for sticking with it and making it until the end.You learned how to work with variables, various data types, and operators.You also learned how to write conditional statements and loops. And you learned the basics of working with arrays and strings.Hopefully, you have gained a good understanding of some of the foundamentals of C programming, got some inspiration on what to learn next, and are excited to continue your programming journey.Happy coding! Read more posts. If this article was helpful, tweet it. Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff. You can make a tax-deductible donation here.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

The C Programming Handbook for Beginners

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×