1. Home
  2. Explore
  3. Computer Science
  4. C Programming Fundamentals

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

C Programming Fundamentals

Speaker 1Speaker 2

C Programming Fundamentals

18:17
0:00-18:17
  1. Maria

    Welcome to our introduction to C. C is one of the oldest programming languages, and many modern languages are based on it. Learning its foundations can also help if you plan to study a related language such as C++.

  2. Michael

    And this course is designed to build that foundation step by step. We’ll start with the tools and simple programs, then work through data, decisions, loops, functions, structures, pointers, and files.

  3. Maria

    Let’s begin with the tools. To program in C, you need somewhere to write and save source code, and a C compiler. A basic text editor can work, but an IDE—an integrated development environment—can make writing and managing programs easier.

  4. Michael

    The course uses Code::Blocks as its IDE. On Windows, the described installer is the Code::Blocks release that includes MinGW; it installs both the IDE and a C compiler. During first startup, choose the GNU GCC compiler if Code::Blocks asks you to select one.

  5. Maria

    On a Mac, first check whether a compiler is already installed by opening Terminal and entering the command spelled C C space dash V. If that doesn’t show compiler information, the course uses the Xcode command-line tools install command, then checks again.

  6. Michael

    After that, download the Mac version of Code::Blocks, open the downloaded archive, and move the application into Applications. The key idea on either platform is that the editor helps you write code, while the compiler translates it into a form the computer can execute.

  7. Maria

    Once the tools are ready, create a console application in Code::Blocks and choose C rather than C++. The project includes a main dot C file, often with a basic program already in it.

  8. Michael

    That main function is where execution begins. When you run a C program, the computer executes the instructions inside main’s curly braces, in order. A simple instruction such as printf can display text in the console.

  9. Maria

    Before execution, the source code needs to be built, or compiled. Compilation translates the C instructions into code the computer can execute; then the built program is run. Code::Blocks offers separate build and run controls, as well as a build-and-run option.

  10. Michael

    C instructions end with semicolons. Order matters: if one printf instruction comes before another, its output appears first. The characters backslash and n represent a newline, so output can move to the next line.

  11. Maria

    That means even a little drawing made from slashes, bars, and underscores is a program: it’s a sequence of print instructions whose order determines the shape on screen. As you learn more instructions, you can combine them into more capable programs.

  12. Michael

    Next up are variables. A variable is a named place to store information, which is useful when a program needs to reuse or change a value. Instead of updating a character’s name in many lines of a story, store it once and refer to that variable wherever needed.

  13. Maria

    When you declare a variable, you specify its type and its name. For a whole-number age, you might declare an int called character age. For a name, you can use an array of char values, written with square brackets, to hold a sequence of characters.

  14. Michael

    You can assign an initial value when declaring a variable, and later assign a different value. That lets a program update information as it runs—for example, changing a character’s age partway through a story.

  15. Maria

    C’s basic data types in this introduction are int for whole numbers, double for decimal numbers, and char for a single character. A character value uses single quotation marks; a char holds just one character.

  16. Michael

    For a sequence of characters—a string—you use char with square brackets and double quotation marks around the text. In C, that string is an array of characters, so it behaves differently from a simple int or double variable.

  17. Maria

    printf displays output, and format specifiers let it include values as well as fixed text. Percent d is used for an integer, percent f for a decimal value, percent s for a string, and percent c for a single character.

  18. Michael

    The values to insert go after the quoted format string, separated by commas, and they line up in order with the specifiers. So if a sentence has a percent s followed by a percent d, provide the string first and the integer second.

  19. Maria

    You can use the same idea with variables. A format specifier acts as a placeholder, and printf inserts the value of the corresponding variable when the program runs. That’s how the story can show the current name and age without repeating those values in every sentence.

  20. Michael

    Numbers can also be used in calculations. C supports addition, subtraction, multiplication with an asterisk, and division with a forward slash. You can perform those operations with literals or with values stored in variables.

  21. Maria

    Pay attention to the types involved. An operation between an integer and a decimal number produces a decimal result, while arithmetic with two integers produces an integer. So five divided by four as integer arithmetic gives one; to retain a decimal result, use a decimal operand and print a decimal.

  22. Michael

    C also offers math functions. The course examples include pow for raising a number to a power, sqrt for a square root, ceil for rounding up, and floor for rounding down. For example, pow with two and three gives eight, and sqrt of thirty-six gives six.

  23. Maria

    Comments are notes in the source code that C ignores when it runs the program. The multi-line form starts with a slash and asterisk and ends with an asterisk and slash. Comments can explain code or temporarily disable a line without deleting it.

  24. Michael

    Use them thoughtfully. A comment is useful when it clarifies something, but the course recommends avoiding unnecessary comments that clutter the program.

  25. Maria

    A constant is a value that should not be changed during the program. Put the keyword const before the type when declaring a constant variable; trying to assign it a new value causes an error.

  26. Michael

    The course also notes a naming convention: constant variable names are often written in uppercase, with underscores between words. That convention isn’t required, but it makes constants easier to recognize.

  27. Maria

    Programs can also get information from users. A common pattern is to print a prompt, declare a variable to hold the answer, use scanf to read it, and then use printf to respond.

  28. Michael

    For scanf, the format string describes the input type. Use percent d for an integer, percent lf for a double, and percent c for a character. When storing those inputs in an ordinary numeric or character variable, place an ampersand before the variable name.

  29. Maria

    Strings are a special case. A char array needs enough space to hold the input, and the course’s scanf example uses percent s without an ampersand. But scanf with percent s reads only up to whitespace, so a name like John Smith is read as John.

  30. Michael

    To read a whole line of text, the course introduces fgets. Give it the destination array, its capacity, and stdin, which means standard input. That lets the program read a line containing spaces, though the newline from pressing Enter may be included too.

  31. Maria

    Those pieces are enough to make a simple calculator. Read two numbers, store them in variables, add them, and print the result. If you want decimal calculations, declare the numbers as double and use scanf’s percent lf format for each input.

  32. Michael

    The example calculator doesn’t validate every possible input. If a user enters text where a number is expected, the program won’t behave as intended. Input checking is something to improve as you learn more.

  33. Maria

    A related exercise is a Mad Libs game. Create character arrays for the user’s color, plural noun, and celebrity, prompt for each value, and use percent s placeholders to weave those answers into a story.

  34. Michael

    That example also makes scanf’s whitespace behavior visible. A two-word celebrity name is split at the space, so the course shows one workaround: read a first name and a last name separately, and place both in the story.

  35. Maria

    Now let’s organize more data with arrays. A regular variable holds one value; an array holds multiple values of the same type. For example, an integer array can contain a list of numbers under one name.

  36. Michael

    You can initialize an array with braces and comma-separated elements. Each element has an index, and C starts indexing at zero: the first item is at index zero, the second at index one, and so on.

  37. Maria

    Use the array name followed by square brackets containing the index to access an element. You can print that element, or assign a new value to it the same way you would update a variable.

  38. Michael

    If you don’t supply the elements when declaring an array, specify its capacity in the square brackets. That tells C how many items it can hold; you can then assign values to particular indexes.

  39. Maria

    And strings connect directly to this idea: a string is an array of characters. That’s why character arrays are used for names, phrases, and other text.

  40. Michael

    Functions help you package code that performs a specific task. The main function is itself a function and is the one the program starts with. To use another function, call it by name with parentheses.

  41. Maria

    A function declared with void doesn’t return information. It can still perform a task, such as printing a greeting. Calling that function from main runs the code inside it, then execution returns to where the call was made.

  42. Michael

    Functions can also accept parameters—values supplied by the caller. A greeting function might take a name, then print a greeting using that name. You can provide multiple parameters, such as a name and an age, as long as the call supplies the expected values in order.

  43. Maria

    A function’s return type describes the value it gives back. To make a function that cubes a number, for instance, declare it to return a double, accept a number as a parameter, calculate the cube, and use return to send the answer back.

  44. Michael

    The return statement also ends that function immediately. Code after it in the same function won’t run. And in the course’s examples, a function is either defined before it’s called or introduced earlier with a prototype containing its return type, name, and parameters.

  45. Maria

    Programs need to make decisions, and if statements let them do that. An if checks a condition: if it’s true, the code in its block runs; otherwise, an else block can run instead.

  46. Michael

    The max function is a good example. Compare two numbers, assign the larger one to a result variable, and return it. With three numbers, an if and else-if chain can test which number is at least as large as the others, then use else for the remaining case.

  47. Maria

    C offers comparison operators for these tests: less than, greater than, less than or equal to, greater than or equal to, equal to with two equals signs, and not equal to with an exclamation point and equals sign.

  48. Michael

    You can combine conditions with logical operators. With AND, both conditions must be true. With OR, at least one must be true. The exclamation point can also negate a condition, turning true into false or false into true.

  49. Maria

    That decision-making pattern becomes useful in a four-function calculator. Read two numbers and an operator character, then use an if and else-if chain to choose addition, subtraction, multiplication, or division.

  50. Michael

    When scanf reads the operator as a character, the course puts a space before percent c in the format string. If none of the recognized operators matches, an else block can display an invalid-operator message.

  51. Maria

    A switch statement is another way to compare one value against several possibilities. The example checks a letter grade and prints a different response for A, B, C, D, or F.

  52. Michael

    Each case names a value to match, followed by a colon and its code. Include break after a case’s work so execution leaves the switch instead of continuing into the next case. A default case handles values that didn’t match any listed case.

  53. Maria

    For grouped information, C provides structures, or structs. A struct lets you define a group of differently typed fields—for example, a student’s name, major, age, and GPA.

  54. Michael

    Once you’ve defined that template, you can create individual student variables and set their fields using a dot and the field name. For the character-array fields, the course uses strcpy to copy text into the name and major arrays.

  55. Maria

    You can create multiple student records from the same struct definition, each with different values. More generally, structs are useful for representing related information about an entity, such as a student, a book, or a phone.

  56. Michael

    Loops repeat code. A while loop checks its condition first, and continues executing its block as long as the condition is true. A counter that starts at one and increases each time can, for example, print the numbers one through five.

  57. Maria

    Make sure the loop’s condition can eventually become false. If the counter never changes, a condition such as index less than or equal to five remains true forever, creating an infinite loop.

  58. Michael

    A do-while loop is similar, but it runs the block once before checking its condition. That matters when you want the code to execute at least one time, even if the condition starts out false.

  59. Maria

    A guessing game shows how loops and decisions work together. Store a secret number, repeatedly ask for a guess while it’s incorrect, and print a winning message after the user guesses correctly.

  60. Michael

    You can add a guess limit with a counter. Increase the guess count after each attempt, compare it with the limit, and track whether the user has run out. Then the program can leave the loop either when the guess is correct or when no guesses remain, and report the appropriate outcome.

  61. Maria

    A for loop is a compact way to write many counter-based loops. Its parentheses contain an initialization, a condition, and an update—for example, initialize a counter, keep going while it’s less than or equal to five, and increment it each time.

  62. Michael

    That structure is particularly useful for arrays. Since an array starts at index zero, a loop can begin at zero and continue while the index is less than the number of elements. Use the index to access and process each element in turn.

  63. Maria

    Two-dimensional arrays extend the idea: each element of the outer array is itself an array. You use two sets of square brackets to select an outer element and then an element within it.

  64. Michael

    A nested loop is a loop inside another loop. For a two-dimensional array, the outer loop can move across the inner arrays, while the inner loop visits the elements in each one. Together, they can print every value in the array.

  65. Maria

    Now let’s connect variables to computer memory. When a program runs, its values are stored in memory, and each stored variable has a memory address. In everyday code, you usually access a value by its variable name.

  66. Michael

    To display a variable’s address, put an ampersand before its name and use percent p in printf. The result is shown as an address, rather than the variable’s stored value.

  67. Maria

    That leads to pointers. A pointer is a value that represents a memory address. You can declare a pointer using an asterisk with its type, and use the ampersand operator to give it the address of a variable.

  68. Michael

    For example, an int pointer can hold the address of an int variable. The same idea applies to pointers associated with doubles and chars. The pointer’s type corresponds to the type of value at the address it refers to.

  69. Maria

    To dereference a pointer—to access the value at the address it holds—put an asterisk before the pointer name. If it points to an integer variable containing thirty, dereferencing it gives you that integer value, not the address.

  70. Michael

    Finally, C can work with files. The course uses a file pointer and fopen to open a file, giving the filename and a mode. The modes introduced here are r for reading, w for writing, and a for appending.

  71. Maria

    With w, the program can create a file or overwrite an existing one. The example uses fprintf, which works much like printf but writes to the file pointer. That makes it possible to write lines of employee information into a text file.

  72. Michael

    With a, new information is added to the end of the file instead of replacing what’s already there. The example prints a newline before adding another employee so the new entry starts on its own line.

  73. Maria

    When you’re finished working with a file, close it with fclose and pass it the file pointer. Closing is part of the basic workflow for reading or writing files.

  74. Michael

    For reading, open the file with r. The course uses fgets to read a line into a character array, with the array, its capacity, and the file pointer as arguments.

  75. Maria

    Each call reads the next line, so calling fgets again advances through the file. You can then print the line or otherwise use the information it contains.

  76. Michael

    And that gives us a broad foundation: C programs are ordered instructions; variables and data types hold information; functions organize tasks; decisions and loops control what happens; arrays and structs organize data; pointers refer to addresses; and file functions let programs save and read information.

  77. Maria

    Exactly. The goal is not to stop at these first examples, but to have the core ideas you can build on. Try the examples, change values, and explore how each concept behaves in a small program of your own.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent