









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An in-depth exploration of c programming, focusing on data types, variables, and arrays. It covers topics such as integers, real numbers, literal values, storage classes, and arrays, including initialization, stack-allocated arrays, and statically-allocated arrays. The document also delves into pointer operators and computing two's complement.
Typology: Study Guides, Projects, Research
1 / 15
This page cannot be seen from the preview
Don't miss anything!










Models of Programming Imperative Object-oriented Procedural Static Typing Dynamic Typing GCC gcc -Wall -std=c99 -g myProgram.c -o myProgram
stdlib.h – standard library o EXIT_SUCCESS (0), EXIT_FAILURE (8) stdio.h – standard i/o header o int getchar(void) : returns code for the next character read (int 0 to 255) or -1 for EOF if no more input o int putchar(int c); Sends one char to the terminal Returns character written or EOF if unable to send o printf – generates formatted output printf(“value:%6.2f\n”, 3.1415926); 6 = field width: take at least 6 characters to print it .2 = precision: round output to 2 digits o scanf - Reads formatted input scanf(“&d”, val); pass-by-value (doesn’t change the variable, passes a copy) scanf(“&d”, &val); pass-by-reference (changes what’s in the variable val) int matches = scanf(“%f%d”, &floatVal, &intVal); matches = 2 if both float and int vals matched 1 if only 1 matched 0 if no value matched -1 if end-of-file reached before matching Input: 37.22b5 would match 37.22 to floatVal, and return 1 ctype.h o bool isalpha(int ch); Check if a character is a letter o bool isspace(int ch); Check if character is whitespace o bool isdigit(int ch); Check if character is a digit o bool isprint(int ch); Check if character is printable (not a control character) o Others: isalnum(int ch); [is alphabet/number] o ispunct(int ch); isupper(int ch); o toupper(int ch); Converts lower to upper case
\’ Single quote \” Double quote \ Backslash \n Newline \t Horizontal tab
Format Specifier Input/Output %c Single character (given its numeric character code) %d Decimal integer %ld long integer %f float or double %s String %p Pointers (in hexadecimal) %zd size_t or sizeof() %o Integer in octal %x Integer in hexadecimal %X Integer in hexadecimal (capialized) %u Unsigned integer %lli long long int (decimal or any of the formats above). User can pick what base to use.
Source Code (Preprocessing) Expanded Source Code (Lexical Analysis (tokenization)) Tokens (Parsing) Parse Tree (Code Generation) Assembly Code (Assembling) Object Code More Objects Libraries (Linking) Executable
bit = smallest unit of computer information byte = 8 bits, single character of text
Floating Point Types: long double, double, float Integer Types (signed & unsigned): long long, long, int, short, char Types Smaller than integers: _Bool, void Naming: o Signed is usually the default so is left off (ex: signed int = int) o Int is optional for short, long ,and long long (ex: long int = long) Signed: positive & negative values o Usually the default Unsigned: 0 and positive values
Range of type is platform dependent. Can look in the /usr/include/limits.h header to find out how much memory is used for each variable type. #include for constants: SHRT_MIN, SHRT_MAX, USHRT_MAX, INT_MIN, INT_MAX, UINT_MAX, LONG_MIN, LONG_MAX (signed range), ULONG_MAX(unsigned range) Integers Type Bit s Byte s Signed Unsigned char 8 1 -128 to 127 0 to 255 short 16 2 -32,768 to 32,767 0 to 65, int 32 4 -2,147,483,648 to 2,147,483, 0 to 4,294,967, long 64 8 - 9,233,372,036,854,775, 808 to 0 to 18,446,744,073,709, ,
! Logical not (type) Type cast: (destination_type) expression Explicitly specifies the type (as opposed to implicit type casting) Ex: c = (unsigned char) d; Can even cast to void to throw away result: (void) f(x); sizeof tells you how much memory it takes to store something size_t sizeType = sizeof(x); printf(“%zd\n”, sizeType);
Constant expressions: expression that always produces the same result o int three = 3;
switch case o switch (val ) { case 0: val +=1; break case 2/2: val -=1; break; case 25/7%2 + 19 -6*3: val *=2; break; Default: … } break: Cancel the innermost loop early continue: Skips the rest of the innermost loop’s current iteration goto: Can jump to a label as long as it’s in the same function o for (int i = 0; i < 0; i++) { if (i > 12) { goto done; } } done: … Expression Evaluation Order Sequence points: Places where the order of evaluation are well defined; and the known side effects to the left will occur before evaluation continues o ; Statement termination o ) Closing parenthesis in a condition evaluation o Operators: a && b a || b a? b: c a , b (but not between function parameters)
Global Variables : Static Storage Class (Statically-Allocated Data) C Program Memory Executable Increasing Addresses Machine Code Statically- Allocated Data (global vars) Heap Data
Compilation Unit : C source code that is compiled and treated as 1 logical unit. Declarations and definitions within a compilation unit determine the scope of functions and data objects. Build multiple files: gcc -Wall -std=c99 -g tournament.c game.c summary.c tournament Linker: Take 1 or more object files generated by the compiler and combines them into 1 executable program. Connects each use with its memory location Header File : Advertises the public interface for an implementation file o Javadoc comments go here o Ex: helper.h (header file) extern int x; void f(int); helper.c (implementation file) #include “helper.h” int x = 5; void f( int a ){…} main.c #include “helper.h” // so it can use functions in helper.c Helper.h and helper.c make a component together Implementation File: File with the implementation of operations specified in the header file
Initialize : o int a[10]; a[0] = 1; // sets value one at a time printf(“%d”, 0[a]); -> “1” // Can access 0 this way too o int a[] = {7, 14, 21, 28}; //compiler figures out size o int a[5] = {7, 14, 21}; // Partial initialization o int a[] = { 1, [7]=10, 90, [2]=40, 2, [5]=35 }; Partial initialization, unspecified index set to 0. Stack-allocated array o Contains garbage if not initialized o Variable-length array: Size when initializing can be determined during execution int main(void) { int n; printf(“How many values would you like: “); scanf(%d”, &n); int list[n]; … } Aren’t resizable but can choose a different size every time the variable goes into scope Can’t use initialization syntax for variable-length arrays: int a[n] = {7, 14, 21}; int a[n] = { }; Statically-allocated array o Contains zeros if not initialized o Size must be a constant expression: int sequence[100]; int main(){…} Functio n Description Example sizeof() Reports the size of its argument. Can be used to figure out array length in some cases. int a; size_t aSize = sizeof(a);\4 bytes float b[100]; …
dest[], char src[]) null terminator strncpy(char dest[], char src[], size_t n) Copy strings with a limit to the number of characters written to the destination. If short, pads with zeros up to n. Won’t null terminate if no room strcmp( char s1[], char s2[] ) Compares strings < 0 if s1 is before s 0 if equal (true) > 0 if s1 is after s strncmp(s1, s2, size_t n) Compares at most n characters strcat(char dest[], char src[]) Copies string from source to the end of dest Dest must be initialized, can be empty strncat(dest, src, n) Gives a bound on the length of the string appended and adds \0 at end. Helps ensure null terminator is added. atoi() (^) Parse string as int int atoi(char str[]) atof() (^) Parse strings as doubles double atof(char str[]) atol() (^) Parse strings as long ints long atoll(char str[]) atoll() (^) Parse strings as long long ints long long atoll(char str[])
int table[# rows][# cols] Initialization (partial can be done & unspecified will be filled with zeros): o int table[3][4]={ {0, 1}, (16, 25, 36, 49}, {64}
o int table[ ][4] = { [1]={16, 25, 36, 49}, [0] ={[1] = 1}, [2][0] = 64 }; o # of rows can be left blank and the compiler can determine the size o Inner dimensions must be specified sizeof o sizeof(table) = size of whole array o sizeof(table[0]) = size of row o sizeof(table[0][0]) = size of an element Multi-dimensional arrays as parameter: o Int process(short block[][7][10]) o Must specify array length as a parameter too if want to use it: void sumTable(int rows, int cols, int table[][cols]){}
Compiled code: C, Interpreted Code: Java
Pointer Operators & : Address-of operator o &a : address of variable a * : Type operator, creates new types o type * identifier;