Play with C

50 %
50 %
Information about Play with C

Published on April 8, 2009

Author: ankush85


Play with C : Play with C For Programmers Play with C : Play with C Why C now? Try programming in a different language Everything you do in Java (or other O-O language) can also implemented with C See the real world - learn to deal with pointers. Direct memory operation Abundant Internet resources on C “Learning C from Java” “C language tutorial” A good practice – part I, project 3 A Simple c program – “hello.c” : A Simple c program – “hello.c” /*---- Hello World C Example ("hello.c") -------------------------------------*/ /* ANSI C Headers */ #include <stdio.h> #include <stdlib.h> /* Main Program starts here */ void main( ) { int i = 0; /* End of declarations ... */ for ( i = 0; i < 10; i++ ) { printf( "%d Hello World ! \n", i ); /* print to standard output */ } } Include headers if you need to use functions in these files Declare all your variables first Comment: /* .. */ NOT // Compile C program : Compile C program Obtain a C compiler Linux/Unix (suggested! use your CS account) Usually c compiler is already installed Windows 2000/XP Microsoft Visual Studio has c compiler Downloadable Free GNU c compilers e. g. Compiling a single-source C program in Unix (use cc, gcc, or g++ ) e.g. cc –o hello hello.c - An executable file named “hello” will be generated. - “ cc hello.c “ is also okay. The output file will be named as “a.out”. cc –o <output file> <source_file> Run C program : Run C program Running the resulting program Just type the name of the executable file. e.g. hello If you local directory is not included in “PATH”, ./hello More details on C compilation and running Arrays in C : Arrays in C Array can be created with any type int a[5]; /* use a[0], a[1], .., a[4] */ char b[3] ; /* use b[0], b[1], b[2] */ float c[2] = { .1, .2}; /*initialization at declaration. c[0] = 0.1 , c[1]=0.2 */ double c[3][5]; /* two dimensional array (column major as Java) */ Array starts at 0. There is no boundary checking. Value of an array variable is the memory address of the first element. Character arrays can be used as strings char str[5]; strcpy(str, “hello”); /* str[0]=‘h’, str[1]=‘e’, …str[4]=‘o’*/ How to declare an array of strings ? 2D character array - char strs[20][5]; /* 20 strings with max-length=5 */ Example - Arrays in C : Example - Arrays in C #include <stdio.h> #include <stdlib.h> /* Print 26 letters in lower case and upper case */ void main() { char a[2] = {'a', 'A'}; /* One dimensional array */ int b[2][26]; /* Two dimensional array */ int i; for(i = 0; i < 26; i++) { b[0][i] = a[0] + i; /*Use the ASCII value of a[0] */ printf("%c ", b[0][i]); /*print the letter with ascii b[0][i] */ } printf("\n"); for(i = 0; i < 26; i++) { b[1][i] = a[1] + i; /*Use the ASCII value of a[1] */ printf("%c ", b[1][i]); /*print the letter with ascii b[1][i] */ } } Pointers in C : Pointers in C Declare pointers to any data type using dereference operator * int* int_ptr; char* ch_ptr; void* void_ptr; A pointer takes its value as the address in memory of another variable int a = 5 int* a_ptr; a_ptr = &a; /* ‘&’ : address of operator */ (*a_ptr) ++ ; /* ‘*’ : dereference operator */ a a_ptr Pointer example : Pointer example malloc, free – Allocate/Free Memory Blocks : malloc, free – Allocate/Free Memory Blocks Allocates memory blocks Returns a void pointer to the allocated space Return NULL if there is insufficient memory available To return a pointer to a type other than void, use a type cast on the return value. Example: int* i_ptr = (int*) malloc (10 * sizeof(int) ); /* Allocate a memory block with size of 10 int variables. */ Deallocates or frees a memory block. Example: free( i_ptr ); /* ignore if i_ptr is null */ void *malloc( size_t size ); void free( void *memblock ); Example of pointers, malloc, free : Example of pointers, malloc, free #include <stdio.h> #include <stdlib.h> void main() { int cost = 5, i; int* cost_ptr; cost_ptr = &cost; /*Let cost_ptr point to "cost“ */ printf("Pointer = %d. Dereference = %d\n", cost_ptr, *cost_ptr); cost_ptr = (int*) malloc( 10 * sizeof(int)); for (i = 0; i < 10; i++) { cost_ptr [i] = i*2; /* cost_ptr can be used as an array variable*/ printf("value %d: %d\t", i, cost_ptr[i]); /* You can also explicitly use the memory location of ith element (can be dangerous).*/ *(cost_ptr + sizeof(int) * i) = 2*i ; printf("value %d: %d\n", i, *(cost_ptr + sizeof(int) * i)); } /* Free the allocated mormory if you don't use it in the future */ free( cost_ptr); } Implement singly linked list in C : Implement singly linked list in C head Define structure with necessary data fields. struct StrListElement { int value; /* value of current list element */ struct StrListElement* next; /* pointing to next element in the list */ }; ... StrListElement temp; StrListElement* temp_ptr = &temp ; User can explicitly access structure data fields use ‘.’ or ‘->’ “->” is used after a pointer to structure variable: temp_ptr->value = 5; temp_ptr->next = null; “.” is used after a structure variable: temp.value = 5; = null; Add elements to the singly linked list : Add elements to the singly linked list struct StrListElement* head = NULL; //Head of the singly linked list struct StrListElement* str_elem_ptr; int i; for( i = 0; i < 5; i++) { /* Create an element which is going to be added into the list */ str_elem_ptr = (struct StrListElement* ) malloc ( sizeof(struct StrListElement)); str_elem_ptr -> value = i; /* /* Add new element to the head of the list */ str_elem_ptr -> next = head; head = str_elem_ptr; } head same function as addFirst method Other operations on singly linked list : Other operations on singly linked list Traverse elements in the list str_elem_ptr = head; while(str_elem_ptr != NULL) { printf("%d\n", str_elem_ptr->value); str_elem_ptr = str_elem_ptr -> next; } Delete elements from the head of list. Free the memory of deleted elements while(head != NULL) { str_elem_ptr = head; head = str_elem_ptr -> next; free(str_elem_ptr); } C functions : C functions A function has the following layout: return-type function-name ( argument-list-if-necessary ) e.g. int foo( int a, int b ) { ..} void f2(int* pa) {..} Arguments are always pass by values in C i.e. “Local copies'' of the values of the arguments are passed to the functions What if we want to pass values out of a function ? Solution 1: return value (but at most 1 value can returned) Solution 2: pointers Pass arguments in/out of C functions : Pass arguments in/out of C functions What are the values of v1 and v2 after swap1 and swap2 ? char v1=‘a’, v2 = ‘b’, char* p1 = &v1; char* p2 = &v2; swap1 ( v1, v2 ); swap2 ( p1, p2 ); void swap1 (char v1, char v2) { char temp; temp = v1; v1 = v2; v2 = temp; } void swap2 (char* v1, char* v2) { char temp; temp = *v1; *v1 = *v2; *v2 = temp; } /* v1 = ‘a’, v2 = ‘b’. */ /* v1 = ‘b’, v2 = ‘a’. */

Add a comment

Related presentations

Related pages - kostenlos und ohne anmeldung online spielen ...

Auf findet ihr eine einzigartige Auswahl an über 7'100 kostenlosen Spielen und Games, die ihr online und ohne Anmeldung spielen könnt.
Read more

Lilly Wood & The Prick and Robin Schulz - Prayer in C ...

Das offizielle Video zu Robins weltweiten Hit-Remix zu "Prayer in C" aus dem Album ... 86 videos Play all FRITACAO SUBSCRIBERS ...
Read more

Online Games - Free - Kostenlose Spiele bei - Home

Online-Games free, tausende kostenlose Online-Spiele, jetzt Games bei spielen., Spiele, Online-Games, kostenlose Online-Games, free Onlinegames ...
Read more

Rakuten - A new way to earn Super Points

Play the best new console and PC games. Earn up to 3% Super Points. Electricals ... By continuing to use, you agree to our Cookies Policy.
Read more

PLAY.CZ - Rádia on-line

PLAY.CZ Top 10. Evropa 2. 1954. Impuls Ráááádio. 1121. ČRo Radiožurnál. 737. Beat. 666. COUNTRY RADIO. 633. Frekvence 1. 580. ČRo Dvojka. 498 ...
Read more

Google Play

Play; YouTube; News; Gmail; Drive; More. Calendar; Translate; ... Powered by Google . Get 2 months of free music ... Louis C.K., Eric Stonestreet ...
Read more

Play Chess Online - Free Chess Games at

Play chess online, learn new chess strategies, tactics and rules, study chess games and openings - all FREE on - the #1 online chess site!
Read more

Home - Uplay

Download Uplay PC. Uplay PC is Ubisoft's PC games portal, where you can find all your games on PC. Download Uplay for PC
Read more

PS4 News, Magazin, Tests, Videos, Spiele -

Cross-Plattform-Play für Ubisofts VR-Spiele angekündigt – Eagle Flight, Werevolves Within und Star Trek: Bridge Crew.
Read more

Spiele bei - Spiele kostenlose Online-Spiele

The Best Online Games! Awesome action games, puzzle games, exciting sports games, mobile games & radical stunt games. Plus the worlds #1 pool game.
Read more