Você está na página 1de 21

IDE Integrated Development Environment

Enables programs to run, that you built



1. Preprocessing
Preprocessor replaces directive with actual library code
2. Compiling
Reads .c and makes it executable
3. Linking
Links to function calls



/* My first program */

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
printf ("Hello World");
system ("pause");
return 0;
}

there are two types of functions:
library and program

#include <stdio.h>
stdio standard input/output library for keyboard or file input/output
stdlib 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

printf writes 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;
status code given to the operating system
will work without it



Format of a simple program
<directives>

int main ()
{
<declarations>
<statements>
}


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 mandatory
o 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)
o integers, or whole numbers
float or double
o floating point, or real numbers
o float = 4 bytes
o double = 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


Assignments
= assign the right side to the left
ex.
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 ()
{
<declarations>
<statements>
}


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

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

\n newline
\a sound an alarm
\b backspace one character
\t horizontal 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=6
ex.
a=3.1;
printf(%4.2f\n, a );
printf(%6.4f\n, a );
printf(%8.6f\n, a );
printf(%10.8f\n, a );

3.10
3.1000
3.100000
3.09999990 <= not exact, because a float only has so many spaces

scanf
reads data from keyboard
& required before variable names
%d int
%f float
%lf double
ex. %d / %d to have the user input 3/5



Arithmetic

binary operator
when a binary operator meets a float and an int, the answer will be an int
when you assign a float to an int, it truncates the value of the float
a*b, a+b, a%b (modulo gives the remainder)
a, b are operands
*+/-% are operators
ex.
d= c%b; d= remainder of c/b

unary operator
applied to one operand
-a

assignment operator
left value must be stored in memory
ex.
c = a+b;
a+b = c; WRONG
5=a; WRONG

compound arithmetic
+=, -=, /=, *=, %=
ex.
float a=0.5, b=3.0;
int i=10;
a+= 1.5; a=2.0; equivalent to a=a+1.5
b /= 4.0; b=0.75; equivalent to b=b+4.0
i %= 7; c=3; equivalent to i=i % 7

increment and decrement operators
++a; increment by one
--a; decrement by one
ex.
x=x+1; the following are equivalent
x+=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

> >= < <= == !=
L to R

&& (logical AND)
L to R

|| (logical OR)
L to R
lowest
= += -= *= /= %=
R to L
ex.
-3 +16*2 -23
= (-3) +16*2 -23
= (-3) +32 -23
= 29 -23
= 6

ex.
int x=1, y;
x+=y=5; this is legal
printf(%d %d\n); output: 5 6

ex.
#include <stdio.h>
int main ()
{
float num;
float round;
float trunc;
int i;

printf("enter a number");
scanf("%f", &num);

num *= 10.;
i = num;
trunc= i/10.;
round = (num/10 + 0.05);

printf("truncated to one decimal place: %.1f \n rounded to one decimal place: %.1f", trunc, round);

return 0;

}


math.h
requires #include <math.h>

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<y)
printf(x<y); with single statement

if(x<y) {
x++;
printf(x incremented); followed by a block, so add brackets


if/else
if the first condition is false, then follow the else

ex.
if (y>x)
printf(y is greater than x);
else
printf(y is less than or equal to x);

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 <stdio.h>
int main()
{
int hr;
int mn;
int mm;
int mhr;
int phr;

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);
else if (mm>1)
printf("Military time; %.2d:%.2d", phr, mn);
else
printf("Military time; %.2d%:%.2d", hr, mn);


return 0;
}



switch statement
alternative to if/else

switch (integer expression) {
case label:
break;
default: like else



ex. grades
if (grade<0 || grade >100)
printf(Grade is out of range\n);
else if (grade >=80)
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<0) continue; //go back to the conditional

sum += a;
count++;
} while (1); //this condition is always true

return 0;
}


