C Programming: Data Types, Variables, and Arrays, Study Guides, Projects, Research of Computer Programming

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

2023/2024

Uploaded on 04/22/2024

vanilla-carrot-cake
vanilla-carrot-cake 🇺🇸

1 document

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Table of Contents
Headers #include<___.h>.....................................................................2
Lecture 2.....................................................................................3
Conversion Specifiers – printf & scanf...................................................4
Steps in C Compilation.........................................................................4
Lecture 4.....................................................................................4
Types.................................................................................................. 5
Capacity.............................................................................................5
Literal Values...................................................................................... 6
Boolean Type: _Bool............................................................................. 6
Operators & Precedence...................................................................... 6
Arithmetic Conversion 5 Rules............................................................. 7
Lecture 5.....................................................................................7
Flow of Control....................................................................................7
Storage Class......................................................................................8
Functions............................................................................................ 9
Multi-File Programs............................................................................. 9
Lecture 6................................................................................... 11
Arrays............................................................................................... 11
Strings.............................................................................................. 12
Lecture 7................................................................................... 13
Multi-Dimensional Arrays...................................................................13
Executing C Programs........................................................................ 14
Lecture 8................................................................................... 14
Lecture 9................................................................................... 15
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download C Programming: Data Types, Variables, and Arrays and more Study Guides, Projects, Research Computer Programming in PDF only on Docsity!

Table of Contents

  • Headers #include<___.h>.....................................................................
  • Lecture 2.....................................................................................
    • Conversion Specifiers – printf & scanf...................................................
    • Steps in C Compilation.........................................................................
  • Lecture 4.....................................................................................
    • Types..................................................................................................
    • Capacity.............................................................................................
    • Literal Values......................................................................................
    • Boolean Type: _Bool.............................................................................
    • Operators & Precedence......................................................................
    • Arithmetic Conversion 5 Rules.............................................................
  • Lecture 5.....................................................................................
    • Flow of Control....................................................................................
    • Storage Class......................................................................................
    • Functions............................................................................................
    • Multi-File Programs.............................................................................
  • Lecture 6...................................................................................
    • Arrays...............................................................................................
    • Strings..............................................................................................
  • Lecture 7...................................................................................
    • Multi-Dimensional Arrays...................................................................
    • Executing C Programs........................................................................
  • Lecture 8...................................................................................
  • Lecture 9...................................................................................

Models of Programming  Imperative  Object-oriented  Procedural  Static Typing  Dynamic Typing GCC gcc -Wall -std=c99 -g myProgram.c -o myProgram

Headers #include<___.h>

 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

Conversion Specifiers – printf & scanf

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.

Steps in C Compilation

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

Lecture 4

 bit = smallest unit of computer information  byte = 8 bits, single character of text

Types

 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

Capacity

 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);

  • / % Multiply, divide, mod
    • Add, subtract < <= > >= Relational operators == != Equals, not equals && Logical and || Logical or ?: Ternary operator: test? expr1 : expr Same as if (test){expr1} else {expr2} Ex: c = a>b? a: b; = += -= *= … Assignment, and its friends , Comma operator: Chain together multiple expressions. Expressions get evaluated left to right

Arithmetic Conversion 5 Rules

  1. If an operand is a floating point type, convert to the wider floating point type
  2. If either operand rank is lower than int (_Bool, char, short), convert to at least the rank of int o Lower ranks are promoted to signed int if it is large enough to hold all values
  3. If both types have the same “signed-ness”, promote to the higher- ranked type
  4. If the signed type can store every value the unsigned type can, convert to the signed type
  5. If the signed type isn’t large enough, use the unsigned version of the higher-ranked type o Given 2 equal ranked types of different signed-ness, C will use the unsigned type o Ex: unsigned int x = 999; x > -1 would be false b/c -1 would be converted to an unsigned value which would overflow to a very positive value  Function parameters : Parameter values get converted to the parameter types expected by the function  Return value gets converted to the return type

Lecture 5

 Constant expressions: expression that always produces the same result o int three = 3;

Flow of Control

 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)

Storage Class

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

bytes each type takes

Lecture 6

Arrays

 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[])

Lecture 7

Multi-Dimensional Arrays

 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]){}

Executing C Programs

Compiled code: C, Interpreted Code: Java

Lecture 8

Pointer Operators  & : Address-of operator o &a : address of variable a  * : Type operator, creates new types o type * identifier;