SlideShare une entreprise Scribd logo
1  sur  62
C / C++ Programming
5/3, Varathur Road, Kundalahalli Gate,
Bangalore-560066
+91- 9513332301 / 02
www.tibacademy.in
Topics
 ““Hello World" ProgramHello World" Program
 Data Types & VariablesData Types & Variables
 printf()printf()
 Arithmetic & LogicalArithmetic & Logical
OperationsOperations
 ConditionalsConditionals
 LoopsLoops
 Arrays & StringsArrays & Strings
 PointersPointers
 FunctionsFunctions
 Command-Line ArgumentCommand-Line Argument
 Data StructureData Structure
 Memory AllocationMemory Allocation
 Programming TipsProgramming Tips
 CC vvs. C++s. C++
 Books recommendedBooks recommended
Hello World Program
 The source codeThe source code
#include <stdio.h>#include <stdio.h>
int main()int main()
{{
printf("Hello Worldn");printf("Hello Worldn");
return(0);return(0);
}}
Hello World Program
 How to compile?How to compile?
$$ gcc hello.c –o hellogcc hello.c –o hello
gccgcc compiling commandcompiling command
hello.chello.c source filesource file
hellohello compiler-generated executable filecompiler-generated executable file
Note: the default output filename is “Note: the default output filename is “a.outa.out””
 How to executeHow to execute??
./hello./hello
““./ ” indicates the following file “hello” resides under the./ ” indicates the following file “hello” resides under the
current directory.current directory.
Hello World Program
Q: why “.” is not included in $PATHQ: why “.” is not included in $PATH
environment variable?environment variable?
Hello World Program
A: security consideration.A: security consideration.
CommandCommand LocationLocation CommentComment
lsls /bin/ls/bin/ls provided by theprovided by the
systemsystem
lsls current directorycurrent directory virusvirus
NameName DescriptionDescription Size*Size* Range*Range*
charchar Character or smallCharacter or small
integerinteger
1 byte1 byte signed: -128 to 127signed: -128 to 127
unsigned: 0 to 255unsigned: 0 to 255
short intshort int
(short)(short)
Short integerShort integer 2 bytes2 bytes signed: -32768 to 32767signed: -32768 to 32767
unsigned: 0 to 65535unsigned: 0 to 65535
intint IntegerInteger 4 bytes4 bytes signed: -2147483648 tosigned: -2147483648 to
21474836472147483647
unsigned: 0 to 4294967295unsigned: 0 to 4294967295
long intlong int
(long)(long)
Long integerLong integer 4 bytes4 bytes signed: -2147483648 tosigned: -2147483648 to
21474836472147483647
unsigned: 0 to 4294967295unsigned: 0 to 4294967295
floatfloat Floating pointFloating point
numbernumber
4 bytes4 bytes 3.4e +/- 38 (7 digits)3.4e +/- 38 (7 digits)
doubledouble Double precisionDouble precision
floating point numberfloating point number
8 bytes8 bytes 1.7e +/- 308 (15 digits)1.7e +/- 308 (15 digits)
longlong
doubledouble
Long doubleLong double
precision floatingprecision floating
point numberpoint number
8 bytes8 bytes 1.7e +/- 308 (15 digits)1.7e +/- 308 (15 digits)
Data types
 Variable DeclarationVariable Declaration
intint length = 100;length = 100;
charchar num = ‘9’; //The actual value is 57num = ‘9’; //The actual value is 57
floatfloat deposit = 240.5;deposit = 240.5;
unsigned shortunsigned short ID = 0x5544;ID = 0x5544;
Try the following statements, and see what happensTry the following statements, and see what happens
unsigned charunsigned char value = -1;value = -1;
printf(“The value is %d n”, value);printf(“The value is %d n”, value);
unsignedunsigned charchar value = 300;value = 300;
printf(“The value is %d n”, value);printf(“The value is %d n”, value);
Result
DefinitionDefinition Memory layoutMemory layout DisplayDisplay commentcomment
unsigned charunsigned char
value = -1value = -1
1111111111111111 255255
unsigned charunsigned char
value = 300value = 300
0010110000101100 4444 overflowoverflow
 Local variableLocal variable
Local variables are declared within the body of a function, and canLocal variables are declared within the body of a function, and can
only be used within that function.only be used within that function.
 Static variableStatic variable
Another class of local variable is the static type. It is specified by theAnother class of local variable is the static type. It is specified by the
keywordkeyword staticstatic in the variable declaration.in the variable declaration.
The most striking difference from a non-static local variable is, a staticThe most striking difference from a non-static local variable is, a static
variable is not destroyed on exit from the function.variable is not destroyed on exit from the function.
 Global variableGlobal variable
A global variable declaration looks normal, but is located outside anyA global variable declaration looks normal, but is located outside any
of the program's functions. So it is accessible to all functions.of the program's functions. So it is accessible to all functions.
Variable types
 An exampleAn example
int global = 10;int global = 10; //global variable//global variable
int func (int x)int func (int x)
{{
static int stat_var;static int stat_var; //static local variable//static local variable
int temp;int temp; //(normal) local variable//(normal) local variable
int name[50];int name[50]; //(normal) local variable//(normal) local variable
…………
}}
Variable Definition vs Declaration
DefinitionDefinition Tell the compiler about the variable: its typeTell the compiler about the variable: its type
and name, as well as allocated a memory cell forand name, as well as allocated a memory cell for
the variablethe variable
DeclarationDeclaration DDescribe information ``about'' the variableescribe information ``about'' the variable,,
doesn’tdoesn’t allocate memory cell for the variableallocate memory cell for the variable
http://www-ee.eng.hawaii.edu/~tep/EE150/book/chap14/subsection2.1.1.4.html
printf()
The printf() function can be instructed to printThe printf() function can be instructed to print
integers, floats and string properly.integers, floats and string properly.
 The general syntax isThe general syntax is
printfprintf( “format”, variables);( “format”, variables);
 An exampleAn example
intint stud_id = 5200;stud_id = 5200;
char * name = “Mike”;char * name = “Mike”;
printfprintf(“(“%s%s ‘s ID is‘s ID is %d%d n”, name, stud_id);n”, name, stud_id);
 Format IdentifiersFormat Identifiers
%d%d decimal integersdecimal integers
%x%x hex integerhex integer
%c%c charactercharacter
%f%f float and double numberfloat and double number
%s%s stringstring
%p%p pointerpointer
 How to specify display space for a variableHow to specify display space for a variable??
printf(“The student id is %printf(“The student id is %55d n”, stud_id);d n”, stud_id);
The value of stud_id will occupyThe value of stud_id will occupy 55 characters space in thecharacters space in the
print-out.print-out.
 Why “n”Why “n”
It introduces a new line on the terminal screen.It introduces a new line on the terminal screen.
aa alert (bell) characteralert (bell) character  backslashbackslash
bb backspacebackspace ?? question markquestion mark
ff formfeedformfeed ’’ single quotesingle quote
nn newlinenewline ”” double quotedouble quote
rr carriage returncarriage return 000000 octal numberoctal number
tt horizontal tabhorizontal tab xhhxhh hexadecimalhexadecimal
numbernumber
vv vertical tabvertical tab
escape sequence
Arithmetic Operations
Arithmetic Assignment Operators
Increment and Decrement
Operators
awkwardawkward easyeasy easiesteasiest
x = x+1;x = x+1; x += 1x += 1 x++x++
x = x-1;x = x-1; x -= 1x -= 1 x--x--
Example
 Arithmetic operatorsArithmetic operators
int i = 10;int i = 10;
int j = 15;int j = 15;
int add = i + j;int add = i + j; //25//25
int diff = j – i;int diff = j – i; //5//5
int product = i * j;int product = i * j; // 150// 150
int quotient = j / i;int quotient = j / i; // 1// 1
iint residual = j %nt residual = j % i; // 5i; // 5
i++;i++; //Increase by 1//Increase by 1
i--;i--; //Decrease by 1//Decrease by 1
 Comparing themComparing them
int i = 10;int i = 10;
int j = 15;int j = 15;
float k = 15.0;float k = 15.0;
j / i = ?j / i = ?
j % i = ?j % i = ?
k / i = ?k / i = ?
k % i = ?k % i = ?
 The AnswerThe Answer
j /j / ii = 1;= 1;
j % i = 5;j % i = 5;
k / ik / i = 1.5;= 1.5;
k % i It isk % i It is illegalillegal..
Note: For %, the operands can only be integers.Note: For %, the operands can only be integers.
Logical Operations
 What is “true” and “false” in CWhat is “true” and “false” in C
In C, there is no specific data type to represent “true” and “false”. CIn C, there is no specific data type to represent “true” and “false”. C
uses value “0” to represent “false”, and uses non-zero value to standuses value “0” to represent “false”, and uses non-zero value to stand
for “true”.for “true”.
 Logical OperatorsLogical Operators
A && BA && B =>=> A and BA and B
A || BA || B =>=> A or BA or B
A == BA == B =>=> Is A equal to B?Is A equal to B?
A != BA != B => Is A not equal to B?=> Is A not equal to B?
A > BA > B =>=> Is A greater than B?Is A greater than B?
A >= BA >= B => Is A greater than or equal to B?=> Is A greater than or equal to B?
A < BA < B =>=> Is A less than B?Is A less than B?
A <= BA <= B => Is A less than or equal to B?=> Is A less than or equal to B?
 Don’t be confusedDon’t be confused
&& and || have different meanings from & and |.&& and || have different meanings from & and |.
& and | are& and | are bitwisebitwise operators.operators.
Short circuiting
 SShort circuiting means that we don'thort circuiting means that we don't
evaluate the second part of an AND or ORevaluate the second part of an AND or OR
unless we really need tounless we really need to..
Some practicesSome practices
Please compute the value of the followingPlease compute the value of the following
logical expressions?logical expressions?
int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>if( i < j && j < k) =>
if( i != j || k < j) =>if( i != j || k < j) =>
if( j<= k || i > k) =>if( j<= k || i > k) =>
if( j == k && m) =>if( j == k && m) =>
if(i)if(i) =>=>
if(m || j && i )if(m || j && i ) =>=>
int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>if( i < j && j < k) => falsefalse
if( i != j || k < j) =>if( i != j || k < j) => truetrue
if( j<= k || i > k) =>if( j<= k || i > k) => truetrue
if( j == k && m) =>if( j == k && m) => falsefalse
if(i)if(i) =>=> truetrue
if(m || j && i )if(m || j && i ) =>=> truetrue
Did you get the correct answers?Did you get the correct answers?
Conditionals
 if statementif statement
Three basic formats,Three basic formats,
ifif ((expressionexpression){){
statement …statement …
}}
ifif ((expressionexpression) {) {
statement …statement …
}}elseelse{{
statement …statement …
}}
if (if (expressionexpression) {) {
statement…statement…
}}else ifelse if ((expressionexpression) {) {
statement…statement…
}}else{else{
statement…statement…
}}
 An exampleAn example
if(score >= 90){if(score >= 90){
a_cnt ++;a_cnt ++;
}else if(score >= 80){}else if(score >= 80){
b_cnt++;b_cnt++;
}else if(score >= 70){}else if(score >= 70){
c_cnt++;c_cnt++;
}else if (score>= 60){}else if (score>= 60){
d_cnt++d_cnt++
}else{}else{
f_cnt++f_cnt++
}}
 The switch statementThe switch statement
switch (switch (expressionexpression) ) 
{{
casecase item1item1::
statementstatement;;
break;break;
casecase item2item2::
statementstatement;;
break;break;
default:default:
statementstatement;;
break;break;
}}
Loops
 for statementfor statement
for (for (expression1expression1;; expression2expression2;; expression3expression3)){{
statement…statement…
}}
expression1expression1 initializes;initializes;
expression2expression2 is the terminate test;is the terminate test;
expression3expression3 is the modifieris the modifier;;
 An exampleAn example
int x;int x;
for (x=0; x<3; x++)for (x=0; x<3; x++)
{{
printf("x=%dprintf("x=%dn",x);n",x);
}}
First time:First time: x = 0;x = 0;
Second time:Second time: x = 1;x = 1;
Third time:Third time: x = 2;x = 2;
Fourth time:Fourth time: x = 3; (donx = 3; (don’’t execute the body)t execute the body)
 The while statementThe while statement
while (while (expressionexpression) {) {
statementstatement ……
}}
while loop exits only when the expression is false.while loop exits only when the expression is false.
 An exampleAn example
int x = 3;int x = 3;
while (x>0) {while (x>0) {
printf("x=%d n",x);printf("x=%d n",x);
x--;x--;
}}
for <==> while
for (for (expression1expression1;;
expression2expression2;;
expression3expression3)){{
statement…statement…
}}
expression1;expression1;
while (expression2)while (expression2)
{{
statementstatement……;;
expression3;expression3;
}}
equals
Arrays & Strings
 ArraysArrays
int ids[50];int ids[50];
char name[100];char name[100];
int table_of_num[30][40];int table_of_num[30][40];
 Accessing an arrayAccessing an array
ids[0] = 40;ids[0] = 40;
i = ids[1] + j;i = ids[1] + j;
table_of_num[3][4] = 100;table_of_num[3][4] = 100;
Note: In C Array subscripts start atNote: In C Array subscripts start at 00 and end one less thanand end one less than
the array size.the array size. [0 .. n-1][0 .. n-1]
 StringsStrings
