Difference between revisions of "C Programming - Getting Started"
(→Standard Library) |
|||
(38 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
− | + | ''This page is part of the [[Programming and CS - Getting Started]]'' | |
− | Getting started with C programming | + | For a video explaining how to get started here, see https://youtu.be/WYTDuKRXWJQ |
+ | |||
+ | ==Getting started with C programming== | ||
# '''Reading''' - start reading through one of the following (pick one that seems an easy read for you) before you start working on the programming problems. | # '''Reading''' - start reading through one of the following (pick one that seems an easy read for you) before you start working on the programming problems. | ||
+ | ## [https://www.tutorialspoint.com/cprogramming/index.htm TutorialsPoint C] - fairly quick read that gives a quick look at the basics, this is suitable for those with just a little bit of previous programming | ||
+ | ## [https://en.wikipedia.org/wiki/The_C_Programming_Language The C Programming Language] - the classic introductory book on C written by those who invented the language, perfect for those who are good programmers already, may not be appropriate for those new to programming | ||
## [https://publications.gbdirect.co.uk/c_book/ The C Book] - a bit older, suitable for people with just a bit of programming experience | ## [https://publications.gbdirect.co.uk/c_book/ The C Book] - a bit older, suitable for people with just a bit of programming experience | ||
## [http://markburgess.org/CTutorial/C-Tut-4.02.pdf C Programming Tutorial] - suitable for people with no previous programming experience | ## [http://markburgess.org/CTutorial/C-Tut-4.02.pdf C Programming Tutorial] - suitable for people with no previous programming experience | ||
Line 9: | Line 13: | ||
## [https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-programming-in-c-january-iap-2010/ MIT C course] - with lecture notes and assignments | ## [https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-programming-in-c-january-iap-2010/ MIT C course] - with lecture notes and assignments | ||
## [http://www.cs.cornell.edu/courses/cs2022/2011sp/ Cornell C course] - with lecture notes and assignments | ## [http://www.cs.cornell.edu/courses/cs2022/2011sp/ Cornell C course] - with lecture notes and assignments | ||
− | # '''Work on solving these problems''' - https://www.hackerrank.com/domains/c. | + | # '''Work on solving these problems''' - https://www.hackerrank.com/domains/c. The next section lists problems to work on - from very easy up to more interesting. |
# '''Get C installed on your computer''' - download and install some C compiler/IDE. We use gcc (see https://gcc.gnu.org/install/binaries.html). You could use any compiler/IDE that is C (not C++). Eclipse (see https://www.eclipse.org/downloads/) would be fine. So would MS Visual Studio (see https://visualstudio.microsoft.com/). Or Clang (see http://releases.llvm.org/download.html). Or some in-browser C site, like https://repl.it/languages/c or https://www.onlinegdb.com/online_c_compiler. | # '''Get C installed on your computer''' - download and install some C compiler/IDE. We use gcc (see https://gcc.gnu.org/install/binaries.html). You could use any compiler/IDE that is C (not C++). Eclipse (see https://www.eclipse.org/downloads/) would be fine. So would MS Visual Studio (see https://visualstudio.microsoft.com/). Or Clang (see http://releases.llvm.org/download.html). Or some in-browser C site, like https://repl.it/languages/c or https://www.onlinegdb.com/online_c_compiler. | ||
− | # If you are a current or incoming ISU student, or an ISU alumni, | + | # If you are a current or incoming ISU student, or an ISU alumni, get help on what you are working on using the online unix lab. When asking about the hackerrank problems make sure to refer to them using the title hackerrank gives them, or give a link to the problem statement on hackerrank. |
+ | # '''Cheat sheets''' - keep a cheat sheet for yourself of C syntax, built-in functions, etc. See below on this page for some of this as well. | ||
− | + | Let's see how far you can get with solving the hackerrank problems! Good luck! | |
== List of Problems == | == List of Problems == | ||
Here are problems to work on from the hackerrank set. Note that you should work on more than just this set, but these are ones we are ready to help you solve! | Here are problems to work on from the hackerrank set. Note that you should work on more than just this set, but these are ones we are ready to help you solve! | ||
+ | |||
+ | Note that you should work on solving these problems completely by yourself. You become a better programmer by figuring things out on your own, not by looking in the comments for solutions. Check the comments if needed, but your goal is to figure out these problems and debug your programs on your own. | ||
=== Basic Programming === | === Basic Programming === | ||
Line 39: | Line 46: | ||
* [https://www.hackerrank.com/challenges/frequency-of-digits-1/problem Digit Frequency] | * [https://www.hackerrank.com/challenges/frequency-of-digits-1/problem Digit Frequency] | ||
* [https://www.hackerrank.com/challenges/dynamic-array-in-c/problem Dynamic Array in C] | * [https://www.hackerrank.com/challenges/dynamic-array-in-c/problem Dynamic Array in C] | ||
− | |||
− | |||
=== And a Bit More === | === And a Bit More === | ||
− | These problems are still a bit more involved. Some require some abstract thinking about the problem, a programming "trick", or other key insight. | + | These problems are still a bit more involved. Some require some abstract thinking about the problem, a programming "trick", or other key insight. Note that at this point you are working on problems such that some of the lab assistants in the unix lab may not have solved these problems. This is where you want to be at - you have mastered the basics and are working on problems independently! |
* [https://www.hackerrank.com/challenges/permutations-of-strings/problem Permutations of Strings] | * [https://www.hackerrank.com/challenges/permutations-of-strings/problem Permutations of Strings] | ||
Line 61: | Line 66: | ||
for C, or g++ for c++. You run the resulting program by typing ./outputName (and then enter/return) at the shell prompt (aka command line). For programs that you are assigned as part of a course, you need to make sure your C/C++ programs compile and run using gcc/g++. Note that programs made using MS Visual Studio or some other compiler will normally not work straight away with gcc/g++ because there are some differences in which functions are included in the header files. | for C, or g++ for c++. You run the resulting program by typing ./outputName (and then enter/return) at the shell prompt (aka command line). For programs that you are assigned as part of a course, you need to make sure your C/C++ programs compile and run using gcc/g++. Note that programs made using MS Visual Studio or some other compiler will normally not work straight away with gcc/g++ because there are some differences in which functions are included in the header files. | ||
+ | |||
+ | ==Study Guide== | ||
+ | Here we keep some notes on the basics of C for you to study. We do not aim to present this information completely, but only to remind of of things you should have learned reading through one of the above resources. | ||
+ | |||
+ | ===C Data Types=== | ||
+ | Note - # of bytes is in () for on the CS server using gcc. This varies depending on your system and compiler. | ||
+ | * char (1), short (2), int (4), long (8), unsigned (modifier for the integer types), float (4), double (8), long double (16). | ||
+ | * pointers - memory address, note that sizeof(char *) is however many bytes a memory address takes up, which in 2020 on the CS server is 8. | ||
+ | * everything is really an integer (print them as integers) | ||
+ | * C string - array of characters, "last" character in the string is \0 (literally all 0's in the byte), also can use NULL | ||
+ | * array - block of memory large enough for multiple int's (or float's, etc.). Declared like <code>int A[10];</code> In the program, <code>A</code> evaluates to the address of the first element in the array. | ||
+ | |||
+ | ===Operators=== | ||
+ | * Bits - & and, ^ xor, | or, ~ complement, << left bit shift, >> right bit shift | ||
+ | * Logical - && and, || or, ! not | ||
+ | * Arithmetic - + - * / % | ||
+ | * Assignment - =, also = after all bit/arithmetic operations (+=, -=, etc.) | ||
+ | * Precedence and associativity - see https://en.cppreference.com/w/c/language/operator_precedence | ||
+ | |||
+ | ===Grouping=== | ||
+ | * { } for compound statements | ||
+ | * ( ) for order of operations, defining functions, calling functions | ||
+ | * [ ] for indexing arrays | ||
+ | |||
+ | ===Statements=== | ||
+ | * for - order of ops is - initializer, check condition, body, increment, check condition, ... | ||
+ | * while - order of ops is - check condition, body, check condition, ... | ||
+ | * do while - order of ops is - body, check condition, body, ... | ||
+ | * break / continue | ||
+ | * switch - only for integer types (including char's), note that must use break with each case (or multiple case's will run the same code) | ||
+ | * if / else | ||
+ | |||
+ | ===Variables, Data, Memory=== | ||
+ | * Initialization - is not guaranteed, you must initialize | ||
+ | * Scope - variables exist within the { } they are declared within, globals are declared outside of functions and have scope for the whole file | ||
+ | * malloc/free - for allocating and freeing dynamically allocated memory (from the heap) | ||
+ | * pointers / memory address - & gets the address (aka memory location) of a variable, * gets the value at a given memory address, int * declares a pointer variable that stores a memory address | ||
+ | * array - if declared as <code>int A[10];</code> then A[i] is the (i+1)st slot in the array, and A (on its own, no brackets) is the address of the first slot in the array | ||
+ | * Basic 4 types of memory - local variables (kept on "the stack"), global variables (kept in "data"), the program code (kept in "code"), dynamic memory (kept in "the heap") | ||
+ | * The stack - local variables automatically allocated space, stack pointer keeps track of the top of the stack, at end of } local variables are "free'd" by changing the stack pointer (so next allocated variables will overwrite previous ones). Stack memory is limited (e.g., 1MB), large arrays and such should be allocated in the heap or as global variables. | ||
+ | * The heap - big chunk of memory, malloc allocates space, free frees it, it's up to program to keep track of malloc'ed memory. Can be as large as memory. | ||
+ | * Code - memory that has the program code itself is read-only. Can be larger than the stack, still best practice to store really large things in the heap. | ||
+ | * Data - global variables are known at compile time, space is allocated when the program is loaded and persists until program is finished, can declare large arrays as globals. | ||
+ | |||
+ | ===Functions=== | ||
+ | * Parameters are passed by value, use pointers to have modified variables "returned" | ||
+ | * return - returns value from function, stops function | ||
+ | |||
+ | ===Pre-processor=== | ||
+ | * Is executed before compiling - first pre-processor is run through the entire file(s), second the compiler runs | ||
+ | * #include - it is as if that file were copy/pasted into the present file | ||
+ | * #define PI 3.14 - when pre-process is run, all occurrences of PI in the program will be replaced with 3.14, before the compiler is run. | ||
+ | |||
+ | ===Command-Line Arguments=== | ||
+ | * argc is count, argv is array of C strings, argv[0] is the name of the program itself, argv[1] is first actual argument, arguments are all C strings so use atoi or atof if need to convert to int or float. | ||
+ | |||
+ | ===Other Punctuation=== | ||
+ | * comments // to the end of the line or /* multiple lines */ | ||
+ | |||
+ | ===Standard Library=== | ||
+ | * string functions - strlen, strcmp, strstr, strtok, atoi, atof, strcpy | ||
+ | * I/O - printf, scanf, fgetc, getline, fgets, fprintf, fscanf, fputc | ||
+ | * math functions - (use -lm flag when compiling with gcc), log, log2, log10, sqrt, pow |
Latest revision as of 18:42, 28 October 2020
This page is part of the Programming and CS - Getting Started
For a video explaining how to get started here, see https://youtu.be/WYTDuKRXWJQ
Contents
Getting started with C programming
- Reading - start reading through one of the following (pick one that seems an easy read for you) before you start working on the programming problems.
- TutorialsPoint C - fairly quick read that gives a quick look at the basics, this is suitable for those with just a little bit of previous programming
- The C Programming Language - the classic introductory book on C written by those who invented the language, perfect for those who are good programmers already, may not be appropriate for those new to programming
- The C Book - a bit older, suitable for people with just a bit of programming experience
- C Programming Tutorial - suitable for people with no previous programming experience
- Fresh2Refresh Tutorial - more of a summary, easy to find particular topics
- cplusplus.com - contains references for functions, often one of the first search results on google searches for C
- MIT C course - with lecture notes and assignments
- Cornell C course - with lecture notes and assignments
- Work on solving these problems - https://www.hackerrank.com/domains/c. The next section lists problems to work on - from very easy up to more interesting.
- Get C installed on your computer - download and install some C compiler/IDE. We use gcc (see https://gcc.gnu.org/install/binaries.html). You could use any compiler/IDE that is C (not C++). Eclipse (see https://www.eclipse.org/downloads/) would be fine. So would MS Visual Studio (see https://visualstudio.microsoft.com/). Or Clang (see http://releases.llvm.org/download.html). Or some in-browser C site, like https://repl.it/languages/c or https://www.onlinegdb.com/online_c_compiler.
- If you are a current or incoming ISU student, or an ISU alumni, get help on what you are working on using the online unix lab. When asking about the hackerrank problems make sure to refer to them using the title hackerrank gives them, or give a link to the problem statement on hackerrank.
- Cheat sheets - keep a cheat sheet for yourself of C syntax, built-in functions, etc. See below on this page for some of this as well.
Let's see how far you can get with solving the hackerrank problems! Good luck!
List of Problems
Here are problems to work on from the hackerrank set. Note that you should work on more than just this set, but these are ones we are ready to help you solve!
Note that you should work on solving these problems completely by yourself. You become a better programmer by figuring things out on your own, not by looking in the comments for solutions. Check the comments if needed, but your goal is to figure out these problems and debug your programs on your own.
Basic Programming
These problems are all pretty basic - require a single loop, if statement, etc. They are good when you are just getting started with C.
- Hello World
- Sum and Difference of Two Numbers
- Functions in C
- Pointer in C
- Conditional Statements in C
- For Loop in C
- Sum of Digits of a Five Digit Number
- Bitwise Operators in C
A Bit More Involved
These problems require nested loops, working with arrays, or other things that are the next level of difficulty. Solve all of the Basic Programming problems before starting on these.
- Printing Pattern Using Loops
- 1D Arrays in C
- Array Reversal
- Printing Tokens
- Digit Frequency
- Dynamic Array in C
And a Bit More
These problems are still a bit more involved. Some require some abstract thinking about the problem, a programming "trick", or other key insight. Note that at this point you are working on problems such that some of the lab assistants in the unix lab may not have solved these problems. This is where you want to be at - you have mastered the basics and are working on problems independently!
After That
If you are able to do all of the problems above, then you don't need us to give you lists of problems any more. You can pick problems to work through on your own. Some suggested places with problems are as follows.
On CS Systems - gcc, g++
For CS courses that use C and C++, the gcc and g++ compilers are normally used. These are already installed on the CS server. If you have a C or C++ program, you compile it by first logging into the CS server using Putty or another terminal program and typing
gcc code.c -o outputName
for C, or g++ for c++. You run the resulting program by typing ./outputName (and then enter/return) at the shell prompt (aka command line). For programs that you are assigned as part of a course, you need to make sure your C/C++ programs compile and run using gcc/g++. Note that programs made using MS Visual Studio or some other compiler will normally not work straight away with gcc/g++ because there are some differences in which functions are included in the header files.
Study Guide
Here we keep some notes on the basics of C for you to study. We do not aim to present this information completely, but only to remind of of things you should have learned reading through one of the above resources.
C Data Types
Note - # of bytes is in () for on the CS server using gcc. This varies depending on your system and compiler.
- char (1), short (2), int (4), long (8), unsigned (modifier for the integer types), float (4), double (8), long double (16).
- pointers - memory address, note that sizeof(char *) is however many bytes a memory address takes up, which in 2020 on the CS server is 8.
- everything is really an integer (print them as integers)
- C string - array of characters, "last" character in the string is \0 (literally all 0's in the byte), also can use NULL
- array - block of memory large enough for multiple int's (or float's, etc.). Declared like
int A[10];
In the program,A
evaluates to the address of the first element in the array.
Operators
- Bits - & and, ^ xor, | or, ~ complement, << left bit shift, >> right bit shift
- Logical - && and, || or, ! not
- Arithmetic - + - * / %
- Assignment - =, also = after all bit/arithmetic operations (+=, -=, etc.)
- Precedence and associativity - see https://en.cppreference.com/w/c/language/operator_precedence
Grouping
- { } for compound statements
- ( ) for order of operations, defining functions, calling functions
- [ ] for indexing arrays
Statements
- for - order of ops is - initializer, check condition, body, increment, check condition, ...
- while - order of ops is - check condition, body, check condition, ...
- do while - order of ops is - body, check condition, body, ...
- break / continue
- switch - only for integer types (including char's), note that must use break with each case (or multiple case's will run the same code)
- if / else
Variables, Data, Memory
- Initialization - is not guaranteed, you must initialize
- Scope - variables exist within the { } they are declared within, globals are declared outside of functions and have scope for the whole file
- malloc/free - for allocating and freeing dynamically allocated memory (from the heap)
- pointers / memory address - & gets the address (aka memory location) of a variable, * gets the value at a given memory address, int * declares a pointer variable that stores a memory address
- array - if declared as
int A[10];
then A[i] is the (i+1)st slot in the array, and A (on its own, no brackets) is the address of the first slot in the array - Basic 4 types of memory - local variables (kept on "the stack"), global variables (kept in "data"), the program code (kept in "code"), dynamic memory (kept in "the heap")
- The stack - local variables automatically allocated space, stack pointer keeps track of the top of the stack, at end of } local variables are "free'd" by changing the stack pointer (so next allocated variables will overwrite previous ones). Stack memory is limited (e.g., 1MB), large arrays and such should be allocated in the heap or as global variables.
- The heap - big chunk of memory, malloc allocates space, free frees it, it's up to program to keep track of malloc'ed memory. Can be as large as memory.
- Code - memory that has the program code itself is read-only. Can be larger than the stack, still best practice to store really large things in the heap.
- Data - global variables are known at compile time, space is allocated when the program is loaded and persists until program is finished, can declare large arrays as globals.
Functions
- Parameters are passed by value, use pointers to have modified variables "returned"
- return - returns value from function, stops function
Pre-processor
- Is executed before compiling - first pre-processor is run through the entire file(s), second the compiler runs
- #include - it is as if that file were copy/pasted into the present file
- #define PI 3.14 - when pre-process is run, all occurrences of PI in the program will be replaced with 3.14, before the compiler is run.
Command-Line Arguments
- argc is count, argv is array of C strings, argv[0] is the name of the program itself, argv[1] is first actual argument, arguments are all C strings so use atoi or atof if need to convert to int or float.
Other Punctuation
- comments // to the end of the line or /* multiple lines */
Standard Library
- string functions - strlen, strcmp, strstr, strtok, atoi, atof, strcpy
- I/O - printf, scanf, fgetc, getline, fgets, fprintf, fscanf, fputc
- math functions - (use -lm flag when compiling with gcc), log, log2, log10, sqrt, pow