Friday, December 9, 2022

Introduction to C


An Introduction to C: A Coding Language


Hello! Welcome to C: A Coding Language!




This website provides a solid basis of the basics of C/C++, one of the most user-friendly and adaptable coding languages for beginners. The creators of these modules wanted to provide users an easy-to-use, practical, and fun environment to learn code.


The topics covered in this tutorial include Downloading C on Windows, Variables, Conditional Statements, and Plotting. Each tutorial gives in-depth tips and tricks, as well as advice on how to best navigate the language of C.


The language C/C++ is one of the easiest programming languages for beginners first learning code. Some of the largest uses of the language C/C++ include technology software interfaces, video games, and the application of engineering ideas and principles to everyday advancements.


Happy Coding!







Thursday, December 8, 2022

Downloading C on Windows

How to Download C on Windows



If you would like a video tutorial walking you step-by-step through how to download C on Windows, follow this link!

https://arizona.zoom.us/rec/share/sGm-awvyhJKseLMeqShXYtpqGBeptCR049OhoW8030tO2_op6oZJDoBEMBdFKWM-.gN73LpbIQC8Um1RF?startTime=1670620067000

Installing C/C++ on Your Computer

1. Open Visual Studio Code on your laptop or computer.

2. Click the icon, Extensions, on the left side of the screen. Then search C/C++ in the search bar.


3. Select Install. The installation should only take up to one minute to complete.

4. Next select File, then the "New Text File" button. Then select Save, and title your file with an appropriate label, and add ".c" at the end. This allows your file to be saved as a C/C++ file. This is a crucial step because otherwise the software will not be able to be accessed if the extension is not added to the file.




Installing Extensions and Compiler for C/C++

1. After installing the C/C++ extension, you may have noticed that there was a pop-up box, asking if you would like to install the recommended extensions for C/C++. This should pop up in the bottom right corner of the screen. Click Install

2. Next, it is time to install the compiler for C that is needed in order to run and execute the code. This tutorial will cover the installation for Windows only. For a MacBook, please find resources elsewhere, such as https://www.cs.auckland.ac.nz/~paul/C/Mac/xcode/. 

3. Follow this link to begin the installation of the compiler for Windows: https://sourceforge.net/projects/mingw.


4. After opening the page, click Download on the screen. This will begin downloading the MinGW GCC compiler.


5. Once it has finished downloading, select MinGW from your downloads and select Run. Another box should appear, and the select Install. Then select Continue. Then you will select Continue again. Then it should show a list of MinGW Installation packages.


6. Once you have reached this screen, select the boxes for both "mingw32-base" and "mingw32-gcc-g++". After you select these, you will confirm the button "Mark for Installation" for both boxes.


7. Next, click the Installation tab once more and select Apply Changes.
8. Next the box will ask if it is okay to proceed, in which you will answer Apply. This will begin more downloading.

9. After the downloading of the packages, wait until it the box says, "All changes were applied successfully; you may now close this dialogue", then select Close.

10. We have downloaded and installed the MinGW compiler, and now it is time to set the environment path. First go to your file directory and find the MinGW folder that has now been created.

11. Double click on this folder and then select bin in the folder.

12. Then copy and paste the directory path from the steps above. The path will be labeled C:\MinGW\bin. Then go to This PC, right click on This PC, then select Properties

13. Then search Advanced system settings in the search bar, and then select Environment Variables

14. Select Path under System Variables and then select Edit.

15. A popup window should show and first click New, then paste the C:\MinGW\bin in the box, and then click OK

16. To check that MinGW was fully installed, go the Command Prompt window and type ' gcc --version ', then press Enter.



Creating a Folder for C

1. First go to your file directory and select New Folder. To be concise, we recommend titling the folder C Program

2. Next go back to Visual Studio Code and select Add Folder.

3. After clicking Add Folder, select your C Program folder in the dialog box. Then select Add

4. The folder C Program should now be seen in Visual Studio. 



To ensure that the installation and downloading process was successful, let's perform a basic code! 

In this first tutorial we will write a basic function to print "Hello World!". To display the message, we will utilize the function printf.


Example 1

Input:
#include <stdio.h> 
int main()
{
printf("Hello World!") ; // printf displays what is in double quotes
return 0 ;
}

Ouput:

Hello World! 

** #include <stdio.h> communicates to the compiler to include the stdio.h file in the program. This is standard for both functions scanf() and printf(). 

** int main() is the function name and int is known as the return type of the function. The 0 return value represents that the program was successful, while the return value of 1 represents that the program was unsuccessful. 





Side Note

One of the best ways to produce organized and clean code is to comment on each of your lines of code. To comment in C/C++, the user must type // before the comment, and the text should turn green






Variables

Introduction to Variables

You can think of variables as containers to store data values. For example, you store food in containers to keep it condensed and save it for later.



There are different variable types in C. The following are a few examples of commonly used variable keywords:

int - storing integers, such as 4 or -57

float - stores floating point numbers, with decimals, such as 4.5 or -57.2

