SlideShare a Scribd company logo
CSU480CSU480
 “Hello World" Program
 Data Types & Variables
 printf()
 Arithmetic & Logical
Operations
 Conditionals
 Loops
 Arrays & Strings
Outline
 PointersPointers
 FunctionsFunctions
 Command-Line ArgumentCommand-Line Argument
 Data StructureData Structure
 Memory AllocationMemory Allocation
 Programming TipsProgramming Tips
 CC vvs. C++s. C++
 Books recommendedBooks recommended

 The source code
#include <stdio.h>
int main()
{
printf("Hello Worldn");
return(0);
}
Hello World Program
Hello World Program
 How to compile?
$ gcc 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 execute?
./hello
“./ ” indicates the following file “hello” resides
under the 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.
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 Declaration
int length = 100;
char num = ‘9’; //The actual value is 57
float deposit = 240.5;
unsigned short ID = 0x5544;
Try the following statements, and see what happens
unsigned char value = -1;
printf(“The value is %d n”, value);
unsigned char value = 300;
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 variable
Local variables are declared within the body of a function, and
can only be used within that function.
 Static variable
Another class of local variable is the static type. It is specified
by the keyword static in the variable declaration.
The most striking difference from a non-static local variable is, a
static variable is not destroyed on exit from the function.
 Global variable
A global variable declaration looks normal, but is located
outside any of the program's functions. So it is accessible to all
functions.
Variable types

 An example
int global = 10; //global variable
int func (int x)
{
static int stat_var; //static local variable
int temp; //(normal) local variable
int name[50]; //(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

The printf() function can be instructed to print
integers, floats and string properly.
 The general syntax is
printf( “format”, variables);
 An example
int stud_id = 5200;
char * name = “Mike”;
printf(“%s ‘s ID is %d n”, name, stud_id);
printf()

 Format Identifiers
%d decimal integers
%x hex integer
%c character
%f float and double number
%s string
%p pointer
 How to specify display space for a variable?
printf(“The student id is %5d n”, stud_id);
The value of stud_id will occupy 5 characters space in
the print-out.
 Why “n”
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 hexadecimal numberhexadecimal number
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--

 Arithmetic operators
int i = 10;
int j = 15;
int add = i + j; //25
int diff = j – i; //5
int product = i * j; // 150
int quotient = j / i; // 1
int residual = j % i; // 5
i++; //Increase by 1
i--; //Decrease by 1
Example

 Comparing them
int i = 10;
int j = 15;
float k = 15.0;
j / i = ?
j % i = ?
k / i = ?
k % i = ?

 The Answer
j / i = 1;
j % i = 5;
k / i = 1.5;
k % i It is illegal.
Note: For %, the operands can only be integers.

 What is “true” and “false” in C
In 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 stand for “true”.
 Logical Operators
A && B => A and B
A || B => A or B
A == B => Is A equal to B?
A != B => Is A not equal to B?
Logical Operations

A > B => Is A greater than B?
A >= B => Is A greater than or equal to B?
A < B => Is A less than B?
A <= B => Is A less than or equal to B?
 Don’t be confused
&& and || have different meanings from & and |.
& and | are bitwise operators.

 Short circuiting means that we don't evaluate the
second part of an AND or OR unless we really need
to.
Some practices
Please compute the value of the following logical
expressions?
Short circuiting

int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) =>
if( i != j || k < j) =>
if( j<= k || i > k) =>
if( j == k && m) =>
if(i) =>
if(m || j && i ) =>

int i = 10; int j = 15; int k = 15; int m = 0;
if( i < j && j < k) => false
if( i != j || k < j) => true
if( j<= k || i > k) => true
if( j == k && m) => false
if(i) => true
if(m || j && i ) => true
Did you get the correct answers?

 if statement
Three basic formats,
if (expression){
statement …
}
if (expression) {
statement …
}else{
statement …
}
Conditionals

if (expression) {
statement…
}else if (expression) {
statement…
}else{
statement…
}

 An example
if(score >= 90){
a_cnt ++;
}else if(score >= 80){
b_cnt++;
}else if(score >= 70){
c_cnt++;
}else if (score>= 60){
d_cnt++
}else{
f_cnt++
}

 The switch statement