Strings are defined as arrays of characters.Strings are defined as arrays of characters.
The only difference from a character array is, a symbol “0”The only difference from a character array is, a symbol “0”
is used to indicate the end of a string.is used to indicate the end of a string.
For example, suppose we have a character array, charFor example, suppose we have a character array, char
name[8], and we store into it a string “Dave”.name[8], and we store into it a string “Dave”.
Note: the length of this string 4, but it occupies 5 bytes.Note: the length of this string 4, but it occupies 5 bytes.
DD aa vv ee 00
Functions
Functions are easy to use; they allow complicated programs to be brokenFunctions are easy to use; they allow complicated programs to be broken
into small blocks, each of which is easier to write, read, and maintain.into small blocks, each of which is easier to write, read, and maintain.
This is calledThis is called modulationmodulation..
 HowHow doesdoes a function look likea function look like??
returntypereturntype function_name(function_name(parameters…parameters…)    )    
{  {  
locallocal variables declaration;variables declaration;   
functionfunction code;code;
return result;  return result;  
}}
 Sample functionSample function
int addition(int x, int y)int addition(int x, int y)
{{
int add;int add;
add = x + y;add = x + y;
return add;return add;
}}
 How toHow to call a function?call a function?
int result;int result;
int i = 5, j = 6;int i = 5, j = 6;
result = addition(i, j);result = addition(i, j);
Pointers
Pointer is the most beautifulPointer is the most beautiful ((ugliestugliest)) part of C, but alsopart of C, but also
brings most trouble to C programmers. Over 90% bugs inbrings most trouble to C programmers. Over 90% bugs in
the C programs cthe C programs coome from pointers.me from pointers.
““The International Obfuscated C Code ContestThe International Obfuscated C Code Contest ””
((http://www.ioccc.org/http://www.ioccc.org/))
 What is a pointerWhat is a pointer??
A pointer is a variable which contains the address in memoryA pointer is a variable which contains the address in memory
of another variable.of another variable.
In C we have a specific type for pointers.In C we have a specific type for pointers.
 Declaring a pointer variableDeclaring a pointer variable
int * pointer;int * pointer;
char * name;char * name;
 How to obtain theHow to obtain the addressaddress of a variableof a variable??
int x = 0x2233;int x = 0x2233;
pointer = &x;pointer = &x;
where & is calledwhere & is called address ofaddress of operator.operator.
 How to get theHow to get the valuevalue of the variable indicated by theof the variable indicated by the
pointerpointer??
int y = *pointer;int y = *pointer;
3333 2222 0000 0000
0x5200 0x5203
0x5200
pointer
What happens in the memory?
Suppose the address of variable x is 0x5200 in the above
example, so the value of the variable pointer is 0x5200.
X
swap the value of two variables
Why is the left one not working?
swap
main
x, y
a, b
call swap(a, b) in main
x, y, a, b are
all local
variables
Why is the right one working?
 Pointers and ArraysPointers and Arrays
Pointers and arrays are very closely linked in C.Pointers and arrays are very closely linked in C.
Array elements arranged inArray elements arranged in consecutiveconsecutive memory locationsmemory locations
 Accessing array elements using pointersAccessing array elements using pointers
int ids[50];int ids[50];
int * p = &ids[0];int * p = &ids[0];
p[i]p[i] <<=>=> ids[i]ids[i]
 Pointers and StringsPointers and Strings
A string can be represented by aA string can be represented by a char *char * pointer.pointer.
Char name[50];Char name[50];
name[0] = ‘D’;name[0] = ‘D’;
name[1] = ‘a’;name[1] = ‘a’;
name[2] = ‘v’;name[2] = ‘v’;
name[3] = ‘e’;name[3] = ‘e’;
name[4] = ‘0’;name[4] = ‘0’;
char * p = &name[0];char * p = &name[0];
printf(“The name is %s n”, p);printf(“The name is %s n”, p);
NoteNote:: TheThe pp represents the string “Dave”, but not the arrayrepresents the string “Dave”, but not the array
name[50].name[50].
Command-Line Argument
In C you can pass arguments to main() function.In C you can pass arguments to main() function.
 mmain() prototypeain() prototype
int main(int argc, char * argv[]);int main(int argc, char * argv[]);
argc indicates the number of argumentsargc indicates the number of arguments
argv is an array of input string pointers.argv is an array of input string pointers.
 How to pass your own argumentsHow to pass your own arguments??
./hello 10./hello 10
 What value is argc and argvWhat value is argc and argv??
Let’s add two printf statement to get the value of argc andLet’s add two printf statement to get the value of argc and
argv.argv.
#include <stdio.h>#include <stdio.h>
int main(int main(int argc, char * argv[]);int argc, char * argv[]);))
{{
int i=0;int i=0;
printf("Hello Worldn");printf("Hello Worldn");
printf(“The argc is %d n”, argc);printf(“The argc is %d n”, argc);
for(i=0; i < argc; i++){for(i=0; i < argc; i++){
printf(“The %dth element in argv is %sn”, i, argv[i]);printf(“The %dth element in argv is %sn”, i, argv[i]);
}}
return(0);return(0);
}}
 The outputThe output
The argc is 2The argc is 2
The 0th element in argv is ./helloThe 0th element in argv is ./hello
The 1th element in argv is 10The 1th element in argv is 10
The trick is the system always passes the name of theThe trick is the system always passes the name of the
executable file as theexecutable file as the firstfirst argument to the main() function.argument to the main() function.
 How to use your argumentHow to use your argument??
Be careful. Your arguments to main() are always in string format.Be careful. Your arguments to main() are always in string format.
Taking the above program for example, the argv[1] is string “10”,Taking the above program for example, the argv[1] is string “10”,
not a number. You must convert it into a number before you cannot a number. You must convert it into a number before you can
use it.use it.
Data Structure
A data structure is a collection of one or more variables, possibly ofA data structure is a collection of one or more variables, possibly of
different types.different types.
 An example of student recordAn example of student record
structstruct stud_record{stud_record{
char name[50];char name[50];
int id;int id;
int age;int age;
int major;int major;
…………
};};
 A data structure is also a data typeA data structure is also a data type
struct stud_record my_record;struct stud_record my_record;
struct stud_record * pointer;struct stud_record * pointer;
pointer = & my_record;pointer = & my_record;
 Accessing a field inside a data structureAccessing a field inside a data structure
my_record.id = 10;my_record.id = 10; “.”“.”
oror
pointer->id = 10;pointer->id = 10; “->”“->”
Memory Allocation
 Stack memory allocationStack memory allocation
Non-static local variable is an example of stack memoryNon-static local variable is an example of stack memory
allocation.allocation.
Such memory allocations are placed in a system memorySuch memory allocations are placed in a system memory
area called thearea called the stackstack..
 Static memory allocationStatic memory allocation