char - stores single characters, such as 'x' or 'y'
char values are always in single quotes

Declaring Variables

In order to create a variable, you have to specify the type of variable and assign the type a value:

Syntax:

type variableName = value;

  • You can name your variable whatever you would like!

Example 1.1

char myChar = 'C'; //my character is C

Example 1.2

int myInt = 32; //my integer is 32

Example 1.3

float myFloat = 32.5; //my floating point number is 32.5

Declaring a variable without assigning the value straightaway is another useful practice.

Example 1.4

int myInt; //myInt is the name of my variable
myInt = 20; //my integer is 20

You can also overwrite previous values with this function.

Example 1.5

int myInt = 32; //my integer is 32
myInt = 20; //my integer is now 20

Output Variables and Format Specifiers

C is different from other coding languages like Python because you cannot use a print function to display the valuable of a variable.

Example 2.1

int myInt = 32;
printf(myInt); //no output

C has a workaround for this called "format specifiers".

Format Specifiers are used with the print function, printf(),
and they act as a placeholder for variable values.

A format specifier starts with a % sign, followed by a character.

For the value of an int variable in C, you must use "%d" or "%i" including the double quotes inside the parentheses of the printf() function.

Example 2.2

int myInt = 32;
printf("%d", myInt); //Prints 32

For the value of a char variable in C, you must use "%c" including the double quotes inside the parentheses of the printf() function.

Example 2.3

char myChar = 'A'; //my character is A
printf("%c", myChar); //Prints A

For the value of a float variable in C, you must use "%f" including the double quotes inside the parentheses of the printf() function.

Example 2.4

float myFloat = 32.5; //my floating point number is 32.5
printf("%f", myFloat); //Prints 32.5

You can use the print feature alongside format specifiers to combine both variables and text.

Example 2.5

int myInt = 5;
printf("The lucky number is: %d", myInt); //Prints "The lucky number is: 5"

Another useful function is printing different types in a single output.

Example 2.6

int myInt = 8;
char myChar = 'Z';
printf("My favorite number is %d and my favorite letter is %c", myInt); //Prints "My favorite number is 8 and my favorite letter is Z"

Adding Multiple Variables

Adding variables is a good first look into the potential of advanced mathematics in coding languages. To add variables in C you can use the + operator.

Example 3.1

int x = 8;
int y = 2;
int sum = x + y;
printf("The sum of x and y is %d", sum); //Prints "The Sum of x and y is 10"


Declaring Multiple Variables is a more streamlined approach to achieve the same result. You can do this my using a comma-seperated list.

Example 3.2

int x = 8, y = 2, z = 10;
printf("The sum of x, y, and z is %d", x + y + z); //Prints "The Sum of x, y, and z is 20"


You are also able to assign the same value to multiple variables in C. This can be helpful to multiply an integer or float.

Example 3.3

int x, y, z;
x = y = z = 420;
printf("420 three times is %d", x + y + z); //Prints "420 three times is 1260)

Test Your Variable Knowledge

Create a Variable called x with a value of 60 and add it with another variable y with a value of 60.

Possible Answers

int x = 60;
int y = 60;
int sum = x + y;
printf("The sum of x and y is %d", sum); //Prints "The Sum of x and y is 120"

int x = 60, y = 60;
printf("The sum of x, y, and z is %d", x + y + z); //Prints "The Sum of x, y, and z is 120"

Most Streamlined Answer

int x, y;
x = y = 60;
printf("60 two times is %d", x + y); //Prints "60 two times is 120)


Hope you enjoyed learning about C and the applications of variables :)






Wednesday, December 7, 2022

Conditional Statements

Conditional Statements

Conditional statements allow the programmer to create choices.

A real world application is our internal body code performing choices. For example, if you're lacking oxygen your body might force itself to yawn. Something in your body is telling you that there is a lack of oxygen, so it performs the task of yawning in lieu of that information. 

C provides us two ways to perform choices. The first is the if statement, alongside the else statement. The second is the switch statement. 


if

An if statement checks if a condition is true. Once it determines the truth of the statement it executes the block provided in the curly brackets. 

Example 1.1

int a = 5
if (a == 5) {
    /* do something* /
}

The == represents equality in the program. It asks if two variables contain an equal value. So the code above is asking if a is equal to 5, then do something. If a was not equal to 5 then the code would not execute. Also, make sure you include the curly brackets and the indent to indicate the block as part of your if statement. 

if - else

You can append an else block to execute a different block if the if condition is false. 

Example 1.2

int a = 5
if (a == 2) {
    /* do something* /
} else {
    /* do something else* / 
}

This code is asking if a is not equal to 2, then perform the action in the else block. 

You can perform multiple else blocks by stacking multiple if statements. 

Example 1.3

int a = 5
if (a == 2) {
    /* do something */
} else if (a==5) {
    /* do something else */ 
} else {
    /* do something else again */
}


switch

A switch statement can be useful when you need to test the exact value of a variable. It tests for equality against a list of values, each called a case. 

Example 2.1

int a = 5