switch (expression) 
{
case item1:
statement;
break;
case item2:
statement;
break;
default:
statement;
break;
}

 for statement
for (expression1; expression2; expression3){
statement…
}
expression1 initializes;
expression2 is the terminate test;
expression3 is the modifier;
Loops

 An example
int x;
for (x=0; x<3; x++)
{
printf("x=%dn",x);
}
First time: x = 0;
Second time: x = 1;
Third time: x = 2;
Fourth time: x = 3; (don’t execute the body)

 The while statement
while (expression) {
statement …
}
while loop exits only when the expression is false.
 An example
int x = 3;
while (x>0) {
printf("x=%d n",x);
x--;
}
for (expression1;
expression2;
expression3){
statement…
}
for <==> while
expression1;expression1;
while (expression2)while (expression2)
{{
statementstatement……;;
expression3;expression3;
}}
equals

 Arrays
int ids[50];
char name[100];
int table_of_num[30][40];
 Accessing an array
ids[0] = 40;
i = ids[1] + j;
table_of_num[3][4] = 100;
Note: In C Array subscripts start at 0 and end one
less than the array size. [0 .. n-1]
Arrays & Strings

 Strings
Strings are defined as arrays of characters.
The only difference from a character array is, a
symbol “0” is used to indicate the end of a string.
For example, suppose we have a character array, char
name[8], and we store into it a string “Dave”.
Note: the length of this string 4, but it occupies 5
bytes.
DD aa vv ee 00

Functions are easy to use; they allow complicated programs to be
broken into small blocks, each of which is easier to write, read, and
maintain. This is called modulation.
 How does a function look like?
returntype function_name(parameters…)    
{  
local variables declaration;  
function code;
return result;  
}
Functions

 Sample function
int addition(int x, int y)
{
int add;
add = x + y;
return add;
}
 How to call a function?
int result;
int i = 5, j = 6;
result = addition(i, j);

Pointer is the most beautiful (ugliest) part of C, but also
brings most trouble to C programmers. Over 90%
bugs in the C programs come from pointers.
“The International Obfuscated C Code Contest ”
(http://www.ioccc.org/)
 What is a pointer?
A pointer is a variable which contains the address in
memory of another variable.
In C we have a specific type for pointers.
Pointers

 Declaring a pointer variable
int * pointer;
char * name;
 How to obtain the address of a variable?
int x = 0x2233;
pointer = &x;
where & is called address of operator.
 How to get the value of the variable indicated by the
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 Arrays
Pointers and arrays are very closely linked in C.
Array elements arranged in consecutive memory
locations
 Accessing array elements using pointers
int ids[50];
int * p = &ids[0];
p[i] <=> ids[i]
 Pointers and Strings
A string can be represented by a char * pointer.

Char name[50];
name[0] = ‘D’;
name[1] = ‘a’;
name[2] = ‘v’;
name[3] = ‘e’;
name[4] = ‘0’;
char * p = &name[0];
printf(“The name is %s n”, p);
Note: The p represents the string “Dave”, but not the
array
name[50].

In C you can pass arguments to main() function.
 main() prototype
int main(int argc, char * argv[]);
argc indicates the number of arguments
argv is an array of input string pointers.
 How to pass your own arguments?
./hello 10
Command-Line Argument

 What value is argc and argv?
Let’s add two printf statement to get the value of argc
and argv.
#include <stdio.h>
int main(int argc, char * argv[]);)
{
int i=0;
printf("Hello Worldn");
printf(“The argc is %d n”, argc);
for(i=0; i < argc; i++){
printf(“The %dth element in argv is %sn”, i, argv[i]);
}
return(0);
}

 The output
The argc is 2
The 0th element in argv is ./hello
The 1th element in argv is 10
The trick is the system always passes the name of the
executable file as the first argument to the main() function.
 How to use your argument?
Be careful. Your arguments to main() are always in string format.
Taking the above program for example, the argv[1] is string “10”,
not a number. You must convert it into a number before you can
use it.