Static local variable and global variable require staticStatic local variable and global variable require static
memory allocation. Static memory allocation happensmemory allocation. Static memory allocation happens
before the program starts, andbefore the program starts, and persistspersists through the entirethrough the entire
life time of the program.life time of the program.
 Dynamic memory allocationDynamic memory allocation
It allows the program determine how much memory itIt allows the program determine how much memory it
needsneeds atat run timerun time,, and allocate exactly the right amount ofand allocate exactly the right amount of
storage.storage.
The region of memory where dynamic allocation andThe region of memory where dynamic allocation and
deallocation of memory can take place is called thedeallocation of memory can take place is called the heapheap..
NoteNote: the program has the responsibility to free the: the program has the responsibility to free the
dynamic memory it allocated.dynamic memory it allocated.
Memory arrangement
 Functions for the dynamic memory allocationFunctions for the dynamic memory allocation
void *malloc(size_t number_of_bytes);void *malloc(size_t number_of_bytes);
allocates dynamic memoryallocates dynamic memory
size_t sizeof(type);size_t sizeof(type);
returns the number of bytes of typereturns the number of bytes of type
void free(void * p)void free(void * p)
releases dynamic memory allocationreleases dynamic memory allocation
 An example of dynamic memory allocationAn example of dynamic memory allocation
int * ids;int * ids; //id arrays//id arrays
int num_of_ids = 40;int num_of_ids = 40;
ids = malloc( sizeof(int) * num_of_ids);ids = malloc( sizeof(int) * num_of_ids);
………….. Processing …..... Processing …...
free(ids);free(ids);
 Allocating a data structure instanceAllocating a data structure instance
struct stud_record * pointer;struct stud_record * pointer;
pointer = malloc(pointer = malloc(sizeofsizeof(struct stud_record));(struct stud_record));
pointer->id = 10;pointer->id = 10;
NeverNever calculate the size of data structure yourself.calculate the size of data structure yourself. TheThe
reason is the size of data types isreason is the size of data types is machine-dependentmachine-dependent.. GiveGive
it to sizeof() functionit to sizeof() function..
size of intsize of int
32-bytes machines32-bytes machines 3232
64-bytes machines64-bytes machines 6464
Programming Tips
 Replacing numbers in your code with macrosReplacing numbers in your code with macros
- don’t use- don’t use magic numbersmagic numbers directlydirectly
#define MAX_NAME_LEN#define MAX_NAME_LEN 50;50;
char name[MAX_NAME_LEN];char name[MAX_NAME_LEN];
 Avoiding global variablesAvoiding global variables
- modulation is more important- modulation is more important
 Giving variables and functions a nice nameGiving variables and functions a nice name
- a meaning name- a meaning name
 Don’t repeat your codeDon’t repeat your code
- make a subroutine/function- make a subroutine/function
 Don’t let the function body to exceed one screenDon’t let the function body to exceed one screen
- hard to debug- hard to debug
 Indenting your codeIndenting your code (clearance)(clearance)
iif(expression)f(expression)
{{
if(expression)if(expression)
{{
…………
}}
}}
 Commenting your codeCommenting your code
 Don’t rush into coding. Plan first.Don’t rush into coding. Plan first.
 Printing out more debugging informationPrinting out more debugging information
 Using debuggerUsing debugger (gdb)(gdb)
C vs. C++
 C++ is a superset of CC++ is a superset of C
 C++ has all the characteristics of CC++ has all the characteristics of C
 Using g++ to compile your source codeUsing g++ to compile your source code
Books recommended
 The C Programming LanguageThe C Programming Language, Brian Kernighan, Brian Kernighan
and Dennis Ritchie. Second edition. Prentice-Hall,and Dennis Ritchie. Second edition. Prentice-Hall,
1988.1988. (C Bible)(C Bible)
 The C++ Programming LanguageThe C++ Programming Language, Bjarne, Bjarne
Stroustrup. Third edition. Addison-Wesley, 1997.Stroustrup. Third edition. Addison-Wesley, 1997.
(C++ Bible)(C++ Bible)
 Advanced Programming in the UNIXAdvanced Programming in the UNIX
EnvironmentEnvironment,, W. Richard StevensW. Richard Stevens,, Addison-Addison-
Wesley, 1992Wesley, 1992.. (APUE)(APUE)
Thanks

Contenu connexe

Tendances

Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
natarafonseca
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproce
Hector Garzo
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standards
Hector Garzo
 

Tendances (19)

C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
What is c
What is cWhat is c
What is c
 
Elements of c program....by thanveer danish
Elements of c program....by thanveer danishElements of c program....by thanveer danish
Elements of c program....by thanveer danish
 
Selection & Making Decisions in c
Selection & Making Decisions in cSelection & Making Decisions in c
Selection & Making Decisions in c
 
Programming C Language
Programming C LanguageProgramming C Language
Programming C Language
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
C language basics
C language basicsC language basics
C language basics
 
C language basics
C language basicsC language basics
C language basics
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproce
 
C program compiler presentation
C program compiler presentationC program compiler presentation
C program compiler presentation
 
Clean code - Agile Software Craftsmanship
Clean code - Agile Software CraftsmanshipClean code - Agile Software Craftsmanship
Clean code - Agile Software Craftsmanship
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standards
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
Aptitute question papers in c
Aptitute question papers in cAptitute question papers in c
Aptitute question papers in c
 
Programming in C [Module One]
Programming in C [Module One]Programming in C [Module One]
Programming in C [Module One]
 
Decision making statements in C
Decision making statements in CDecision making statements in C
Decision making statements in C
 

Similaire à C C++ tutorial for beginners- tibacademy.in

presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
KrishanPalSingh39
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
Julien Wetterwald
 

Similaire à C C++ tutorial for beginners- tibacademy.in (20)

presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
 
CPU
CPUCPU
CPU
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
1 introduction to c program
1 introduction to c program1 introduction to c program
1 introduction to c program
 
the refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptxthe refernce of programming C notes ppt.pptx
the refernce of programming C notes ppt.pptx
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Programming in C Basics
Programming in C BasicsProgramming in C Basics
Programming in C Basics
 
Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02Primitive Data Types and Variables Lesson 02
Primitive Data Types and Variables Lesson 02
 
OpenGurukul : Language : C Programming
OpenGurukul : Language : C ProgrammingOpenGurukul : Language : C Programming
OpenGurukul : Language : C Programming
 
Control structure of c
Control structure of cControl structure of c
Control structure of c
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 

Plus de TIB Academy

Plus de TIB Academy (18)

AWS Training Institute in Bangalore | Best AWS Course In Bangalore
AWS Training Institute in Bangalore | Best AWS Course In BangaloreAWS Training Institute in Bangalore | Best AWS Course In Bangalore
AWS Training Institute in Bangalore | Best AWS Course In Bangalore
 
