C Video Tutorial

C Video TutorialWelcome to part 1 of my C Video Tutorial! I have been getting this request constantly lately so I decided to cover the C programming language in a fast and complete tutorial series. It will probably be complete by the end of the weekend!

I cover: Comments, #include, #define, Global Variables, main(), char, int, long int, float, double, printf(), Escape Sequences, %d, %ld, %f, %c, %s, Character Arrays (Strings), strcpy, scanf(), Math Functions, Order of Operations, Math Shortcuts, Casting and more…

If you like videos like this it helps to tell Google+ with a click here

Windows users have many C compilers available for use. I prefer to use MinGW-builds because of the ease of installation.

Here is a great tutorial on how to install MinGW.

How to Install the Latest C Compiler on Mac

It is very easy to install GCC 4.8.1 on a Mac if you have Mac Ports installed. Here are the steps to set everything up:

1. Go to MacPorts and install it by downloading the DMG and installing it. Make sure you pick the right version based on your operating system version.

2. Open your Mac Terminal ( Applications – Utilities – Terminal )

3. Update MacPorts by typing this in the terminal sudo port selfupdate

4. Install GCC 4.8 by typing this in the terminal sudo port install gcc48 ( This can take a while to install )

5. Now change the default version of GCC by typing this in the terminal sudo port select –set gcc mp-gcc48

6. Now type this in the terminal hash gcc

7. Test if you are using the new version of GCC by typing this in the terminal gcc -v

If you see version 4.8 in what follows, congratulations you have the updated version of GCC and you are ready to start writing C11 programs.

Code From the Video

/* This is a multi-line comment
   Always comment as you write code*/

// Single line comment

// Provides you with printf() among other functions
// When the program is compiled the code between the brackets
// will be loaded here

#include <stdio.h> // For printf, scanf
#include <string.h> // For strcpy

// You define constants with define
// Tells the compiler to replace MYNAME with what is provided

#define MYNAME "Derek Banas"

// Every program must have a main function
// The main function is where the computer starts executing your code
// If you have any other functions that aren't called from main
// they will never execute

// This is a global variable that is available in every function
// in this program

int globalVar = 100;