A data structure is a collection of one or more variables, possibly
of different types.
 An example of student record
struct stud_record{
char name[50];
int id;
int age;
int major;
……
};
Data Structure

 A data structure is also a data type
struct stud_record my_record;
struct stud_record * pointer;
pointer = & my_record;
 Accessing a field inside a data structure
my_record.id = 10; “.”
or
pointer->id = 10; “->”

 Stack memory allocation
Non-static local variable is an example of stack
memory allocation.
Such memory allocations are placed in a system
memory area called the stack.
 Static memory allocation
Static local variable and global variable require static
memory allocation. Static memory allocation
happens before the program starts, and persists
through the entire life time of the program.
Memory Allocation

 Dynamic memory allocation
It allows the program determine how much memory
it needs at run time, and allocate exactly the right
amount of storage.
The region of memory where dynamic allocation and
deallocation of memory can take place is called the
heap.
Note: the program has the responsibility to free the
dynamic memory it allocated.

Memory arrangement

 Functions for the dynamic memory allocation
void *malloc(size_t number_of_bytes);
allocates dynamic memory
size_t sizeof(type);
returns the number of bytes of type
void free(void * p)
releases dynamic memory allocation
 An example of dynamic memory allocation
int * ids; //id arrays
int num_of_ids = 40;
ids = malloc( sizeof(int) * num_of_ids);
…….. Processing …...
free(ids);
 Allocating a data structure instance
struct stud_record * pointer;
pointer = malloc(sizeof(struct stud_record));
pointer->id = 10;
Never calculate the size of data structure yourself.
The reason is the size of data types is machine-
dependent. Give it to sizeof() function.
size of intsize of int
32-bytes machines32-bytes machines 3232
64-bytes machines64-bytes machines 6464
 Replacing numbers in your code with macros
- don’t use magic numbers directly
#define MAX_NAME_LEN 50;
char name[MAX_NAME_LEN];
 Avoiding global variables
- modulation is more important
 Giving variables and functions a nice name
- a meaning name
 Don’t repeat your code
- make a subroutine/function
 Don’t let the function body to exceed one screen
- hard to debug
Programming Tips

 Indenting your code (clearance)
if(expression)
{
if(expression)
{
……
}
}
 Commenting your code
 Don’t rush into coding. Plan first.
 Printing out more debugging information
 Using debugger (gdb)

 C++ is a superset of C
 C++ has all the characteristics of C
 Using g++ to compile your source code
C vs. C++

Thanks

More Related Content

What's hot

Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
nikshaikh786
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Unit ii ppt
Unit ii pptUnit ii ppt
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
nikshaikh786
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
nikshaikh786
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standardsHector Garzo
 
Computation Chapter 4
Computation Chapter 4Computation Chapter 4
Computation Chapter 4
Inocentshuja Ahmad
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
DhivyaSubramaniyam
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
DhivyaSubramaniyam
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproceHector Garzo
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
Raajendra M
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
Rasan Samarasinghe
 
Kuliah komputer pemrograman
Kuliah  komputer pemrogramanKuliah  komputer pemrograman
Kuliah komputer pemrogramanhardryu
 

What's hot (20)

Module 3-Functions
Module 3-FunctionsModule 3-Functions
Module 3-Functions
 
DITEC - Programming with Java
DITEC - Programming with JavaDITEC - Programming with Java
DITEC - Programming with Java
 
C tutorial
C tutorialC tutorial
C tutorial
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
C
CC
C
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
Module 4- Arrays and Strings
Module 4- Arrays and StringsModule 4- Arrays and Strings
Module 4- Arrays and Strings
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Module 5-Structure and Union
Module 5-Structure and UnionModule 5-Structure and Union
Module 5-Structure and Union
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standards
 
Computation Chapter 4
Computation Chapter 4Computation Chapter 4
Computation Chapter 4
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
Python unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabusPython unit 2 as per Anna university syllabus
Python unit 2 as per Anna university syllabus
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproce
 
C SLIDES PREPARED BY M V B REDDY
C SLIDES PREPARED BY  M V B REDDYC SLIDES PREPARED BY  M V B REDDY
C SLIDES PREPARED BY M V B REDDY
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
DIWE - Fundamentals of PHP
DIWE - Fundamentals of PHPDIWE - Fundamentals of PHP
DIWE - Fundamentals of PHP
 