MySQL training in Bangalore | Best MySQL Course in Bangalore
MySQL training in Bangalore | Best MySQL Course in BangaloreMySQL training in Bangalore | Best MySQL Course in Bangalore
MySQL training in Bangalore | Best MySQL Course in Bangalore
 
CCNA Training in Bangalore | Best Networking course in Bangalore
CCNA Training in Bangalore | Best Networking course in BangaloreCCNA Training in Bangalore | Best Networking course in Bangalore
CCNA Training in Bangalore | Best Networking course in Bangalore
 
Core Java Training in Bangalore | Best Core Java Class in Bangalore
Core Java Training in Bangalore | Best Core Java Class in BangaloreCore Java Training in Bangalore | Best Core Java Class in Bangalore
Core Java Training in Bangalore | Best Core Java Class in Bangalore
 
Advance Java Training in Bangalore | Best Java Training Institute
Advance Java Training in Bangalore | Best Java Training Institute Advance Java Training in Bangalore | Best Java Training Institute
Advance Java Training in Bangalore | Best Java Training Institute
 
Best Hadoop Training in Bangalore - TIB Academy
Best Hadoop Training in Bangalore - TIB AcademyBest Hadoop Training in Bangalore - TIB Academy
Best Hadoop Training in Bangalore - TIB Academy
 
Selenium training for beginners
Selenium training for beginnersSelenium training for beginners
Selenium training for beginners
 
Python Training
Python TrainingPython Training
Python Training
 
TIB Academy provides best Oracal DBA classes in Bangalore
TIB Academy provides best Oracal DBA classes in BangaloreTIB Academy provides best Oracal DBA classes in Bangalore
TIB Academy provides best Oracal DBA classes in Bangalore
 
java tutorial for beginner - Free Download
java tutorial for beginner - Free Downloadjava tutorial for beginner - Free Download
java tutorial for beginner - Free Download
 
Aws tutorial for beginners- tibacademy.in
Aws tutorial for beginners- tibacademy.inAws tutorial for beginners- tibacademy.in
Aws tutorial for beginners- tibacademy.in
 
Java tutorial for beginners-tibacademy.in
Java tutorial for beginners-tibacademy.inJava tutorial for beginners-tibacademy.in
Java tutorial for beginners-tibacademy.in
 
Android tutorial for beginners-traininginbangalore.com
Android tutorial for beginners-traininginbangalore.comAndroid tutorial for beginners-traininginbangalore.com
Android tutorial for beginners-traininginbangalore.com
 
Hadoop tutorial for beginners-tibacademy.in
Hadoop tutorial for beginners-tibacademy.inHadoop tutorial for beginners-tibacademy.in
Hadoop tutorial for beginners-tibacademy.in
 
SoapUI Training in Bangalore
SoapUI Training in BangaloreSoapUI Training in Bangalore
SoapUI Training in Bangalore
 
R programming
R programmingR programming
R programming
 
Spring-training-in-bangalore
Spring-training-in-bangaloreSpring-training-in-bangalore
Spring-training-in-bangalore
 
Salesforce Certification
Salesforce CertificationSalesforce Certification
Salesforce Certification
 

Dernier

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Dernier (20)

Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