main()
{
	// Variables are boxes in memory that save important data
	// A variable name must start with a letter, but then can
	// contain numbers, letters or underscores

	// A char can hold any of 256 single characters
	// All characters are surrounded by apostrophes '
	// If you save a number as a char it can't be used for calculating

	char firstLetter = 'D';

	// An int can contain any whole number positive or negative
	// Between -32,768 and 32,767

	int age = 38;
	
	// Use a long int if you need to use a number larger or smaller
	// then is provided by an int
	
	long int superBigNum = -32767000;

	// A float is a number with a decimal positive or negative

	float piValue = 3.14159265359;
	
	// A double is used when you need a number bigger then float
	
	double reallyBigPi = 3.1415926535897932384626433832795028841971;
	
	printf("\n");

	// Most all C function names contain no uppercase letters
	// printf() prints to screen the string inside of quotes
	// \n tells the screen to skip to the next line
	// Escape Sequences: \t - tab, \\ - backslash, \" - Quote

	printf("This will print to screen\n\n");

	// %d is a conversion character that inserts an int into your output

	printf("I am %d years old\n\n", age);
	
	// %ld is a conversion character for long ints
	
	printf("Big Number %ld\n\n", superBigNum);

	// %f is a conversion character for floats and doubles
	// You can define the number of decimal places as well
	// Size goes from -3.4 * 10^38 to 3.4 * 10^38

	printf("Pi = %.5f\n\n", piValue);
	
	// As you can see the computer representation of a float
	// is imprecise. If you need precision it is best to store
	// decimals as ints
	
	printf("Big Pi = %.20f\n\n", reallyBigPi);
	
	// %c is the conversion character for chars
	
	printf("The first letter of my name is %c\n\n", firstLetter);
	
	// %s is used for strings
	
	printf("My name is %s\n\n", "Derek");
	
	// To create a String you instead create char arrays
	// Every char array has a \0 String Terminator as the last 
	// character, so always make your char arrays at least 1
	// character longer then you need
	
	char myName[12] = "Derek Banas";
	
	// You could also do this char myName[] = "Derek Banas";
	
	printf("My name is %s\n\n", myName);
	
	// You can't assign a new value to a char array
	// You would use strcpy for that
	
	strcpy(myName, "Bob Smith");
	
	printf("My name is %s\n\n", myName);
	
	// scanf() is used to get input from the user
	// You must use the & ampersand before the
	// variable unless you're using %s
	
	char middleInitial;
	
	printf("What is your middle initial? ");
	
	scanf(" %c", &middleInitial);
	
	// You can only except more then one value if you
	// define exactly what you expect to get
	
	char firstName[30], lastName[30];
	
	printf("What is your name? ");
	
	scanf(" %s %s", firstName, lastName);
	
	printf("Your name is %s %c %s\n\n", firstName, middleInitial, lastName);
	
	
	
	// You can also except a / if you know the user will enter it
	
	int month, day, year;
	
	printf("Whats your birth date? ");
	
	scanf(" %d/%d/%d", &month, &day, &year);
	
	printf("Birth Date %d/%d/%d\n\n", month, day, year);
	
	// C Programming Math
	// +, -, *, /, and sometimes % (% only with ints)
	
	int num1 = 12, num2 = 15, numAns;
	
	float decimal1 = 1.2, decimal2 = 1.5, decimalAns;
	
	printf("Integer Calculation %d\n\n", num2 / num1);
	
	printf("Float Calculation %f\n\n", decimal2 / decimal1);
	
	printf("Modulus %d\n\n", num2 % num1);
	
	// Use parentheses when needed
	// Order of Operations
	// Parentheses
	// - Negative Sign, ! Not, ++ Increment, -- Decrement
	// * Multiplication, / Division, % Modulus
	// + Addition, - Subtraction
	// Relational Operators : <, >, <=, >=
	
	printf("Without Parentheses %d\n\n", 3 + 6 * 10);
	
	printf("With Parentheses %d\n\n", (3 + 6) * 10);
	
	int randomNum = 1;
	
	// There are shortcut ways to perform calculations
	// +=, -=, *=, /=, %=, ++, --
	
	printf("1 += 2 : %d\n\n", randomNum, randomNum += 2);
	
	// We didn't do it this way because the addition takes
	// place first 
	
	printf("%d += 2 : %d\n\n", randomNum, randomNum += 2);
	
	// ++ and -- work differently depending on where they are
	
	int exNum = 1;
	
	printf("++%d : %d\n\n", exNum, ++exNum);
	
	exNum = 1;
	
	printf("%d++ : %d\n\n", exNum, exNum++);
	
	// If you ever need to cast one data type to another
	// just put (dataType) before it to cast
	
	int numberEx = 12;
	
	float numberEx2 = 1.234;
	
	int numberEx3 = numberEx / numberEx2;
	
	printf("numberEx / numberEx2 : %f\n\n", (float) numberEx3);

	return 0;
}

38 Responses to “C Video Tutorial”

  1. Raj says:

    I am currently watching your Java related videos which are awesome, I cant thank you enough. I am trying to get into BigData/Hadoop programming and hence learning Java.

    Not sure if this is a lot to ask but I’ll ask anyway. Do you plan to make videos on Java MapReduce for Hadoop Programming?

    • Derek Banas says:

      Thank you :) Im happy that you are enjoying the. I don’t have the capability to properly cover a topic like Hadoop. Sorry, but I’m not at a university. I have to stick with the simple tools at hand.

    • Steve says:

      Hi Raj,

      for Hadoop check these out:

      cloudera intro on youtube you can also check out their resources at the end, they’ve got some tutorials and free trials for education purposes

      a Yahoo tutuorial , it could be useful

      and of course Apache’s stuff

      you will need huge data sets with plenty of comodity hardware to feel the power of hadoop its designed specifically to deal with Big Data. If you got one computer scanning three text files for a string, it may take you ages using Hadoop, since it is built to divide the work on tera- even petabytes of data between thousands of computers and it would take you some minutes to do so, whereas a year if you used one computer. What Hadoop would do is calculate how to distribute the problem between the different machines.

      Hope that helps

  2. abc says:

    What about C# will you cover it?

  3. w3ccode says:

    Thank you so much!I have learned from your java tutorial,and could you make some C++ video tutorial?

  4. Steve says:

    Hi Derek,

    you did not use ‘&’ when taking the input for your name, I suppose the string thingy is in play here or is it because it knows that arrays are always refered to by their address?

    scanf(” %s %s”, firstName, lastName);

    I truly appreciate this wonderful tutorial!

  5. Rad says:

    Hi Derek Sir,
    I just started learning C from your videos.
    Would you like to say on how to go on with the languages.
    I am 15 years of age. :D

    I truly appreciate this wonderful tutorial.

    • Derek Banas says:

      Hi, Thank you very much :) I plan on uploading another C tutorial tomorrow. I’ll continue until I’ve covered most everything on the C language. Thank you for visiting my website.

  6. Atila says:

    Hi Derek. Thank you for these very nice, educative C video tutorials. I really enjoyed watching them. I’ve been planning to ask you a question. Are you going to be making similarly structured C++ video tutorials, too, in the future? I’m repeating many C++ language constructs and learning some advanced topics like those different STL containers and those important search and sort algorithms and I’ve been wondering whether you will be making C++ video tutorials including the new C++11 features as well? I noticed that you described C’s int variables as 16-bit long in size. I believe an int variable is 32 bit long and its signed by default ( Double Word ) on most computer architectures and compilers nowadays. I learned in a book that the exact size of an int variable depends on the target computer architecture you are compiling your program for and it’s usually compiled into a 32-bit (4 bytes) memory value by most of today’s popular and widely used compilers. I may be wrong about this, but weren’t int variables compiled into 16bit memory values many years ago when processors were based on the 16bit cpu architecture?

    • Derek Banas says:

      Yes I will definitely cover C++. Yes I used the 16 bit int as an example to explain later in the tutorial on how bits and bytes work. When i made this I should have mentioned what I was planning. I have planned this tutorial from the beginning to be more like an exploration of the C language rather then as a list of features. Basically this tutorial is an experiment. I always improve at making tutorials when I experiment like this. Sorry if I confused you. Always feel free to ask questions

  7. Sawyer Scater says:

    Hi Derek. Thank you for your video I’m going to take a class this Fall 2013. this video has helped me and I’m double sure i will be great in class and in career.

  8. abdullah says:

    please can you tell me what is the different between c and objective c

  9. Ethan says:

    Hi, thanks for the videos. Thought they’d be difficult to follow with such a fast pace, but you explain everything so simply that it doesn’t matter :)

    Unfortunately, I have a problem. I’ve managed to install GCC just fine (from what I can tell), but compiling a “Hello, world!” program I copied from online to test it gives the following output:

    ———

    hw.c:1:19: fatal error: stdio.h: No such file or directory
    #include

    compilation terminated

    ———

    There’s a little arrow pointing to the space next to “” if that means anything. I know I set the path up correctly so I doubt that’s an issue. The code is copied from here: http://groups.engin.umd.umich.edu/CIS/course.des/cis400/c/hworld.html

    Is there any way you can help me? I really want to get into this while I’m still in a motivated mood. Thanks!

  10. lolol says:

    will you make any csharp gui and database videos?
    also some database tutorials could be good.

  11. Tony says:

    Hi Derek, I followed your step for installing C on my mac, but it doesn’t work, here is the terminal output. I’ve tried to reinstall xcode and redownloaded macport like 3 times. But nothing works. i really want to have the latest version of C!! Thank you so much for reading this

    My laptop info: Software Mac OS X Lion 10.7.5 (11G63) Processor 2 GHz Intel Core i7

    The following is terminal output after installed macport:

    Jiecaos-MacBook-Pro:~ TonyWang$ sudo port selfupdate
    Password:
    —> Updating MacPorts base sources using rsync
    MacPorts base version 2.2.1 installed,
    MacPorts base version 2.2.1 downloaded.
    —> Updating the ports tree
    —> MacPorts base is already the latest version

    The ports tree has been updated. To upgrade your installed ports, you should run
    port upgrade outdated
    Jiecaos-MacBook-Pro:~ TonyWang$ sudo port install gcc48
    —> Computing dependencies for gcc48
    —> Cleaning gcc48
    —> Scanning binaries for linking errors: 100.0%
    —> No broken files found.
    Jiecaos-MacBook-Pro:~ TonyWang$ sudo port select –set gcc mp-gcc48
    Warning: The ‘set’ command only expects two arguments. Extra arguments will be ignored.
    Selecting ‘gcc’ for ‘–set’ failed: The specified group ‘–set’ does not exist.
    Jiecaos-MacBook-Pro:~ TonyWang$ hash gcc
    Jiecaos-MacBook-Pro:~ TonyWang$ gcc -v
    Using built-in specs.
    Target: i686-apple-darwin11
    Configured with: /private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/src/configure –disable-checking –enable-werror –prefix=/Applications/Xcode.app/Contents/Developer/usr/llvm-gcc-4.2 –mandir=/share/man –enable-languages=c,objc,c++,obj-c++ –program-prefix=llvm- –program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ –with-slibdir=/usr/lib –build=i686-apple-darwin11 –enable-llvm=/private/var/tmp/llvmgcc42/llvmgcc42-2336.11~182/dst-llvmCore/Developer/usr/local –program-prefix=i686-apple-darwin11- –host=x86_64-apple-darwin11 –target=i686-apple-darwin11 –with-gxx-include-dir=/usr/include/c++/4.2.1
    Thread model: posix
    gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)
    Jiecaos-MacBook-Pro:~ TonyWang$

  12. Hermes says:

    Hey Derek I noticed that when you make a change in the text wrangler window it automatically compiles into your terminal window. Is there a way to do this on a windows?

    Im using on windows 8 using notepad++ and the windows cmd.

    Thanks

  13. Sean says:

    D: Im kinda new to this and I don’t know what went wrong this is when I did step 4.

    Error:
    Error: No Xcode installation was found.
    Error: Please install Xcode and/or run xcode-select to specify its location.
    Error:
    Warning: xcodebuild exists but failed to execute
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: Xcode does not appear to be installed; most ports will likely fail to build.
    —> Computing dependencies for gcc48Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Warning: All compilers are either blacklisted or unavailable; defaulting to first fallback option
    Error: Unable to execute port: can’t read “build.cmd”: Failed to locate ‘make’ in path: ‘/opt/local/bin:/opt/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin’ or at its MacPorts configuration time location, did you move it?

    • Derek Banas says:

      You need to download XCode to get this to work. Tell me if that doesn’t fix the problem.

      • Sean says:

        Another problem lucky me. :P Thanks

        —> Computing dependencies for gcc48
        —> Dependencies to be installed: cctools cctools-headers ld64 dyld-headers libunwind-headers llvm-3.3 libffi llvm_select cloog gmp isl autoconf m4 perl5 perl5.12 gdbm gettext expat libiconv gperf llvm-gcc42 gcc_select ncurses xz automake libtool libgcc libmpc mpfr
        —> Fetching archive for cctools-headers
        —> Attempting to fetch cctools-headers-845_0.darwin_13.noarch.tbz2 from http://packages.macports.org/cctools-headers
        —> Attempting to fetch cctools-headers-845_0.darwin_13.noarch.tbz2 from http://lil.fr.packages.macports.org/cctools-headers
        —> Attempting to fetch cctools-headers-845_0.darwin_13.noarch.tbz2 from http://mse.uk.packages.macports.org/sites/packages.macports.org/cctools-headers
        —> Fetching distfiles for cctools-headers
        —> Attempting to fetch cctools-845.tar.gz from http://ykf.ca.distfiles.macports.org/MacPorts/mpdistfiles/cctools-headers
        —> Attempting to fetch cctools-845.tar.gz from http://opensource.apple.com/tarballs/cctools/
        —> Verifying checksums for cctools-headers
        —> Extracting cctools-headers
        —> Configuring cctools-headers
        —> Building cctools-headers
        —> Staging cctools-headers into destroot
        Error: org.macports.destroot for port cctools-headers returned: command execution failed
        Error: Failed to install cctools-headers
        Please see the log file for port cctools-headers for details:
        /opt/local/var/macports/logs/_opt_local_var_macports_sources_rsync.macports.org_release_tarballs_ports_devel_cctools-headers/cctools-headers/main.log
        Error: The following dependencies were not installed: cctools cctools-headers ld64 dyld-headers libunwind-headers llvm-3.3 libffi llvm_select cloog gmp isl autoconf m4 perl5 perl5.12 gdbm gettext expat libiconv gperf llvm-gcc42 gcc_select ncurses xz automake libtool libgcc libmpc mpfr
        To report a bug, follow the instructions in the guide:
        http://guide.macports.org/#project.tickets
        Error: Processing of port gcc48 failed

        • Sean says:

          Oh I also got mavericks to download Xcode and I also downloaded MacPorts for Maverick just in case that means anything :)

        • Derek Banas says:

          Take a look at this post for a solution http://trac.macports.org/ticket/36931 Tell me if that doesn’t solve it.

          On a side note, as a Mac user I have found it is bad to upgrade OS X especially when the OS first comes out. I’m still using 10.7 because they have moved more towards providing tools for the general public while destroying tools that many developers depend on. That is just my opinion for what it may be worth?

  14. Kel says:

    Hey Derek,

    I see you have a set-up for running C in eclipse for a MAC. I am having trouble running my build/launcher on my eclipse when i want to test my programming. Any recommendations or websites on how to specifically set this up on a Windows 7 64 bit?

  15. senthilnathan says:

    Hi Derek , I’m currently watching your c tutorials , it’s really awesome.

    can you make videos for data structures and algorithms?

  16. Shaun Paiva says:

    I am very new to all this type of stuff and while using text wrangler and following your video I have an error pop up that says something about a shebang line. It would be greatly appreciated if you can help.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Google+