Kuliah komputer pemrograman
Kuliah  komputer pemrogramanKuliah  komputer pemrograman
Kuliah komputer pemrograman
 

Viewers also liked

Break and continue statement in C
Break and continue statement in CBreak and continue statement in C
Break and continue statement in C
Innovative
 
Jumping statements
Jumping statementsJumping statements
Jumping statementsSuneel Dogra
 
Operators in java
Operators in javaOperators in java
Operators in java
yugandhar vadlamudi
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Nilesh Dalvi
 
operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c language
shhanks
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
KV(AFS) Utarlai, Barmer (Rajasthan)
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Conceptsthinkphp
 

Viewers also liked (9)

Break and continue
Break and continueBreak and continue
Break and continue
 
Break and continue statement in C
Break and continue statement in CBreak and continue statement in C
Break and continue statement in C
 
Jumping statements
Jumping statementsJumping statements
Jumping statements
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
operators and control statements in c language
operators and control statements in c languageoperators and control statements in c language
operators and control statements in c language
 
Constructor & Destructor
Constructor & DestructorConstructor & Destructor
Constructor & Destructor
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 

Similar to C tutorial

c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
gitesh_nagar
 
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
 
What is c
What is cWhat is c
What is c
Nitesh Saitwal
 
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
AnkitaVerma776806
 
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
Ismar Silveira
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiM2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
rakshithatan
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
Mahira Banu
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
Soran University
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
JAYA
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
MOHAMAD NOH AHMAD
 
C intro
C introC intro
C intro
Kamran
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans incnayakq
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
Pradipta Mishra
 

Similar to C tutorial (20)

c_tutorial_2.ppt
c_tutorial_2.pptc_tutorial_2.ppt
c_tutorial_2.ppt
 
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
 
What is c
What is cWhat is c
What is c
 
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
 
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
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Elements of programming
Elements of programmingElements of programming
Elements of programming
 
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiM2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
C intro
C introC intro
C intro
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Qust & ans inc
Qust & ans incQust & ans inc
Qust & ans inc
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
 

More from Patruni Chidananda Sastry

Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
Patruni Chidananda Sastry
 
Power consumption by means of wi fi
Power consumption by means of wi fiPower consumption by means of wi fi
Power consumption by means of wi fi
Patruni Chidananda Sastry
 
Digital thermometer ppt
Digital thermometer pptDigital thermometer ppt
Digital thermometer ppt
Patruni Chidananda Sastry
 
Microcontroller 8051
Microcontroller 8051Microcontroller 8051
Microcontroller 8051
Patruni Chidananda Sastry
 
Gps
Gps Gps
Basics of electronics
Basics of electronicsBasics of electronics
Basics of electronics
Patruni Chidananda Sastry
 
Mail server
Mail serverMail server
Dns
DnsDns
Raid
Raid Raid
Raid intro
Raid introRaid intro
Moisture controller report total
Moisture controller report totalMoisture controller report total
Moisture controller report total
Patruni Chidananda Sastry
 
Linux basics andng hosti
Linux basics andng hostiLinux basics andng hosti
Linux basics andng hosti
Patruni Chidananda Sastry
 

More from Patruni Chidananda Sastry (14)

Spread spectrum
Spread spectrumSpread spectrum
Spread spectrum
 
Power consumption by means of wi fi
Power consumption by means of wi fiPower consumption by means of wi fi
Power consumption by means of wi fi
 
Digital thermometer ppt
Digital thermometer pptDigital thermometer ppt
Digital thermometer ppt
 
Microcontroller 8051
Microcontroller 8051Microcontroller 8051
Microcontroller 8051
 
Gps
Gps Gps
Gps
 
Basics of electronics
Basics of electronicsBasics of electronics
Basics of electronics
 
Mail server
Mail serverMail server
Mail server
 
Linux
Linux Linux
Linux
 
Dns
DnsDns
Dns
 
Raid
Raid Raid
Raid
 
