Learning C-Programming

Dojocat for funsies

Learning Notes

Dan Gookin | LinkedIn Learning

Programming Cycle

  • Edit source code (.c file)
  • Compiled into object code (.o file)
  • Linker takes object code and combines with c lang libraries (most modern compliers do this built in)
  • Test run

Note: IDEs are used more for their bonus tools than for their need with C, the terminal compiler works from the jump.

Understanding a C Program

  • Every C program has to start with main(){}, where the function is main() and the content of the main function are in the {}
  • There are 44 keywords in the C language
  • Workhorses of C language are functions
    • functions are held in C libraries
    • linkers job is to combine the library with your program's object code, blending them together to make a program
    • to use a function in a program file you need to incorporate a header file, which defines the function
  • Operators: symbols used to manipulate data in the program
    • mathematical
    • comparison
    • assignment
    • special symbols
      • bitwise
      • unary
  • Values and Variables
    • types of values and variables
      • characters
      • integers
      • floating-point numbers (decimals)
      • memory locations
    • variables are containers for a value, it's contents can change
    • the values that go into variables are the same types of values used directly in the program
    • remember that C programs run top-down

Note: The C language uses preprocessor directives to help control program flow; the main() function is the first function executed in all programs. The main() function is by default an integer function

Simple First Program

Dan presents an example program as the first simple program to get used to, and it highlights some realities in learning programming:

  1. There are always more than one way to do things
  2. Programming is better learned through the use of multiple mediums and multiple sources
  3. Always pay attention to the logs for errors and do a little research on why, it might be a change/update in language standards issue
  4. Make sure you develop a library of resources to regularly stay connected to, even after becoming an advanced user

Dan's example first dummy.c program

int main() {
  puts ("I am no longer a dummy.");
  return(0);
}

When I ran the program the way Dan had it written, the following error came up:

dummy.c:2:3: warning: implicit declaration of function 'puts' is invalid in C99
      [-Wimplicit-function-declaration]
  puts ("I am no longer a dummy.");
  ^
1 warning generated.

So I "Googled" it, and learned one thing that I could have learned by watching the rest of the video, and one other important thing:

  1. The puts function requires a definition before it can be used, otherwise the compiler get confused
    • The definition is held in the standard I/O (input/output) header file.
    • Must include that header file in source code by using the preprocessor directive
    • #include <stdio.h> is the preprocessor directive that includes the definition for the puts function
  2. There are real syntax differences between the older standard of C called C99 and the newer standard of C called C11, so it'll be good for me to keep things like that in mind

The original program above isn't necessarily wrong because it works, but that's because the program is simple and Apple's compiler isn't mean about warnings/errors.

  • include the standard header
  • you can pass void for the arguments as there's nothing being used, or you can leave the arguments area blank (i.e. main() or main(void) are both fine)
  • if the return listed is zero, the return() statement can be removed, because return() is defaulted at zero.
Finished product looks like this:
#include <stdio.h>

int main(void) {
    puts("I am no longer a dummy.");
}
Yay! First C Program!! :)

Note: The difference between puts and print in C might have more impact than the difference between the two in other languages like Ruby, as described here.

Reminder of puts() vs printf()

Input/Output or I/O

  • Without C library output functions, the C language would just put what comes in, directly out.
    • Top examples:
      • printf()
        • unlike puts(), printf() doesn't create a new line during output unless there is an escape character as shown below
      • putchar() (put-car)
      • puts()
        • puts() puts/sends a string of text to standard output, where 'puts' is a put string, and a string is a collection of characters enclosed in double quotes.
        • the function is defined in the stdio header included at the head
Example with puts()
/*Traditional C comments are made like this...*/
#include <stdio.h>

int main()
{
    puts("Sample exercise with two lines of text");
    puts("as the output. The program runs top-down.");

    return(0);
}
Example with printf()
/*Traditional C comments are made like this...*/
#include <stdio.h>

int main()
{
    printf("Sample exercise with two lines of text\n");
    printf("as the output. The program runs top-down.");

    return(0);
}

Remember other differences as explained here

Escape Characters/Escape Sequences

Additional Reference

  • \n new line
  • \a alarm or beep
  • \b backspace
  • \f form feed
  • \r carriage return
  • \t tab (horizontal)
  • \v tab (vertical)
  • \\ backslash
  • \' single quote
  • \" double quote
  • \? question mark
  • \ooo octal number
  • \xhh hexadecimal number
  • \0 null
Examples Applied
#include <stdio.h>