C C++ tutorial for beginners- tibacademy.in

  • 1. C / C++ Programming 5/3, Varathur Road, Kundalahalli Gate, Bangalore-560066 +91- 9513332301 / 02 www.tibacademy.in
  • 2. Topics  ““Hello World" ProgramHello World" Program  Data Types & VariablesData Types & Variables  printf()printf()  Arithmetic & LogicalArithmetic & Logical OperationsOperations  ConditionalsConditionals  LoopsLoops  Arrays & StringsArrays & Strings  PointersPointers  FunctionsFunctions  Command-Line ArgumentCommand-Line Argument  Data StructureData Structure  Memory AllocationMemory Allocation  Programming TipsProgramming Tips  CC vvs. C++s. C++  Books recommendedBooks recommended
  • 3. Hello World Program  The source codeThe source code #include <stdio.h>#include <stdio.h> int main()int main() {{ printf("Hello Worldn");printf("Hello Worldn"); return(0);return(0); }}
  • 4. Hello World Program  How to compile?How to compile? $$ gcc hello.c –o hellogcc hello.c –o hello gccgcc compiling commandcompiling command hello.chello.c source filesource file hellohello compiler-generated executable filecompiler-generated executable file Note: the default output filename is “Note: the default output filename is “a.outa.out””
  • 5.  How to executeHow to execute?? ./hello./hello ““./ ” indicates the following file “hello” resides under the./ ” indicates the following file “hello” resides under the current directory.current directory. Hello World Program Q: why “.” is not included in $PATHQ: why “.” is not included in $PATH environment variable?environment variable?
  • 6. Hello World Program A: security consideration.A: security consideration. CommandCommand LocationLocation CommentComment lsls /bin/ls/bin/ls provided by theprovided by the systemsystem lsls current directorycurrent directory virusvirus
  • 7. NameName DescriptionDescription Size*Size* Range*Range* charchar Character or smallCharacter or small integerinteger 1 byte1 byte signed: -128 to 127signed: -128 to 127 unsigned: 0 to 255unsigned: 0 to 255 short intshort int (short)(short) Short integerShort integer 2 bytes2 bytes signed: -32768 to 32767signed: -32768 to 32767 unsigned: 0 to 65535unsigned: 0 to 65535 intint IntegerInteger 4 bytes4 bytes signed: -2147483648 tosigned: -2147483648 to 21474836472147483647 unsigned: 0 to 4294967295unsigned: 0 to 4294967295 long intlong int (long)(long) Long integerLong integer 4 bytes4 bytes signed: -2147483648 tosigned: -2147483648 to 21474836472147483647 unsigned: 0 to 4294967295unsigned: 0 to 4294967295 floatfloat Floating pointFloating point numbernumber 4 bytes4 bytes 3.4e +/- 38 (7 digits)3.4e +/- 38 (7 digits) doubledouble Double precisionDouble precision floating point numberfloating point number 8 bytes8 bytes 1.7e +/- 308 (15 digits)1.7e +/- 308 (15 digits) longlong doubledouble Long doubleLong double precision floatingprecision floating point numberpoint number 8 bytes8 bytes 1.7e +/- 308 (15 digits)1.7e +/- 308 (15 digits) Data types
  • 8.  Variable DeclarationVariable Declaration intint length = 100;length = 100; charchar num = ‘9’; //The actual value is 57num = ‘9’; //The actual value is 57 floatfloat deposit = 240.5;deposit = 240.5; unsigned shortunsigned short ID = 0x5544;ID = 0x5544; Try the following statements, and see what happensTry the following statements, and see what happens unsigned charunsigned char value = -1;value = -1; printf(“The value is %d n”, value);printf(“The value is %d n”, value); unsignedunsigned charchar value = 300;value = 300; printf(“The value is %d n”, value);printf(“The value is %d n”, value);
  • 9. Result DefinitionDefinition Memory layoutMemory layout DisplayDisplay commentcomment unsigned charunsigned char value = -1value = -1 1111111111111111 255255 unsigned charunsigned char value = 300value = 300 0010110000101100 4444 overflowoverflow
  • 10.  Local variableLocal variable Local variables are declared within the body of a function, and canLocal variables are declared within the body of a function, and can only be used within that function.only be used within that function.  Static variableStatic variable Another class of local variable is the static type. It is specified by theAnother class of local variable is the static type. It is specified by the keywordkeyword staticstatic in the variable declaration.in the variable declaration. The most striking difference from a non-static local variable is, a staticThe most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function.variable is not destroyed on exit from the function.  Global variableGlobal variable A global variable declaration looks normal, but is located outside anyA global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions.of the program's functions. So it is accessible to all functions. Variable types
  • 11.  An exampleAn example int global = 10;int global = 10; //global variable//global variable int func (int x)int func (int x) {{ static int stat_var;static int stat_var; //static local variable//static local variable int temp;int temp; //(normal) local variable//(normal) local variable int name[50];int name[50]; //(normal) local variable//(normal) local variable ………… }}
  • 12. Variable Definition vs Declaration DefinitionDefinition Tell the compiler about the variable: its typeTell the compiler about the variable: its type and name, as well as allocated a memory cell forand name, as well as allocated a memory cell for the variablethe variable DeclarationDeclaration DDescribe information ``about'' the variableescribe information ``about'' the variable,, doesn’tdoesn’t allocate memory cell for the variableallocate memory cell for the variable
  • 14. printf() The printf() function can be instructed to printThe printf() function can be instructed to print integers, floats and string properly.integers, floats and string properly.  The general syntax isThe general syntax is printfprintf( “format”, variables);( “format”, variables);  An exampleAn example intint stud_id = 5200;stud_id = 5200; char * name = “Mike”;char * name = “Mike”; printfprintf(“(“%s%s ‘s ID is‘s ID is %d%d n”, name, stud_id);n”, name, stud_id);
  • 15.  Format IdentifiersFormat Identifiers %d%d decimal integersdecimal integers %x%x hex integerhex integer %c%c charactercharacter %f%f float and double numberfloat and double number %s%s stringstring %p%p pointerpointer  How to specify display space for a variableHow to specify display space for a variable?? printf(“The student id is %printf(“The student id is %55d n”, stud_id);d n”, stud_id); The value of stud_id will occupyThe value of stud_id will occupy 55 characters space in thecharacters space in the print-out.print-out.
  • 16.  Why “n”Why “n” It introduces a new line on the terminal screen.It introduces a new line on the terminal screen. aa alert (bell) characteralert (bell) character backslashbackslash bb backspacebackspace ?? question markquestion mark ff formfeedformfeed ’’ single quotesingle quote nn newlinenewline ”” double quotedouble quote rr carriage returncarriage return 000000 octal numberoctal number tt horizontal tabhorizontal tab xhhxhh hexadecimalhexadecimal numbernumber vv vertical tabvertical tab escape sequence
  • 19. Increment and Decrement Operators awkwardawkward easyeasy easiesteasiest x = x+1;x = x+1; x += 1x += 1 x++x++ x = x-1;x = x-1; x -= 1x -= 1 x--x--
  • 20. Example  Arithmetic operatorsArithmetic operators int i = 10;int i = 10; int j = 15;int j = 15; int add = i + j;int add = i + j; //25//25 int diff = j – i;int diff = j – i; //5//5 int product = i * j;int product = i * j; // 150// 150 int quotient = j / i;int quotient = j / i; // 1// 1 iint residual = j %nt residual = j % i; // 5i; // 5 i++;i++; //Increase by 1//Increase by 1 i--;i--; //Decrease by 1//Decrease by 1
  • 21.  Comparing themComparing them int i = 10;int i = 10; int j = 15;int j = 15; float k = 15.0;float k = 15.0; j / i = ?j / i = ? j % i = ?j % i = ? k / i = ?k / i = ? k % i = ?k % i = ?
  • 22.  The AnswerThe Answer j /j / ii = 1;= 1; j % i = 5;j % i = 5; k / ik / i = 1.5;= 1.5; k % i It isk % i It is illegalillegal.. Note: For %, the operands can only be integers.Note: For %, the operands can only be integers.
  • 23. Logical Operations  What is “true” and “false” in CWhat is “true” and “false” in C In C, there is no specific data type to represent “true” and “false”. CIn C, there is no specific data type to represent “true” and “false”. C uses value “0” to represent “false”, and uses non-zero value to standuses value “0” to represent “false”, and uses non-zero value to stand for “true”.for “true”.  Logical OperatorsLogical Operators A && BA && B =>=> A and BA and B A || BA || B =>=> A or BA or B A == BA == B =>=> Is A equal to B?Is A equal to B? A != BA != B => Is A not equal to B?=> Is A not equal to B?
  • 24. A > BA > B =>=> Is A greater than B?Is A greater than B? A >= BA >= B => Is A greater than or equal to B?=> Is A greater than or equal to B? A < BA < B =>=> Is A less than B?Is A less than B? A <= BA <= B => Is A less than or equal to B?=> Is A less than or equal to B?  Don’t be confusedDon’t be confused && and || have different meanings from & and |.&& and || have different meanings from & and |. & and | are& and | are bitwisebitwise operators.operators.
  • 25. Short circuiting  SShort circuiting means that we don'thort circuiting means that we don't evaluate the second part of an AND or ORevaluate the second part of an AND or OR unless we really need tounless we really need to.. Some practicesSome practices Please compute the value of the followingPlease compute the value of the following logical expressions?logical expressions?
  • 26. int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) =>if( i < j && j < k) => if( i != j || k < j) =>if( i != j || k < j) => if( j<= k || i > k) =>if( j<= k || i > k) => if( j == k && m) =>if( j == k && m) => if(i)if(i) =>=> if(m || j && i )if(m || j && i ) =>=>
  • 27. int i = 10; int j = 15; int k = 15; int m = 0;int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) =>if( i < j && j < k) => falsefalse if( i != j || k < j) =>if( i != j || k < j) => truetrue if( j<= k || i > k) =>if( j<= k || i > k) => truetrue if( j == k && m) =>if( j == k && m) => falsefalse if(i)if(i) =>=> truetrue if(m || j && i )if(m || j && i ) =>=> truetrue Did you get the correct answers?Did you get the correct answers?
  • 28. Conditionals  if statementif statement Three basic formats,Three basic formats, ifif ((expressionexpression){){ statement …statement … }} ifif ((expressionexpression) {) { statement …statement … }}elseelse{{ statement …statement … }}
  • 29. if (if (expressionexpression) {) { statement…statement… }}else ifelse if ((expressionexpression) {) { statement…statement… }}else{else{ statement…statement… }}
  • 30.  An exampleAn example if(score >= 90){if(score >= 90){ a_cnt ++;a_cnt ++; }else if(score >= 80){}else if(score >= 80){ b_cnt++;b_cnt++; }else if(score >= 70){}else if(score >= 70){ c_cnt++;c_cnt++; }else if (score>= 60){}else if (score>= 60){ d_cnt++d_cnt++ }else{}else{ f_cnt++f_cnt++ }}
  • 31.  The switch statementThe switch statement switch (switch (expressionexpression) )  {{ casecase item1item1:: statementstatement;; break;break; casecase item2item2:: statementstatement;; break;break; default:default: statementstatement;; break;break; }}
  • 32. Loops  for statementfor statement for (for (expression1expression1;; expression2expression2;; expression3expression3)){{ statement…statement… }} expression1expression1 initializes;initializes; expression2expression2 is the terminate test;is the terminate test; expression3expression3 is the modifieris the modifier;;
  • 33.  An exampleAn example int x;int x; for (x=0; x<3; x++)for (x=0; x<3; x++) {{ printf("x=%dprintf("x=%dn",x);n",x); }} First time:First time: x = 0;x = 0; Second time:Second time: x = 1;x = 1; Third time:Third time: x = 2;x = 2; Fourth time:Fourth time: x = 3; (donx = 3; (don’’t execute the body)t execute the body)
  • 34.  The while statementThe while statement while (while (expressionexpression) {) { statementstatement …… }} while loop exits only when the expression is false.while loop exits only when the expression is false.  An exampleAn example int x = 3;int x = 3; while (x>0) {while (x>0) { printf("x=%d n",x);printf("x=%d n",x); x--;x--; }}
  • 35. for <==> while for (for (expression1expression1;; expression2expression2;; expression3expression3)){{ statement…statement… }} expression1;expression1; while (expression2)while (expression2) {{ statementstatement……;; expression3;expression3; }} equals
  • 36. Arrays & Strings  ArraysArrays int ids[50];int ids[50]; char name[100];char name[100]; int table_of_num[30][40];int table_of_num[30][40];  Accessing an arrayAccessing an array ids[0] = 40;ids[0] = 40; i = ids[1] + j;i = ids[1] + j; table_of_num[3][4] = 100;table_of_num[3][4] = 100; Note: In C Array subscripts start atNote: In C Array subscripts start at 00 and end one less thanand end one less than the array size.the array size. [0 .. n-1][0 .. n-1]
  • 37.  StringsStrings Strings are defined as arrays of characters.Strings are defined as arrays of characters. The only difference from a character array is, a symbol “0”The only difference from a character array is, a symbol “0” is used to indicate the end of a string.is used to indicate the end of a string. For example, suppose we have a character array, charFor example, suppose we have a character array, char name[8], and we store into it a string “Dave”.name[8], and we store into it a string “Dave”. Note: the length of this string 4, but it occupies 5 bytes.Note: the length of this string 4, but it occupies 5 bytes. DD aa vv ee 00
  • 38. Functions Functions are easy to use; they allow complicated programs to be brokenFunctions are easy to use; they allow complicated programs to be broken into small blocks, each of which is easier to write, read, and maintain.into small blocks, each of which is easier to write, read, and maintain. This is calledThis is called modulationmodulation..  HowHow doesdoes a function look likea function look like?? returntypereturntype function_name(function_name(parameters…parameters…)    )     {  {   locallocal variables declaration;variables declaration;    functionfunction code;code; return result;  return result;   }}
  • 39.  Sample functionSample function int addition(int x, int y)int addition(int x, int y) {{ int add;int add; add = x + y;add = x + y; return add;return add; }}  How toHow to call a function?call a function? int result;int result; int i = 5, j = 6;int i = 5, j = 6; result = addition(i, j);result = addition(i, j);
  • 40. Pointers Pointer is the most beautifulPointer is the most beautiful ((ugliestugliest)) part of C, but alsopart of C, but also brings most trouble to C programmers. Over 90% bugs inbrings most trouble to C programmers. Over 90% bugs in the C programs cthe C programs coome from pointers.me from pointers. ““The International Obfuscated C Code ContestThe International Obfuscated C Code Contest ”” ((http://www.ioccc.org/http://www.ioccc.org/))  What is a pointerWhat is a pointer?? A pointer is a variable which contains the address in memoryA pointer is a variable which contains the address in memory of another variable.of another variable. In C we have a specific type for pointers.In C we have a specific type for pointers.
  • 41.  Declaring a pointer variableDeclaring a pointer variable int * pointer;int * pointer; char * name;char * name;  How to obtain theHow to obtain the addressaddress of a variableof a variable?? int x = 0x2233;int x = 0x2233; pointer = &x;pointer = &x; where & is calledwhere & is called address ofaddress of operator.operator.  How to get theHow to get the valuevalue of the variable indicated by theof the variable indicated by the pointerpointer?? int y = *pointer;int y = *pointer;
  • 42. 3333 2222 0000 0000 0x5200 0x5203 0x5200 pointer What happens in the memory? Suppose the address of variable x is 0x5200 in the above example, so the value of the variable pointer is 0x5200. X
  • 43. swap the value of two variables
  • 44. Why is the left one not working? swap main x, y a, b call swap(a, b) in main x, y, a, b are all local variables
  • 45. Why is the right one working?
  • 46.  Pointers and ArraysPointers and Arrays Pointers and arrays are very closely linked in C.Pointers and arrays are very closely linked in C. Array elements arranged inArray elements arranged in consecutiveconsecutive memory locationsmemory locations  Accessing array elements using pointersAccessing array elements using pointers int ids[50];int ids[50]; int * p = &ids[0];int * p = &ids[0]; p[i]p[i] <<=>=> ids[i]ids[i]  Pointers and StringsPointers and Strings A string can be represented by aA string can be represented by a char *char * pointer.pointer.
  • 47. Char name[50];Char name[50]; name[0] = ‘D’;name[0] = ‘D’; name[1] = ‘a’;name[1] = ‘a’; name[2] = ‘v’;name[2] = ‘v’; name[3] = ‘e’;name[3] = ‘e’; name[4] = ‘0’;name[4] = ‘0’; char * p = &name[0];char * p = &name[0]; printf(“The name is %s n”, p);printf(“The name is %s n”, p); NoteNote:: TheThe pp represents the string “Dave”, but not the arrayrepresents the string “Dave”, but not the array name[50].name[50].
  • 48. Command-Line Argument In C you can pass arguments to main() function.In C you can pass arguments to main() function.  mmain() prototypeain() prototype int main(int argc, char * argv[]);int main(int argc, char * argv[]); argc indicates the number of argumentsargc indicates the number of arguments argv is an array of input string pointers.argv is an array of input string pointers.  How to pass your own argumentsHow to pass your own arguments?? ./hello 10./hello 10
  • 49.  What value is argc and argvWhat value is argc and argv?? Let’s add two printf statement to get the value of argc andLet’s add two printf statement to get the value of argc and argv.argv. #include <stdio.h>#include <stdio.h> int main(int main(int argc, char * argv[]);int argc, char * argv[]);)) {{ int i=0;int i=0; printf("Hello Worldn");printf("Hello Worldn"); printf(“The argc is %d n”, argc);printf(“The argc is %d n”, argc); for(i=0; i < argc; i++){for(i=0; i < argc; i++){ printf(“The %dth element in argv is %sn”, i, argv[i]);printf(“The %dth element in argv is %sn”, i, argv[i]); }} return(0);return(0); }}
  • 50.  The outputThe output The argc is 2The argc is 2 The 0th element in argv is ./helloThe 0th element in argv is ./hello The 1th element in argv is 10The 1th element in argv is 10 The trick is the system always passes the name of theThe trick is the system always passes the name of the executable file as theexecutable file as the firstfirst argument to the main() function.argument to the main() function.  How to use your argumentHow to use your argument?? Be careful. Your arguments to main() are always in string format.Be careful. Your arguments to main() are always in string format. Taking the above program for example, the argv[1] is string “10”,Taking the above program for example, the argv[1] is string “10”, not a number. You must convert it into a number before you cannot a number. You must convert it into a number before you can use it.use it.
  • 51. Data Structure A data structure is a collection of one or more variables, possibly ofA data structure is a collection of one or more variables, possibly of different types.different types.  An example of student recordAn example of student record structstruct stud_record{stud_record{ char name[50];char name[50]; int id;int id; int age;int age; int major;int major; ………… };};
  • 52.  A data structure is also a data typeA data structure is also a data type struct stud_record my_record;struct stud_record my_record; struct stud_record * pointer;struct stud_record * pointer; pointer = & my_record;pointer = & my_record;  Accessing a field inside a data structureAccessing a field inside a data structure my_record.id = 10;my_record.id = 10; “.”“.” oror pointer->id = 10;pointer->id = 10; “->”“->”
  • 53. Memory Allocation  Stack memory allocationStack memory allocation Non-static local variable is an example of stack memoryNon-static local variable is an example of stack memory allocation.allocation. Such memory allocations are placed in a system memorySuch memory allocations are placed in a system memory area called thearea called the stackstack..  Static memory allocationStatic memory allocation Static local variable and global variable require staticStatic local variable and global variable require static memory allocation. Static memory allocation happensmemory allocation. Static memory allocation happens before the program starts, andbefore the program starts, and persistspersists through the entirethrough the entire life time of the program.life time of the program.
  • 54.  Dynamic memory allocationDynamic memory allocation It allows the program determine how much memory itIt allows the program determine how much memory it needsneeds atat run timerun time,, and allocate exactly the right amount ofand allocate exactly the right amount of storage.storage. The region of memory where dynamic allocation andThe region of memory where dynamic allocation and deallocation of memory can take place is called thedeallocation of memory can take place is called the heapheap.. NoteNote: the program has the responsibility to free the: the program has the responsibility to free the dynamic memory it allocated.dynamic memory it allocated.
  • 56.  Functions for the dynamic memory allocationFunctions for the dynamic memory allocation void *malloc(size_t number_of_bytes);void *malloc(size_t number_of_bytes); allocates dynamic memoryallocates dynamic memory size_t sizeof(type);size_t sizeof(type); returns the number of bytes of typereturns the number of bytes of type void free(void * p)void free(void * p) releases dynamic memory allocationreleases dynamic memory allocation  An example of dynamic memory allocationAn example of dynamic memory allocation int * ids;int * ids; //id arrays//id arrays int num_of_ids = 40;int num_of_ids = 40; ids = malloc( sizeof(int) * num_of_ids);ids = malloc( sizeof(int) * num_of_ids); ………….. Processing …..... Processing …... free(ids);free(ids);
  • 57.  Allocating a data structure instanceAllocating a data structure instance struct stud_record * pointer;struct stud_record * pointer; pointer = malloc(pointer = malloc(sizeofsizeof(struct stud_record));(struct stud_record)); pointer->id = 10;pointer->id = 10; NeverNever calculate the size of data structure yourself.calculate the size of data structure yourself. TheThe reason is the size of data types isreason is the size of data types is machine-dependentmachine-dependent.. GiveGive it to sizeof() functionit to sizeof() function.. size of intsize of int 32-bytes machines32-bytes machines 3232 64-bytes machines64-bytes machines 6464
  • 58. Programming Tips  Replacing numbers in your code with macrosReplacing numbers in your code with macros - don’t use- don’t use magic numbersmagic numbers directlydirectly #define MAX_NAME_LEN#define MAX_NAME_LEN 50;50; char name[MAX_NAME_LEN];char name[MAX_NAME_LEN];  Avoiding global variablesAvoiding global variables - modulation is more important- modulation is more important  Giving variables and functions a nice nameGiving variables and functions a nice name - a meaning name- a meaning name  Don’t repeat your codeDon’t repeat your code - make a subroutine/function- make a subroutine/function  Don’t let the function body to exceed one screenDon’t let the function body to exceed one screen - hard to debug- hard to debug
  • 59.  Indenting your codeIndenting your code (clearance)(clearance) iif(expression)f(expression) {{ if(expression)if(expression) {{ ………… }} }}  Commenting your codeCommenting your code  Don’t rush into coding. Plan first.Don’t rush into coding. Plan first.  Printing out more debugging informationPrinting out more debugging information  Using debuggerUsing debugger (gdb)(gdb)
  • 60. C vs. C++  C++ is a superset of CC++ is a superset of C  C++ has all the characteristics of CC++ has all the characteristics of C  Using g++ to compile your source codeUsing g++ to compile your source code
  • 61. Books recommended  The C Programming LanguageThe C Programming Language, Brian Kernighan, Brian Kernighan and Dennis Ritchie. Second edition. Prentice-Hall,and Dennis Ritchie. Second edition. Prentice-Hall, 1988.1988. (C Bible)(C Bible)  The C++ Programming LanguageThe C++ Programming Language, Bjarne, Bjarne Stroustrup. Third edition. Addison-Wesley, 1997.Stroustrup. Third edition. Addison-Wesley, 1997. (C++ Bible)(C++ Bible)  Advanced Programming in the UNIXAdvanced Programming in the UNIX EnvironmentEnvironment,, W. Richard StevensW. Richard Stevens,, Addison-Addison- Wesley, 1992Wesley, 1992.. (APUE)(APUE)