Raid intro
Raid introRaid intro
Raid intro
 
SEO AND DIGITAL MARKETING
SEO AND DIGITAL MARKETINGSEO AND DIGITAL MARKETING
SEO AND DIGITAL MARKETING
 
Moisture controller report total
Moisture controller report totalMoisture controller report total
Moisture controller report total
 
Linux basics andng hosti
Linux basics andng hostiLinux basics andng hosti
Linux basics andng hosti
 

Recently uploaded

可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
cuobya
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
Understanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdfUnderstanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdf
SEO Article Boost
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
Laura Szabó
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
hackersuli
 
Search Result Showing My Post is Now Buried
Search Result Showing My Post is Now BuriedSearch Result Showing My Post is Now Buried
Search Result Showing My Post is Now Buried
Trish Parr
 
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
ukwwuq
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
ysasp1
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
Trending Blogers
 
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
cuobya
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!
Toptal Tech
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
nhiyenphan2005
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
harveenkaur52
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
Danica Gill
 

Recently uploaded (20)

可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
可查真实(Monash毕业证)西澳大学毕业证成绩单退学买
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
Understanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdfUnderstanding User Behavior with Google Analytics.pdf
Understanding User Behavior with Google Analytics.pdf
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
Gen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needsGen Z and the marketplaces - let's translate their needs
Gen Z and the marketplaces - let's translate their needs
 