int main(void) {
    //standard
    puts("I am no longer a dummy.");
    //makes noise every digit
    puts("My phone number is 4\a7\a0\a3\a3\a2\a5\a0\a2\a6\a\n");
    //output depends on compiler
    puts("Attempt at\b\b\b\bbackspace\n");
    //example of printf with new line
    printf("Hello\n");
    printf("Fancy terminal\n\n");
    //tab b/t new words, used frequently in loop based pattern printing programs
    //see: http://www.geeksforgeeks.org/tag/pattern-printing/
    puts("Hello \t horizontal tab\n");
    //using the vertical tab
    printf("Hello friends");
    printf("\v Welcome to the vertical tab\n\n");
    //carriage return character, output depends on compiler
    puts("Hello fri \r ends\n\n");
    //backslash
    printf("Ello\\Terminal\n\n");
    //single and then double quotes
    printf("\' Hello Mac\n");
    printf("\" You fancy terminal\n\n");
    //questions and exclamations
    printf("What\?!\?!\n\n");
    //OOO is one to three octal digits (0...7) meaning there must be at least one digit after `\` and maximum three.
    //Since 072 is the octal notation, first it is converted to decimal notation that is the ASCII value of the char `:` so that `SZ\072` is replaced with `SZ:13`
    char* fav_num = "SZ\07213";
    printf("%s\n\n", fav_num);
    //More of that fancy stuff but this time with hexadecimal digits
    char* initials = "S\x5a";
    printf("%s\n\n", initials);

}

The octal notation example, is a cool yet complicated little beast.

So when SZ\07213 is written, the part being translated is the 72, where 72 in the octal code system is translated to a 3a in the hex code system, which is a : character.

Thus: 72 written in octal notation as 072 is translated as :

closer look at the octal notation SZ:13

char* fav_num = "SZ\07213";
printf("%s", fav_num);

with the hexadecimal it's the same result, just more direct SZ:13

char* fav_num = "SZ\x3a13";
printf("%s", fav_num);

Format Specifiers and Placeholders

In the example above with the octal and hexadecimal notation printouts, the %s is a placeholder for the fav_num variable.

Format Specifier Characters Matched Argument Type
%c any single character char
%d, %i integer integer type
%u integer unsigned
%o octal integer (base 8) unsigned
%x, %X hex integer (base 16) unsigned
%f, %g, %G floating point number floating type
%e %E floating point number scientific notation floating type
%p address format (or pointer) void*
%s any sequence of non-whitespace characters, strings char
%% the percent sign unsigned?

So when you write printf("%s", fav_num); you are passing two arguments through printf function. The first in this example is a format specifier or placeholder and the second is the computed/compiled value of the fav_num variable, which is to be printed where the placeholder is.

Another simpler example is in the use of strings and numbers together, like this: printf("My name is Samiah, and I am %d years old", 27); Where the output will be:

My name is Samiah, and I am 27 years old

Because the printf function has two parameters, the first is the string which holds my name and the placeholder for my age, and the value of the integer that is passed in the second parameter that is my age

It's important to note that the printf function doesn't do the calculations, the C program does. The printf function merely prints the values of the calculations on the default output display

Here are some other little novelty type examples:

printf("Here are some sample values %d,%d,%d,%d,%d,%d,%d\n",1,2,3,4,5,6,7); printf("Everyone knows that 2+2=%d\n",4); printf("Everyone still knows that 2+2=%d\n",2+2);

Here are some sample values 1,2,3,4,5,6,7 Everyone knows that 2+2=4 Everyone still knows that 2+2=4

A fancy way to write the first example might be to use

char* colon="\072"
printf("Here are some sample values%s %d, %d, %d, %d, %d, %d, %d\n", colon, 1, 2, 3, 4, 5, 6, 7)

Note: you must pass a single quote for the single character value to a %c placeholder.

Links for the fancy stuff here:


C Language Variables

  • a variable is a container for a value
  • it must be declared of a specific type
  • it must have a unique name
  • it must be used within the code
  • in C, the variable type matches the variables content
    • int: integer or whole-number values
    • float: floating-point numbers
      • remember, to declare floating-point numbers, you have to add a . even if original value is whole. (i.e. 7.0 not 7)
    • char: single characters
    • C language lacks a string variable type, instead a character array is used.
  • additional keywords can be used to declare variables
    • double
    • short
    • long
    • signed
    • unsigned
  • general rules of naming variables
    • must begin with a letter or underline (letter is preferred)
    • can include numbers, letters and some symbols
    • name must be unique, with no two variable having the same name
    • variable names should not be the same as standard functions or C language keywords
      • variable values can be changed later on in the program, so using the same name would be a mess

Using one variable...

#include <stdio.h>

int main()
{
  int age = 27;
  printf("%s is %d years old.\n", "Samiah", age);
  printf("That's approximately %d months old!\n", age*12);

  return(0);
}

Result

Samiah is 27 years old.
That's approximately 324 months old!

... and then going variable nuts

#include <stdio.h>