switch (a) {
    case 0:
        /* do something */
        break;
    case 1:
        /* do something else */
        break;
    case 2:
        /* do another something else */
        break;
}

Again, it is very important to indent properly to make sure that the switch statement is applied to each switch case.

We also need a break keyword at the end of every case to stop the next case from executing before the prior ends. 


default

Default can be put at the end of all the other cases. It is executed if no case constant-expression is equal to the initial value. If there is no default statement and no case matches, non of the statement in the switch will be executed (Microsoft). If you input more than one default clause you will get a syntax error, so don't do that!

Test Your Knowledge

int x = 10;
if (x == 5) {
    printf("The magic number is 10")

What will be printed?

Answer

Nothing! It's false. 

Thats a wrap on conditional statements. If you practiced alongside, then you will be a master coder! 


Tuesday, December 6, 2022

Plotting Basic Functions in C/C++


Plotting Basic Functions in C/C++

If you would like a video tutorial walking you step-by-step through how to install gnuplot, follow this link!

https://arizona.zoom.us/rec/share/jYW1eye3tC01Fh51Z4ZqPG1u-jqWfn6xGIVOv7AWAbjMKaiL5u03f7nGc3uAe-0e.pLHzTTMbRRYEhI3U?startTime=1670621330000

In order to plot basic functions in C/C++ through Visual Studio Code (VSC), we need a library!

• A library in programming languages is a collection of prewritten code that users can use in order to optimize their code beyond what is available in VSC. Some examples include NumPy and Matplotlib, which is commonly used in Python programming language.

• They also work for a variety of programming languages, so it is highly versatile.




https://designenterprisestudio.com

For plotting data, we will install the library called gnuplot by simply going to this link:

https://sourceforge.net/projects/gnuplot/files/gnuplot/


In the video tutorial, we go through a more extensive process, but we have put the direct link here for your convenience :)

You will then scroll down and press the folder labeled 5.2.0. This is not the latest version, so you are welcome to download the latest version with a few more bug fixes, but this one will work fine for our purposes.

Press the gp520-win64-mingw.exe towards the top of the list, which will then download and appear near the bottom left corner of your screen. Click that, and it will download. Let it to make changes to your computer, and just keep pressing Continue and Ok until the download is complete.

Once it is completely installed, you will open File Explorer on your computer, and go to Downloads, and the most recent download named gp520-win64-mingw will be there. This shows that the download was successful.

As you did when you downloaded the compiler, we need to edit the Environment Variables on your computer. You will do this by going to This PC and going to the drive, whatever it may be named on your device, and click on the folder labeled Program Files. From there, you will see a folder labeled gnuplot, and open that. As before, open the bin folder, and go to the bar above it and copy the property name in its entirety.

Go back to This PC, and right click anywhere on there without an icon being selected, and open Properties. In the settings search bar, type Advanced System Settings and select View Advanced System Settings.

A pop up will appear, and you will then press Environment Variables. Under System Variables (the most bottom box), select Path and then Edit. Another pop up will appear, and you will press New and paste the property name you copied from earlier, and then press Ok.

At this point, your computer should now recognize gnuplot! In order to test that, in the search bar for your computer, type in Command Prompt and open it. A black box pop up will appear, and you will type gnuplot right where it wants you to type when it first opens. Press Enter on your keyboard, and if there is no error, gnuplot properties will show up, showing your computer recognizes it.

Congratulations, you have successfully downloaded and installed gnuplot onto your device! Let's test out some simple functions to see if it plots graphs.

After you have typed gnuplot and pressed Enter, after gnuplot>, type in plot sin(x)/x, making sure to have the parentheses there. Press Enter on your keyboard, and you should have a pop up like the one below show up.




One thing that is important to note is that plotting data is pretty difficult in C/C++ and complicated compared to plotting data on other programs such as Excel or MatLab. Plotting in C/C++ works best for basic functions such as trigonometric and x. Probably the most effective use for plotting in C/C++ is the ability to hover your cursor over any point on the curve and be able to have precise x and y coordinates pop up in the far left bottom corner of the graph window. You can also change where you are looking into on the graph by zooming in and out of it using your mouse. Plotting data is possible by having a text file or a data file created in C/C++, but that is far beyond a beginner's ability, and can be done faster and easier through Excel.


Some Extra Practice

Mess around with different elementary functions, and altering those from standard conditions. Try plotting:

cos(x)

(x+2)-4

cos(x)/x

10sin(x)

7x+9

Also, find the coordinates of the top of the third peak on the graph sin(x)/x


Answers

Syntax -


gnuplot>plot cos(x)


Graph -




Syntax -


gnuplot>plot (x+2)-4


Graph -






Syntax -


gnuplot>plot cos(x)/x


Graph -






Syntax -


gnuplot>plot sin(x)*10


Graph -






Syntax -


gnuplot>plot (x*7)+9


Graph -





Coordinates of the top of the third peak on the graph sin(x)/x -

x = 7.69321

y= 0.127998

See! You can see the x and y coordinates in the bottom left corner of the window by hovering over the top of the third peak!