[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024[HUN][hackersuli] Red Teaming alapok 2024
[HUN][hackersuli] Red Teaming alapok 2024
 
Search Result Showing My Post is Now Buried
Search Result Showing My Post is Now BuriedSearch Result Showing My Post is Now Buried
Search Result Showing My Post is Now Buried
 
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
制作原版1:1(Monash毕业证)莫纳什大学毕业证成绩单办理假
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
成绩单ps(UST毕业证)圣托马斯大学毕业证成绩单快速办理
 
Explore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories SecretlyExplore-Insanony: Watch Instagram Stories Secretly
Explore-Insanony: Watch Instagram Stories Secretly
 
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
制作毕业证书(ANU毕业证)莫纳什大学毕业证成绩单官方原版办理
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!Ready to Unlock the Power of Blockchain!
Ready to Unlock the Power of Blockchain!
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
 
7 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 20247 Best Cloud Hosting Services to Try Out in 2024
7 Best Cloud Hosting Services to Try Out in 2024
 

C tutorial

  • 2.  “Hello World" Program  Data Types & Variables  printf()  Arithmetic & Logical Operations  Conditionals  Loops  Arrays & Strings Outline  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.   The source code #include <stdio.h> int main() { printf("Hello Worldn"); return(0); } Hello World Program
  • 4. Hello World Program  How to compile? $ gcc 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 execute? ./hello “./ ” indicates the following file “hello” resides under the 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. 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 Declaration int length = 100; char num = ‘9’; //The actual value is 57 float deposit = 240.5; unsigned short ID = 0x5544; Try the following statements, and see what happens unsigned char value = -1; printf(“The value is %d n”, value); unsigned char value = 300; 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 variable Local variables are declared within the body of a function, and can only be used within that function.  Static variable Another class of local variable is the static type. It is specified by the keyword static in the variable declaration. The most striking difference from a non-static local variable is, a static variable is not destroyed on exit from the function.  Global variable A global variable declaration looks normal, but is located outside any of the program's functions. So it is accessible to all functions. Variable types
  • 11.   An example int global = 10; //global variable int func (int x) { static int stat_var; //static local variable int temp; //(normal) local variable int name[50]; //(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.  The printf() function can be instructed to print integers, floats and string properly.  The general syntax is printf( “format”, variables);  An example int stud_id = 5200; char * name = “Mike”; printf(“%s ‘s ID is %d n”, name, stud_id); printf()
  • 15.   Format Identifiers %d decimal integers %x hex integer %c character %f float and double number %s string %p pointer  How to specify display space for a variable? printf(“The student id is %5d n”, stud_id); The value of stud_id will occupy 5 characters space in the print-out.
  • 16.  Why “n” 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 hexadecimal numberhexadecimal number 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.   Arithmetic operators int i = 10; int j = 15; int add = i + j; //25 int diff = j – i; //5 int product = i * j; // 150 int quotient = j / i; // 1 int residual = j % i; // 5 i++; //Increase by 1 i--; //Decrease by 1 Example
  • 21.   Comparing them int i = 10; int j = 15; float k = 15.0; j / i = ? j % i = ? k / i = ? k % i = ?
  • 22.   The Answer j / i = 1; j % i = 5; k / i = 1.5; k % i It is illegal. Note: For %, the operands can only be integers.
  • 23.   What is “true” and “false” in C In 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 stand for “true”.  Logical Operators A && B => A and B A || B => A or B A == B => Is A equal to B? A != B => Is A not equal to B? Logical Operations
  • 24.  A > B => Is A greater than B? A >= B => Is A greater than or equal to B? A < B => Is A less than B? A <= B => Is A less than or equal to B?  Don’t be confused && and || have different meanings from & and |. & and | are bitwise operators.
  • 25.   Short circuiting means that we don't evaluate the second part of an AND or OR unless we really need to. Some practices Please compute the value of the following logical expressions? Short circuiting
  • 26.  int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => if( i != j || k < j) => if( j<= k || i > k) => if( j == k && m) => if(i) => if(m || j && i ) =>
  • 27.  int i = 10; int j = 15; int k = 15; int m = 0; if( i < j && j < k) => false if( i != j || k < j) => true if( j<= k || i > k) => true if( j == k && m) => false if(i) => true if(m || j && i ) => true Did you get the correct answers?
  • 28.   if statement Three basic formats, if (expression){ statement … } if (expression) { statement … }else{ statement … } Conditionals
  • 29.  if (expression) { statement… }else if (expression) { statement… }else{ statement… }
  • 30.   An example if(score >= 90){ a_cnt ++; }else if(score >= 80){ b_cnt++; }else if(score >= 70){ c_cnt++; }else if (score>= 60){ d_cnt++ }else{ f_cnt++ }
  • 31.   The switch statement switch (expression)  { case item1: statement; break; case item2: statement; break; default: statement; break; }
  • 32.   for statement for (expression1; expression2; expression3){ statement… } expression1 initializes; expression2 is the terminate test; expression3 is the modifier; Loops
  • 33.   An example int x; for (x=0; x<3; x++) { printf("x=%dn",x); } First time: x = 0; Second time: x = 1; Third time: x = 2; Fourth time: x = 3; (don’t execute the body)
  • 34.   The while statement while (expression) { statement … } while loop exits only when the expression is false.  An example int x = 3; while (x>0) { printf("x=%d n",x); x--; }
  • 35. for (expression1; expression2; expression3){ statement… } for <==> while expression1;expression1; while (expression2)while (expression2) {{ statementstatement……;; expression3;expression3; }} equals
  • 36.   Arrays int ids[50]; char name[100]; int table_of_num[30][40];  Accessing an array ids[0] = 40; i = ids[1] + j; table_of_num[3][4] = 100; Note: In C Array subscripts start at 0 and end one less than the array size. [0 .. n-1] Arrays & Strings
  • 37.   Strings Strings are defined as arrays of characters. The only difference from a character array is, a symbol “0” is used to indicate the end of a string. For example, suppose we have a character array, char name[8], and we store into it a string “Dave”. Note: the length of this string 4, but it occupies 5 bytes. DD aa vv ee 00
  • 38.  Functions are easy to use; they allow complicated programs to be broken into small blocks, each of which is easier to write, read, and maintain. This is called modulation.  How does a function look like? returntype function_name(parameters…)     {   local variables declaration;   function code; return result;   } Functions
  • 39.   Sample function int addition(int x, int y) { int add; add = x + y; return add; }  How to call a function? int result; int i = 5, j = 6; result = addition(i, j);
  • 40.  Pointer is the most beautiful (ugliest) part of C, but also brings most trouble to C programmers. Over 90% bugs in the C programs come from pointers. “The International Obfuscated C Code Contest ” (http://www.ioccc.org/)  What is a pointer? A pointer is a variable which contains the address in memory of another variable. In C we have a specific type for pointers. Pointers
  • 41.   Declaring a pointer variable int * pointer; char * name;  How to obtain the address of a variable? int x = 0x2233; pointer = &x; where & is called address of operator.  How to get the value of the variable indicated by the 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 Arrays Pointers and arrays are very closely linked in C. Array elements arranged in consecutive memory locations  Accessing array elements using pointers int ids[50]; int * p = &ids[0]; p[i] <=> ids[i]  Pointers and Strings A string can be represented by a char * pointer.
  • 47.  Char name[50]; name[0] = ‘D’; name[1] = ‘a’; name[2] = ‘v’; name[3] = ‘e’; name[4] = ‘0’; char * p = &name[0]; printf(“The name is %s n”, p); Note: The p represents the string “Dave”, but not the array name[50].
  • 48.  In C you can pass arguments to main() function.  main() prototype int main(int argc, char * argv[]); argc indicates the number of arguments argv is an array of input string pointers.  How to pass your own arguments? ./hello 10 Command-Line Argument
  • 49.   What value is argc and argv? Let’s add two printf statement to get the value of argc and argv. #include <stdio.h> int main(int argc, char * argv[]);) { int i=0; printf("Hello Worldn"); printf(“The argc is %d n”, argc); for(i=0; i < argc; i++){ printf(“The %dth element in argv is %sn”, i, argv[i]); } return(0); }
  • 50.   The output The argc is 2 The 0th element in argv is ./hello The 1th element in argv is 10 The trick is the system always passes the name of the executable file as the first argument to the main() function.  How to use your argument? Be careful. Your arguments to main() are always in string format. Taking the above program for example, the argv[1] is string “10”, not a number. You must convert it into a number before you can use it.
  • 51.  A data structure is a collection of one or more variables, possibly of different types.  An example of student record struct stud_record{ char name[50]; int id; int age; int major; …… }; Data Structure
  • 52.   A data structure is also a data type struct stud_record my_record; struct stud_record * pointer; pointer = & my_record;  Accessing a field inside a data structure my_record.id = 10; “.” or pointer->id = 10; “->”
  • 53.   Stack memory allocation Non-static local variable is an example of stack memory allocation. Such memory allocations are placed in a system memory area called the stack.  Static memory allocation Static local variable and global variable require static memory allocation. Static memory allocation happens before the program starts, and persists through the entire life time of the program. Memory Allocation
  • 54.   Dynamic memory allocation It allows the program determine how much memory it needs at run time, and allocate exactly the right amount of storage. The region of memory where dynamic allocation and deallocation of memory can take place is called the heap. Note: the program has the responsibility to free the dynamic memory it allocated.
  • 56.   Functions for the dynamic memory allocation void *malloc(size_t number_of_bytes); allocates dynamic memory size_t sizeof(type); returns the number of bytes of type void free(void * p) releases dynamic memory allocation  An example of dynamic memory allocation int * ids; //id arrays int num_of_ids = 40; ids = malloc( sizeof(int) * num_of_ids); …….. Processing …... free(ids);
  • 57.  Allocating a data structure instance struct stud_record * pointer; pointer = malloc(sizeof(struct stud_record)); pointer->id = 10; Never calculate the size of data structure yourself. The reason is the size of data types is machine- dependent. Give it to sizeof() function. size of intsize of int 32-bytes machines32-bytes machines 3232 64-bytes machines64-bytes machines 6464
  • 58.  Replacing numbers in your code with macros - don’t use magic numbers directly #define MAX_NAME_LEN 50; char name[MAX_NAME_LEN];  Avoiding global variables - modulation is more important  Giving variables and functions a nice name - a meaning name  Don’t repeat your code - make a subroutine/function  Don’t let the function body to exceed one screen - hard to debug Programming Tips
  • 59.   Indenting your code (clearance) if(expression) { if(expression) { …… } }  Commenting your code  Don’t rush into coding. Plan first.  Printing out more debugging information  Using debugger (gdb)
  • 60.   C++ is a superset of C  C++ has all the characteristics of C  Using g++ to compile your source code C vs. C++