int main()
{
  int age_years, months;
  int age_months;
  age_years = 27;
  months = 12;
  age_months = age_years*months;
  printf("Samiah is %d years old, and there are %d months in a year, so Samiah is approximately %d months old!\n", age_years, months, age_months);

  return(0);
}

Result

Samiah is 27 years old, and there are 12 months in a year, so Samiah is approximately 324 months old!

Calculating single character variables example:

#include <stdio.h>

int main()
{
  char x,y,z;
  x= 'A';
  y= x+1;
  z= y+1;

  printf("It's as easy as %c%c%c!\n",x,y,z);

  return(0);
}

Result

It's as easy as ABC!

Character I/O Functions

  • most common character i/o functions are getchar and putchar
    • getchar gets/fetches
    • putchar sends/pushes
  • although character functions, they work with integer values
  • require stdio.h header
  • functions are stream oriented
  • Note: %c is described as resent C

Example character i/o function

#include <stdio.h>

int main() {
  int c;
  printf("Type a letter: "); //window prompt for user
  c=getchar(); //collected user entry
  printf("You typed '"); //first half return statement
  putchar(c); //adding input value to return statement
  printf("'.\n'"); //final half return statement w/ input value
  return 0;
}

That last line with the three character strings, can also be provided as three putchar functions

#include <stdio.h>

int main() {
  int c;
  printf("Type a letter: "); //window prompt for user
  c=getchar(); //collected user entry
  printf("You typed '"); //first half return statement
  putchar(c); //adding input value to return statement
  putchar('\'');
  putchar('.');
  putchar('\n');
  return 0;
}

In this example, you would have the same output, but you would need to escape the single quote character or the compiler gets confused.

A more condensed version of this example, would just provide the getchar function, without the need for any putchar functions, and would display the same output

#include <stdio.h>

int main() {
  int c;
  printf("Type a letter: "); //window prompt for user
  c=getchar(); //collected user entry
  printf("You typed '%c'.\n", c); //return statement all at once
  return 0;
}

Multiple characters can also be added, like let's say a monogram example

#include <stdio.h>
int main() {

/*Three character inputs*/
  int s,d,z;
  //window prompt for user
  printf("Type the three letters of your initials: ");
  s=getchar(); //collected user entry
  d=getchar(); //collected user entry
  z=getchar(); //collected user entry
  printf("You typed '%c%c%c'.\n\n", s,d,z);
  return 0;
}

Output of this function should look like this

Type the three letters of your initials: sdz
You typed 'sdz'.

Note: if your output looks like the following example instead of the above example, remember that the printf line should have this '%c%c%c' for user readability, instead of this '%c''%c''%c'

Bad user readability output (mistake I made the first time)

Type the three letters of your initials: SDZ
You typed 'S''D''Z'.

You'll note that the getchar functions do not pause and wait for input. They simply look for all input coming from the standard input device like a stream of characters flowing out of a hose.

To demonstrate this, if you were to input only one letter, you would get this output instead:

Type the three letters of your initials: S

You typed 'S

'.

The output was only set as the letter I input and the new line, as if it was a character.

If on the other hand you were to type in too many letters, you would get an output like this

Type the three letters of your initials: SDZA
You typed 'SDZ'.

Even though the program will allow continual entries until I hit the enter key, it only outputs the first three characters.

In the multiple character program, I chose to use the printf function instead of using three separate putchar functions, but the output result would have been the same. Because, even if we separated the code, the output happens all at once because of the stream.

The characters the user types are actually sent to output as they are typed, which is how the code runs, but the stream output is buffered.

That means, the computer waits until the buffer is full or flushed before sending out the characters. In this case, the buffer is flushed once the program is finished.

*Remember, the standard C I/O library functions are stream oriented

It kind of reminds me of those character eliminated/protected forms that display something like s***********[email protected], even though you typed [email protected]. It's not quite the same, because in those languages I'm referencing, you're intentionally telling the browser to return a symbol instead of the actual input character, but it's a good mental connection for me to remember that this is important later on

Other I/O character functions in C can be found in these references: UMASS Handout Explaination Resource University of Madrid Resource University of Hawaii Resource Duke University Resource GB Direct UK CPP Wiki Reference for C Style I/O Open Tech Guides Resource

Side Note: Sometimes it might seem redundant to have these resources listed that might go over more advanced stuff, only to later add notes regarding simpler tasks; but remember, all of this is to build a personal resource library for me. A lot of times I am just stockpiling solid resources that I can come back to later, to build more advanced things as I go along.

Oh, and I use Bookmark Ninja and the Google Chrome extension OneTab to stay on top of all of these resources. In case that was a wonder.

Fancier Stuff: File I/O C Functions

results matching ""

    No results matching ""