Upload
jaspreet-sandhu
View
221
Download
0
Embed Size (px)
Citation preview
8/11/2019 Proramming Notes
1/21
IDEIntegrated Development Environment
Enables programs to run, that you built
1. PreprocessingPreprocessor replaces directive with actual library code
2. CompilingReads .c and makes it executable
3. LinkingLinks to function calls
/* My first program */
#include #include
int main (void){
printf ("Hello World");system ("pause");
return0;}
there are two types of functions:
library and program
#include
stdio standard input/output library for keyboard or file input/outputstdlib any call to system
main ()
main, represents the main program
statement:
command that ends in ;
compound statements are between { }this shows where main begins and ends
printfwrites text to the screen
f stands for formatted
Comment
anything written in the comment will be ignored by the compiler
can be used to explain code// single line comment
/*
multiple level comments
*/
/* anything between these will be ignored by the complier */
system (pause);
makes the program pause, until you let it go again
return 0;
8/11/2019 Proramming Notes
2/21
status code given to the operating system
will work without it
Format of a simple program
int main ()
{
}
C is made up of 3 features:
- Directives
o edit commands that modify the program prior to compilation (#include)
o begins with # and no ;- Functions- blocks of executable code (such as main)
o Only main is mandatoryo int main(void), int means that the main function returns an integer value
o return 0; this statement causes the main function to terminate and returns a value
of 0.
- Statements commands to be performed
Identifiers
names of variables, functions, and macros
may contain letters, digits, & underscores must not begin with a number
up to 31 characters
Note: job Job JoB are different identifiers
special case sensitive identifiers that have meaning to the compiler, can't be used as variables
Data Types
int (4 bytes)
ointegers, or whole numbers
float or double
ofloating point, or real numbers
ofloat = 4 bytes
odouble = 8 bytes
How information is stored
binary
1 binary digit is a bit
8 consecutive bits are a byte
o 1 byte can represent 28=256 different values
8/11/2019 Proramming Notes
3/21
Assignments
= assign the right side to the leftex.
int height; (declare it first, if you dont declare it will be garbage)height =8;
Variable Declaration
give it a type give the variable a name
Note: if you dont assign a variable a value, it equals to nothing, or garbage
ex. int a;
int main ()
{
}
Constants
also known as macro definition use all capitals no equal sign or semicolon
ex.
#define CONSTANT 166
return #;
return 0;o everything is fine
return -1;o something went wrong, exist the program
ex.if (terms< 1 ){
printf(invalid input!\n);return -1;
}
Error Types
syntax errors
occur during compilation ex. missing semicolon
run time errors
complies successfully, but will crash on execution
ex. out of bounds loop ex. open non-existent file x/0 number too large to represents the file doesnt exist and you try to extract info
8/11/2019 Proramming Notes
4/21
logic errors
compiles successfully, will run, but not give out the correct input ex. - should be an == ex. if should be an else if
printf
in stdio library used to print stuff to the screen f stands for formatted
\nnewline
\asound an alarm
\bbackspace one character
\thorizontal tab
\\to print a single \
Conversion specifier
%d for int
%f for floats and doubles
ex.int a = 3;double b = -13.;
printf(value of a is %d\nvalue of b is %f, a, b);
Output:
value of a is 3
value of b is -13.000000 (10 digits including -)
ex.int a, b;a=7;b=9;printf(a+b= %d\n, a+b);
output 16
Conversion Specification
%m.pX
%-m.pX
m- number of characters
p- precision, so how many decimal places
X- conversion specifier
d- int
o default p=1
f- float or double
o default p=6ex.a=3.1;printf(%4.2f\n, a );printf(%6.4f\n, a );
8/11/2019 Proramming Notes
5/21
printf(%8.6f\n, a );printf(%10.8f\n, a );
3.10
3.1000
3.100000
3.09999990
8/11/2019 Proramming Notes
6/21
ex.
x=x+1; the following are equivalentx+=1;++x;x++;
Expression Evaluation
precedence the order that operators are evaluated
associativity the direction of the evaluation
precedence operator associativity
highest () L to R++--(post) L to R++--(pre) R to L
! (logical NOT) L to R+-(unary) R to L
*/% L to R+ - (binary) L to R
> >= <
8/11/2019 Proramming Notes
7/21
}
math.h
requires #include
cos(x), sin(x), tan(x) x in radians
sqrt(x) square root
fabs(x) absolute value
exp(x) exponential log(x) natural logarithm
log10(x) log base 10
pow(x,y) x raised to power y
M_PI
M_LN2 natural logarithm of 2
Logical Expressions
equal ==
not equal !=
logical NOT ! (unary)
logical AND &&
logical OR ||
if
performs action listed if true
ex.if (x
8/11/2019 Proramming Notes
8/21
ex.which does the else belong to?if (y != 0) {
if (x != 0)result =x/y;
}else
printf(Error);first, if no brackets it would go the second
ex.#include intmain(){
inthr;intmn;intmm;intmhr;intphr;
printf ("Enter a time (hr min):");
scanf ("%d %d", &hr, &mn);
printf("am (1) or pm (2):");scanf("%d", &mm);
phr=hr+12;
if(hr == 12)printf ("Military time; %.2d:%.2d", hr*(mm-1), mn);
elseif(mm>1)printf("Military time; %.2d:%.2d", phr, mn);
else
printf("Military time; %.2d%:%.2d", hr, mn);
return0;}
switch statement
alternative to if/else
switch (integer expression) {
case label:
break;
default: like else
ex. gradesif (grade100)
printf(Grade is out of range\n);else if (grade >=80)
8/11/2019 Proramming Notes
9/21
printf(Letter grade: A\n);else if (grade >=70)
printf(Letter grade: B\n);else if (grade >=60)
printf(Letter grade: C\n);else if (grade >=50)
printf(Letter grade: D\n);else
printf(Letter grade: F\n);
switch (grade/10) {case 8: case 9: case 10:
printf(Letter grade: A\n);break;
case 7:printf(Letter grade: B\n);break;
case 6:printf(Letter grade: C\n);break;
case 5:printf(Letter grade: D\n);break;
default:printf(Letter grade: F\n);break;
}
break and continue
ex.int main ( ) {
int sum=0, count=0, a;do {
printf(Enter a value: );scanf(%d, &a);
if (a==0) break; //leave the do while loop
in (a
8/11/2019 Proramming Notes
10/21
if (a>b) true
if (!(a>b)) false
if (a>b && a*b==1) false
if (a>b || a*b==1) true
ex.
if (a-b ==0) is equal to
if (!(a-b))
ex.int a=0, b=2, c=4;if (a= c-b)
printf(%d\n, b);else
printf(%d\n, c);
printf(%d\n, a==c-b);
Answer:2 assigns a new value of 2
1 logical, so its true, therefore its 1
Loops
while
do while
for
while
checks condition before entering the loop
continues to loop until the condition becomes falseex.int i= 0, sum=0;printf(enter an integer (-1 to end): 0;scanf(%d, &i);while (i>= 0) {
sum += I;printf(enter an integer (-1 to end);scanf(%d, &i);
}
printf(the sum is %d\n, sum);
do while
test the condition at the end of the loop
loop is executed at least onceex.do {
sum += I;printf(enter an integer (-1 to end);scanf(%d, &i);
} while(i>=0)
8/11/2019 Proramming Notes
11/21
printf(the sum is: %d\n, sum);
for
designed for controlled repetitionex.int i, j=0;for (i=0; i< 10; i++) {
j+=I;}
int i=0, j=0;while (i
8/11/2019 Proramming Notes
12/21
} while (n != 0);return 0;
}
output if n=3
1
1 2
1 2 3
Number Systems
Base 10
10 digits, 0 -> 9
Base 7
7 digits
ex. 157= (1x71) + (5x 70)
=12
binary
base 2ex. 111111112= 255
hexadecimal
0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11
16 = 24
every four digits of binary (right to left), is equal to one of hex
o just like if it was 8, it would be equal to 3 digits of binary
ex.
34D16
= 11 0100 1101
characters
data type: charex.
char c1, c2, c3;c1= f;
c2= F; these are different characters
c3=4; the character 4, not the value
ASCII Character Set
American Standard Code for Information Interchange Characters stored in 1 byte of memory
8/11/2019 Proramming Notes
13/21
ex.char c1, c2;c1= f;c2=102;c3= f;
printf(c1 is: %d\n, c1);printf(c2 is: %d\n, c2);
printf(c2 is: %c\n, c2);printf(c2 is: %d\n, c3);
output
c1 is: 102
c2 is: 102
c2 is: f
c3 is: 102
putchar();
alternative to printf
prints out one character at a time
print variables no
characters need
ex.char a 61 =;
8/11/2019 Proramming Notes
14/21
putchar(a); value of a=61putchar(61);putchar(=);
output
===
getchar();
alternative to scanf
grabs one character from the keyboardex.printf(enter two characters: );c1= getchar();c2= getchar();c3= getchar();
ex. # of keystrokes#include intmain (){
intc, i=0;
printf("Type whatever you want: ");do{c= getchar();i++;
} while(c != '\n');
printf("\n\nYou typed %d keystrokes (including the return/enter key \n\n", i);
return0;}
file input and output
FILE * filename;
data type
* = pointer
name of file, that you make up
filename = fopen (avg.dat, r);
fopen, opens the file on your computer somewhere
fclose would close the file
avg.dat, is what the file is called, but in some computers you have to write out the whole path
r= read only
w= overwrite
a=append/add
EOF
end of file
fscanf returns a special character at the end of a file
ex.while (fscanf(in, %d, #) != EOF) {
8/11/2019 Proramming Notes
15/21
}
File doesnt exist
in_file= fopen(avh.dat, r);
if (in_file == NULL) {
printf(avh.dat does not exist!);return -1; }
fscanf
reads data from a file
int a, b, c;FILE * input;input = fopen (nums.txt, r);
fscanf(input, %d, &b, &d);
printf(average: %d\n, (a+b+c)/3);
fclose (input);
fprintf
prints into the file
must use w or aex.int i=1, j=4;FILE*out_file;out_file=fopen (data.out, w);
fprintf(out_file, %d\n, i);fprintf(out_file, %d\n, j);
fclose (out_file);
functions
library functions
user defined functions
use the function like pow(x,y) or sin(x)
the value of a inside a function will carry through to the mainex.#include
intrund (doublea);
intmain (){
doublea;
printf("Enter a number: ");scanf("%lf", &a);
8/11/2019 Proramming Notes
16/21
printf("rounded to the nearest whole number: %d", rund(a));
return0;}
intrund (doublea) {if(a>0.)
return(int)(a+.5);else
return(int)(a-.5);}
ex.#include #define FILE_NAME "/Users/Alicia/Documents/Dropbox/APS106-2013/7-Midterm/grades.txt"
/* function declarations */intreadGrades(intnum_of_grades);intwriteGrade(intgradeAdd);
intmain (void)
{ intchoice, num;intgrade;interror = 0;
printf ("\n");
while(1){printf ("Would you like to (1) view or (2) add to your grade history (3) exit?: ");scanf ("%d", &choice);
switch(choice) {
case1:printf ("How many grades would you like to read (0 for all)?");scanf ("%d", #);error = readGrades(num);if(error)
printf("There was an error reading the file. \n");break;
case2:printf ("What grade would you like to add?");scanf ("%d", &grade);error = writeGrade(grade);if(!error)
printf("%d was added to the grade file. \n", grade);break;case3:
return0;default:
printf("Incorrect input \n");}if(error){
printf("An error has occurred in your program.\n");break;
}}
8/11/2019 Proramming Notes
17/21
return-1;}
intreadGrades(intnum_of_grades){
inti, grade;
FILE *in;in = fopen (FILE_NAME, "r"); //Can use just grades.txt if running from local directory.
if(in == NULL) {printf ("file doesn't exist\n");return-1;
}if(num_of_grades == 0){
while(fscanf(in, "%d", &grade) != EOF) {printf ("%d ", grade);
}}else{
for(i=1; i
8/11/2019 Proramming Notes
18/21
Arrays
Bubble sort
2D arrays
o dont need first dimension to be initializedEx. initialize arrays
int N,n,i;
char *Noble[] = {"Helium", "Neon", "Argon","Krypton"};
N = 4;
for(i=0; i < N; i++) {
n=0;while(Noble[i][n] != '\0') n++;
printf("%c%c %d\n", Noble[i][0], Noble[i][1], n);
}
Addresses
- 1 bit is either a 1 or a 0- 1 byte = 8 bits
- char 1 byte- int 4 bytes
- double 8 bytes- pointer 4 bytes- sizeof = gives the size of something in terms of bytes
Pointers
4 bytes
& address operator
o the address of that value
o goes in front of an int, float, char
* indirection operator
o the value of that address
o goes in front of a pointer to pass the variable, you have to pass the address of the variable
o call by reference
arithmetic
o a[2]= *(a+2)
theres no point of adding addresses, but subtract can be useful
Ex. char c= r;
char *c_ptr;
c_ptr= &c;
printf(value %c\n, c);
printf(value %c\n, *c_ptr);
printf(address %c\n,&c);
printf(address %c\n, c_ptr);
value r
value r
address 0012FF7C
8/11/2019 Proramming Notes
19/21
address 0012FF7C
Ex.
//doesnt return the negative of the argument, but makes it negative inside the function.
#include
void negate (int *);
int main ( ) {
int i=3;
printf(\n\n i = %d, i);
negate(&i);printf(\n\n i = %d, i);
return 0;
}
void negate (int *j) {
*j = -*j;
return;
}
string.h
#include Strcpy - copies the string s2 into the string s1 strcpy(str2, "abcd"); /* str2 now contains "abcd"
*/
Strncpy: copies str2( starting from n) into str1: strncpy(str1, str2, n);
Strlen - returns the length of a string len = strlen("abc"); /* len is now 3 */
strcat- appends the contents of the string s2 to the end of the string s1. It returns s1 (apointer to the resulting string). strcpy(str1, "abc"); strcat(str1, "def"); /* str1 now contains
"abcdef" */
strcmp -Testing whether str1 is less than str2: if (strcmp(str1, str2) < 0) /* is str1 < str2? */Testing whether str1 is less than or equal to str2: if (strcmp(str1, str2)
8/11/2019 Proramming Notes
20/21
else
*y = 'a'+i;
y++; }
*y = '\0';
puts (x);
enter 4, output: aBcD
if yu use puts(y) instead of puts(x) then yu get nothing (cause y starts at the end and x starts at the
beginning.
Struct
struct Elmnts { int num;
char symbol;
float mass; };
int main(){ int i;
struct Elmnts *ptr;
struct Elmnts fewElmts[] = {{5,'B',10.811},{6,'C',12.011}, {7,'N',14.007}, {8,'O',15.999}, {9,'F',18.998}};
ptr = fewElmts; printf("%c\n",ptr->symbol);
printf("%d\n",(++ptr)->num);
ptr++;
printf("%d\n",++(ptr->num));
ptr++;
printf("%0.3f\n",(ptr++)->mass);
printf("%c\n", ptr->symbol);
return 0;
}
Output:
B
6
8 //not 15.007, ptr address not the value
15.999
F
Dynamic Memory Allocation#include
mallocAllocates a block of memory but doesnt initialize it.
Eg. A call of malloc that allocates memory for a string of n characters:
char * p;
p = malloc(n* (sizeof(char) + 1));
callocAllocates a block of memory and clears it to 0.
8/11/2019 Proramming Notes
21/21
Eg. A call of calloc that allocates space for an array of n integers:
a = calloc(n, sizeof(int));
reallocResizes a previously allocated block of memory
eg; realloc(a,sizeof(int)*5); /*characters will only have 5 elements*/
realloc(*ptr, size);
free- unallocates the allocated memoryE.g. free(a);
Random Number Generator
#include
int number;srand ((unsigned) time(NULL));
number = rand()%100+1;
(Num frm 1-100)
number = rand ( )%4;
(Numb from 0-3)