logic test
result is either true (non-zero or 1) or false (zero)
when the expression evaluated as false, assigns it an integer 0
ex.
int a=1, b=0;

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 false
ex.
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 once
ex.
do {
sum += I;
printf(enter an integer (-1 to end);
scanf(%d, &i);
} while(i>=0)
printf(the sum is: %d\n, sum);

for
designed for controlled repetition
ex.
int i, j=0;
for (i=0; i< 10; i++) {
j+=I;
}

int i=0, j=0;
while (i<10) {
j+=i;
i++;
}


nested loops
ex.
B W B W B W B W
W B W B W B W B
B W B W B W B W
W B W B W B W B

int main ( ) {
int i, j, rows, cols;
printf(enter # rows and columns: );
scanf(%d %d, &rows, &cols;

for (i=1; i <= rows; i++) {
for (j=1; j<= cols; j++) {
if ((i+j)%2 ==1)
printf(W);
else
printf(B);
}
printf(\n);
}
return 0;
}


ex.
#include <stdio.h>
int main ( ) {
int i, j, n;
printf(\n);
do{
printf(Enter a positive number (0 to exit):);
scanf(%d, &n);
if (n>0)
for (i=1; i<=n; i++) {
for (j=1; j<=I; j++)
printf(%d, j);
printf(\n);
}
} 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 = (1x7
1
) + (5x 7
0
)
=12

binary
base 2
ex. 111111112 = 255

hexadecimal
0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11
16 = 2
4

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: char
ex.
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

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 =;

putchar(a); value of a=61
putchar(61);
putchar(=);

output
===

getchar();
alternative to scanf
grabs one character from the keyboard
ex.
printf(enter two characters: );
c1= getchar();
c2= getchar();
c3= getchar();

ex. # of keystrokes
#include <stdio.h>
int main ()
{
int c, 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);

return 0;
}


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, &num) != EOF) {
}


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 a
ex.
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 main
ex.
#include <stdio.h>

int rund (double a);

int main ()
{
double a;

printf("Enter a number: ");
scanf("%lf", &a);

printf("rounded to the nearest whole number: %d", rund(a));

return 0;
}

int rund (double a) {
if (a>0.)
return (int)(a+.5);
else
return (int)(a-.5);
}

ex.
#include <stdio.h>
#define FILE_NAME "/Users/Alicia/Documents/Dropbox/APS106-2013/7-Midterm/grades.txt"

/* function declarations */
int readGrades(int num_of_grades);
int writeGrade(int gradeAdd);

int main (void)
{
int choice, num;
int grade;
int error = 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) {
case 1:
printf ("How many grades would you like to read (0 for all)?");
scanf ("%d", &num);
error = readGrades(num);
if (error)
printf("There was an error reading the file. \n");
break;
case 2:
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;
case 3:
return 0;
default:
printf("Incorrect input \n");
}
if (error){
printf("An error has occurred in your program.\n");
break;
}
}
return -1;
}


int readGrades(int num_of_grades)
{
int i, 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<= num_of_grades; i++) {
while (fscanf(in, "%d", &grade) != EOF)
printf ("%d ", grade);
}
}
printf("\n");

fclose (in);
return 0;
}

int writeGrade(int gradeAdd)
{
FILE *outf;
outf = fopen (FILE_NAME, "a");
if (outf == NULL) {
printf ("file doesn't exist\n");
return -1;
}

fprintf (outf, "\n%d", gradeAdd);

fclose (outf);
return 0;
}



Arrays
Bubble sort
2D arrays
o dont need first dimension to be initialized
Ex. 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
address 0012FF7C

Ex.
//doesnt return the negative of the argument, but makes it negative inside the function.
#include <stdio.h>
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 <string.h>
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 (a
pointer 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) <= 0) /* is str1 <= str2?
*/

Ex.
char a[] = "scrabble", b[7];
char *ptr = a;
for ( ; *ptr = *(ptr+2); ++ptr ) ;
*a = *a - 14;
printf("%s\n", a);
strcpy(b, a);
strncpy(b, "bu", 2);
printf("%s %d\n", b, strlen(b));

Output:
dabble
bubble 6


ex.
int i, n; char *x, *y; printf ("how many? "); scanf ("%d", &n); x = (char*) malloc
((n+1)*sizeof(char)); y = x; for (i=0; i<n; i++) {
if (i%2)
*y = 'A'+i;
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 <stdlib.h>
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.
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 memory
E.g. free(a);




Random Number Generator
#include <time.h>
int number;
srand ((unsigned) time(NULL));
number = rand()%100+1;
(Num frm 1-100)
number = rand ( )%4;
(Numb from 0-3)

Você também pode gostar