SlideShare uma empresa Scribd logo
1 de 50
C101 – Intro to Programming
with C
Peter Gaal
Introduction
• Your Name
• Your day job
• Your last holiday destination?
C language overview
• procedural, general purpose, cross platform
• available almost on every platform
• Widely used
• Statically typed with weak typing
• Manual memory management, low memory
footprint
• C is not object oriented but C++ and
Objective-C has OOP support
C++ language overview
• OOP support (classes)
• available on all major platforms (except
embedded devices with small memory)
• Widely used
• Statically typed, strong typing
• Manual memory management (mostly), low
memory footprint
History of C
• general-purpose, procedural programming
language, weak typing
• First appeared around year 1972, initially
developed in AT&T Bell Labs and was used to
(re-)implement the Unix operating system
• In 1989 became ANSI standard (C89)
• Updated in 1999 - C99 and in 2011 - C11 (not
all compilers support it)
History of C++
• Created by Bjarne Stroustrup in 1979, initially
called "C with Classes“
• features: class, derived class, strong typing,
inlining, and default argument
• 1983: it was renamed from C with Classes to C++
• new features: virtual functions, function name
and operator overloading, references, constants,
type-safe free-store memory allocation
(new/delete)
History of C++
• 1989, C++ 2.0: multiple inheritance, abstract
classes, static member functions, const
member functions, and protected members
• 1990: templates, exceptions, namespaces,
new casts, boolean type
• 1998: became an ISO standard, known as
C++98
• recently new major updates: C++11, C++14,
C++17
Usage of C
• Embedded devices
• System programming
• Operating systems
• Drivers
• Libraries
• Low power, high performance apps
Usage of C++
• All high performance/low power apps, similar
to C but where we need classes
• Games
• Low latency
• Computer vision
• 3D graphics, video, audio
• Compression/decompression
Software written in C/C++
• Linux kernel (in C), Windows 95-10, Office,
SQL, Exchange, VC++, VB, C# compiler
• JRE – Java runtime environment
• MySQL, Perl, PHP, Python, MongoDB
• Adobe Photoshop, VLC player
• Firefox, Internet explorer
Advantages
• Speed, high performance (low power)
• Compact (low) memory usage
• Low level, “close to the metal”
• Deterministic application response (no
garbage collection stops the app)
• Creates native code, no need to install Java or
.NET runtime, good protection against reverse
compilation
Disadvantages
• Hard language, manual memory management,
complicated bugs hard to debug like
segmentation fault (access violation), memory
leaks, dangling pointers, corruption of data,
buffer overruns, therefore lower productivity,
sometimes hard to read
• C/C++ compiler is slow due to complicated
syntax (header files, macros)
Why is C (C++) hard?
• Because you can find or write code like this:
• or this:
• or this:
Hint: if you don’t know what the last code does try to run with these parameters:
obama republican democrat or: Jobs Mac PC
nixon republican democrat Gates Mac PC
bush republican democrat
kennedy republican democrat
lincoln republican democrat Source: http://www.ioccc.org/2013/cable1/cable1.c
The International Obfuscated C Code Contest, year 2013
Now seriously, this is a real C code in the libraries (ffmpeg.c, ~line 327):
this is also a real C code (libx264.c, ~line 770):
• but you can write also a nice, readable code in C/C++
• and you can write also bad, unreadable code in any other language
How C/C++ works
Source code files
(mostly platform
independent)
.c, .h, .cpp, .hpp
Compiler
obj files
(platform
dependent)
Library files (.a)
(platform dependent)
Linker
Native executable code (binary file)
Platform (CPU) dependent
(different output on every platform)
main() function – program entry
How C/C++ works on different platforms
Source code files
(mostly platform
independent)
.c, .h, .cpp, .hpp
Compiler + Linker
Win32 x86
Win32 x86 Binary (.EXE)
Dynamically linked libraries
(DLL) – x86Win32 x86 libraries
(.a, .lib)
Compiler + Linker
Win 64bit
Windows 64bit Binary (.EXE)
Dynamically linked libraries
(DLL) – 64bitWin 64bit libraries
(.a, .lib)
Compiler + Linker
Linux x86
Linux x86 Binary (executable)
Dynamically linked libraries
x86 (.so)Linux x86 libraries (.a)
Compiler + Linker
Linux ARM
Linux ARM Binary (executable)
Dynamically linked libraries
ARM (.so)Linux ARM libraries (.a)
C/C++ File structure
Header files
*.h (usually C)
*.hpp (C++)
Source files
*.c (usually C)
*.cpp (C++)
library files
*.lib, *.a
C/C++ 101 – Intro to Programming
with C/C++
Writing your first program in C
Hello, World!
Source: http://profitswithjody.com/wp-content/uploads/2012/11/hello_world_Wallpaper_5ze28.jpg
Writing your first program in C
• Create a new “Win32 Console application, Visual C++” in
Visual C++ Express named MyFirstCProgram, select empty
project on the application settings screen
• Create a new CPP file in “Source Files” in Solution Explorer
HelloWorld.c as illustrated below:
/* Prints “Hello, World” */
#include <stdio.h>
int main()
{
printf("Hello, worldn");
}
Compiling Your First C Program
• In Visual C++: Press “F7” or “Debug->Build Solution”
from main menu
• It’s recommended to save your source files but it’s not
required in Visual C++, other IDEs might require it
Running Your First C Program
• Press Ctrl-F5 to Run your program in Visual
C++
• Alternatively you can use F5 or “Debug->Start
debugging” from main menu
Congratulations!
/* Prints “Hello, World” */
#include <stdio.h>
int main()
{
printf("Hello, worldn");
}
C program structure
Comments Included header files (other libraries)
Function
Arguments (we will
have them later)
HelloWorld.c
Language Features
Basic Built-In Types
int
char
float
double
bool
Type Modifiers
short (short int)
long (long int)
signed (by default)
unsigned (unsigned int)
Flow Control
if else
for while
Punctuation
{ {
( )
, ;
Assignment
=
Pointers
*
& (reference)
#include <stdio.h>
printf()
scanf()
Operators
+ - * /
% +
+
-- >
< <= >= ==
!= >> <<
Derived Types
struct
enum
array
union
Memory
Management
malloc()
free()
realloc()
sizeof()
Qualifiers
const
volatire
Pre-processor
Macros
#include
#define
#ifdef
#endif
Calling
Convention
cdecl
stdcall
fastcall
Memory
Types
code
stack
heap
Built-in Data Types
type set of values literal values operators
char Characters
Numbers (-128..127)
‘A’, ‘@’, ‘0’
65, 32, 0
Compare
int integers 17
12345
add, subtract,
multiply, divide
double Floating-point numbers 3.1415
6.022e23
add, subtract,
multiply, divide
bool Truth values true
false
and, or, not
Basic Definitions
• Variable - a name that refers to a value.
• Assignment statement - associates a value
with a variable.
Strings
• In C there is no string type! (as it is in Java)
• But you can use strings as array of chars
• In C strings are NULL terminated (array of chars)
• String is a pointer to first letter (char in the array)
Examples of strings (all strings are static)
defined length char str[20]=“Hello World”;
defined length without initial value char str[20];
automatic length (by compiler) char str[]=“Hello World”;
Automatic, pointer syntax char *str=“Hello World”;
same definition
What is a pointer?
A pointer is a variable which
contains the address in
memory of another variable.
Here is your Hello world
string in the memory
Memory address, where your
string is located
Here is the content of the pointer in
the memory
(bytes are in reverse order because of the LITTLE
endian architecture)
Memory address, where your
pointer is located
points to a single byte in memory
What is a NULL terminated string?
char str[] = “Hello”;
‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’
(null)
str[0] str[1] str[2] str[3] str[4] str[5]
• string is finished with a special char (null, ‘0’)
• warning: ‘0’ is not ‘0’
• “Hello” string with length 5 characters needs at
least 6 characters (bytes) to store the string
Strings
char str[6]=”Hello”;
char str[6];
str[0]=‘H’;
Str[1]=‘e’;
Str[2]=‘l’;
Str[3]=‘l’;
Str[4]=‘o’;
Str[5]=‘0’;
This is the same functionality
Strings
• You can’t concatenate string in a C with an
operator (+ in Java or C#)
char *result;
char *string1 = “Hello “;
char *string2 = “World”;
result = string1 + string2;
Strings
• You can concatenate strings using:
– strcat (and similar functions)
– printf (print formatted data to console)
– sprintf (write formatted data to string)
• You need to allocate enough memory for the
destination string
• strcpy – makes a copy of string
Concatenating strings
/* make sure there is enough memory
for the result */
char result[100];
strcpy(result, “Hello “);
strcat(result, “World”);
Concatenating strings with other types
• Use string formatting functions
Expression (def.: char result[100]) Value
sprintf(result, “%s%s”, “Hi, “, “Bob”); “Hi, Bob”
sprintf(result, “Hi, %s”, “Bob”); “Hi, Bob”
sprintf(result, “%d %d %d”, 1, 2, 1); “1 2 1”
sprintf(result, “%d + %d”, 1234, 99); “1234 + 99”
sprintf(result, “%d%d”, 123, 99); “12399”
• If you need just to print on the console you
can use printf instead of sprintf and you don’t
need to allocate the string
Command line arguments
#include <stdio.h>
int main(int argc, char *argv[]) {
}
argument count
array of string arguments
argv[0] is the program name with full path
argv[1] is the first argument
argv[2] is the second argument, etc.
Hands-on Exercise
Command Line Arguments
Command Line Arguments
• Create a program that takes a name as command-line argument and
prints “Hi <name>, How are you?”
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hi, ");
printf(argv[1]);
printf(". How are you?n");
}
Command Line Arguments
• You need to pass an argument into your command line
application, otherwise it will crash or will do nothing
• Press Alt-F7 (or menu Project->Properties), expand
Configuration Properties, select Debugging and in the
second line you will see “Command arguments”
• Type here your name, then press OK and run the
program again
• In the next exercise if you will need more than one
argument then just put spaces between each argument
Command Line Arguments
• You shouldn’t pass an unverified string from your command line directly
into printf function, so we will modify it:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hi, ");
printf("%s", argv[1]);
printf(". How are you?n");
}
Command Line Arguments
• You can do the previous program with just one printf function now:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hi, %s. How are you?n",
argv[1]);
}
Integer Data Type
Data Type Attributes
Values Integers between -2E31 to +2E31-1
Typical literals 1234, -99 , 99, 0, 1000000
Operation Add subtract multiply divide remainder
Operator + - * / %
• Useful for expressing algorithms.
Integer Data Type
Expression Value Comment
5 + 3 8
5 – 3 2
5 * 3 15
5 / 3 1 no fractional
part
5 % 3 2 remainder
1 / 0 run-time error
3 * 5 - 2 13 * has
precedence
3 + 5 / 2 5 / has
precedence
3 – 5 - 2 -4 left associative
(3-5) - 2 -4 better style
3 – (5-2) 0 unambiguous
Double Data Type
• Useful in scientific applications and floating-
point arithmetic
• float is a type with a “half precision”
• sizeof(float)=4, sizeof(double)=8 (in Bytes)
Data Type Attributes
Values Real numbers specified by the IEEE 754 standard
Typical literals 3.14159 6.022e23 -3.0 2.0 1.41421356237209
Operation Add subtract multiply divide
Operator + - * /
Double Data Type
Expression Value
3.141 + 0.03 3.171
3.141 – 0.03 3.111
6.02e23 / 2 3.01e23
5.0 / 3.0 1.6666666666667
10.0 % 3.141 0.577
1.0 / 0.0 Infinity (INF)
sqrt(2.0)
(#include <math.h>)
1.4142135623730951
not defined in C!
C Math Library (#include <math.h>)
Methods
sin() cos()
log() exp()
sqrt() pow()
fmin() fmax()
abs()
http://java.sun.com/javase/6/docs/api/java/lang/Math.html
• PI constant: you can define by yourself:
#define PI 3.14159265358979323846
Hands-on Exercise
Integer Operations
Exercise: Integer Operations
• Create new Win32 console application empty project in Visual
C++ called IntOps
• Create a source file named IntOps.c that performs integer
operations on a pair of integers from the command line and
prints the results.
> IntOps 1234 99
1234 + 99 = 1333
1234 * 99 = 122166
1234 / 99 = 12
1234 % 99 = 46
Solution: Integer Operations
#include <stdio.h>
int main(int argc, char *argv[])
{
int a,b;
int sum, prod, quot, rem;
sscanf(argv[1],"%d", &a);
sscanf(argv[2],"%d", &b);
sum = a + b;
prod = a * b;
quot = a / b;
rem = a % b;
printf("%d + %d = %dn", a, b, sum);
printf("%d * %d = %dn", a, b, prod);
printf("%d / %d = %dn", a, b, quot);
printf("%d %% %d = %dn", a, b, rem);
}
> IntOps 1234 99
1234 + 99 = 1333
1234 * 99 = 122166
1234 / 99 = 12
1234 % 99 = 46

Mais conteúdo relacionado

Mais procurados

C programming session 01
C programming session 01C programming session 01
C programming session 01
Dushmanta Nath
 
System Programming Unit IV
System Programming Unit IVSystem Programming Unit IV
System Programming Unit IV
Manoj Patil
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
Anil Dutt
 

Mais procurados (19)

C programming session 01
C programming session 01C programming session 01
C programming session 01
 
System Programming Unit IV
System Programming Unit IVSystem Programming Unit IV
System Programming Unit IV
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Structure of c_program_to_input_output
Structure of c_program_to_input_outputStructure of c_program_to_input_output
Structure of c_program_to_input_output
 
C language
C languageC language
C language
 
Presentation on C++ programming
Presentation on C++ programming Presentation on C++ programming
Presentation on C++ programming
 
Introduction to c language
Introduction to c languageIntroduction to c language
Introduction to c language
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Basic C Programming language
Basic C Programming languageBasic C Programming language
Basic C Programming language
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
C material
C materialC material
C material
 
Variables in C and C++ Language
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
Programming construction tools
Programming construction toolsProgramming construction tools
Programming construction tools
 
C language basics
C language basicsC language basics
C language basics
 
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
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 

Destaque

Chapter 1 -introduction_to_computers csc
Chapter 1 -introduction_to_computers cscChapter 1 -introduction_to_computers csc
Chapter 1 -introduction_to_computers csc
Tyrah Ira
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computers
VisualBee.com
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
NSU-Biliran Campus
 
DM_iPad_Portfolio
DM_iPad_PortfolioDM_iPad_Portfolio
DM_iPad_Portfolio
Jason Moore
 
Dân văn phòng khổ sở vì thoái hóa đốt sống cổ
Dân văn phòng khổ sở vì thoái hóa đốt sống cổDân văn phòng khổ sở vì thoái hóa đốt sống cổ
Dân văn phòng khổ sở vì thoái hóa đốt sống cổ
burton409
 
My name is Zach
My name is ZachMy name is Zach
My name is Zach
lmarzo01
 

Destaque (20)

Chapter 1 -introduction_to_computers csc
Chapter 1 -introduction_to_computers cscChapter 1 -introduction_to_computers csc
Chapter 1 -introduction_to_computers csc
 
iPhone Training Syllabus - Course
iPhone Training Syllabus - CourseiPhone Training Syllabus - Course
iPhone Training Syllabus - Course
 
France
FranceFrance
France
 
2 memory-and-io-devices
2 memory-and-io-devices2 memory-and-io-devices
2 memory-and-io-devices
 
Objective-C
Objective-CObjective-C
Objective-C
 
Introduction to computers
Introduction to computersIntroduction to computers
Introduction to computers
 
Introduction to computer programming
Introduction to computer programmingIntroduction to computer programming
Introduction to computer programming
 
1 introduction-to-computer
1 introduction-to-computer1 introduction-to-computer
1 introduction-to-computer
 
Computer Hardware
Computer HardwareComputer Hardware
Computer Hardware
 
Computer Programming- Lecture 4
Computer Programming- Lecture 4Computer Programming- Lecture 4
Computer Programming- Lecture 4
 
Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal
Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 ClipsalWatch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal
Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal
 
DM_iPad_Portfolio
DM_iPad_PortfolioDM_iPad_Portfolio
DM_iPad_Portfolio
 
Dân văn phòng khổ sở vì thoái hóa đốt sống cổ
Dân văn phòng khổ sở vì thoái hóa đốt sống cổDân văn phòng khổ sở vì thoái hóa đốt sống cổ
Dân văn phòng khổ sở vì thoái hóa đốt sống cổ
 
Watch Chiefs vs Crusaders - World - Super Rugby 2015 - rugby union scores 201...
Watch Chiefs vs Crusaders - World - Super Rugby 2015 - rugby union scores 201...Watch Chiefs vs Crusaders - World - Super Rugby 2015 - rugby union scores 201...
Watch Chiefs vs Crusaders - World - Super Rugby 2015 - rugby union scores 201...
 
My name is Zach
My name is ZachMy name is Zach
My name is Zach
 
Amrapali Group's Success Story
Amrapali Group's Success StoryAmrapali Group's Success Story
Amrapali Group's Success Story
 
Smk1
Smk1Smk1
Smk1
 
Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal 500
Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal 500Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal 500
Watch 2015 Stadium Super Trucks Clipsal 500 Adelaide Promo - 2015 Clipsal 500
 
Watch Robby Gordon Stadium Super Trucks To Race At The 2015 Clipsal 500 Adela...
Watch Robby Gordon Stadium Super Trucks To Race At The 2015 Clipsal 500 Adela...Watch Robby Gordon Stadium Super Trucks To Race At The 2015 Clipsal 500 Adela...
Watch Robby Gordon Stadium Super Trucks To Race At The 2015 Clipsal 500 Adela...
 
Netwealth educational webinar - The 5 deadly sins of SMSFs
Netwealth educational webinar - The 5 deadly sins of SMSFsNetwealth educational webinar - The 5 deadly sins of SMSFs
Netwealth educational webinar - The 5 deadly sins of SMSFs
 

Semelhante a C101 – Intro to Programming with C

C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
EPORI
 
C++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.pptC++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.ppt
yp02
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineni
abhishekl404
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
Dmitri Nesteruk
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 

Semelhante a C101 – Intro to Programming with C (20)

Intro to .NET and Core C#
Intro to .NET and Core C#Intro to .NET and Core C#
Intro to .NET and Core C#
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++_programs.ppt
C++_programs.pptC++_programs.ppt
C++_programs.ppt
 
C++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.pptC++ programming: Basic introduction to C++.ppt
C++ programming: Basic introduction to C++.ppt
 
Abhishek lingineni
Abhishek lingineniAbhishek lingineni
Abhishek lingineni
 
CPlusPus
CPlusPusCPlusPus
CPlusPus
 
0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf0100_Embeded_C_CompilationProcess.pdf
0100_Embeded_C_CompilationProcess.pdf
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
cs262_intro_slides.pptx
cs262_intro_slides.pptxcs262_intro_slides.pptx
cs262_intro_slides.pptx
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 
Uni texus austin
Uni texus austinUni texus austin
Uni texus austin
 
Basics of C
Basics of CBasics of C
Basics of C
 
College1
College1College1
College1
 
Introduction to C programming
Introduction to C programmingIntroduction to C programming
Introduction to C programming
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 

Último

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
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
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Último (20)

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Ữ Â...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).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
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
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
 
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
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
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
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
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
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

C101 – Intro to Programming with C

  • 1. C101 – Intro to Programming with C Peter Gaal
  • 2. Introduction • Your Name • Your day job • Your last holiday destination?
  • 3. C language overview • procedural, general purpose, cross platform • available almost on every platform • Widely used • Statically typed with weak typing • Manual memory management, low memory footprint • C is not object oriented but C++ and Objective-C has OOP support
  • 4. C++ language overview • OOP support (classes) • available on all major platforms (except embedded devices with small memory) • Widely used • Statically typed, strong typing • Manual memory management (mostly), low memory footprint
  • 5. History of C • general-purpose, procedural programming language, weak typing • First appeared around year 1972, initially developed in AT&T Bell Labs and was used to (re-)implement the Unix operating system • In 1989 became ANSI standard (C89) • Updated in 1999 - C99 and in 2011 - C11 (not all compilers support it)
  • 6. History of C++ • Created by Bjarne Stroustrup in 1979, initially called "C with Classes“ • features: class, derived class, strong typing, inlining, and default argument • 1983: it was renamed from C with Classes to C++ • new features: virtual functions, function name and operator overloading, references, constants, type-safe free-store memory allocation (new/delete)
  • 7. History of C++ • 1989, C++ 2.0: multiple inheritance, abstract classes, static member functions, const member functions, and protected members • 1990: templates, exceptions, namespaces, new casts, boolean type • 1998: became an ISO standard, known as C++98 • recently new major updates: C++11, C++14, C++17
  • 8. Usage of C • Embedded devices • System programming • Operating systems • Drivers • Libraries • Low power, high performance apps
  • 9. Usage of C++ • All high performance/low power apps, similar to C but where we need classes • Games • Low latency • Computer vision • 3D graphics, video, audio • Compression/decompression
  • 10. Software written in C/C++ • Linux kernel (in C), Windows 95-10, Office, SQL, Exchange, VC++, VB, C# compiler • JRE – Java runtime environment • MySQL, Perl, PHP, Python, MongoDB • Adobe Photoshop, VLC player • Firefox, Internet explorer
  • 11. Advantages • Speed, high performance (low power) • Compact (low) memory usage • Low level, “close to the metal” • Deterministic application response (no garbage collection stops the app) • Creates native code, no need to install Java or .NET runtime, good protection against reverse compilation
  • 12. Disadvantages • Hard language, manual memory management, complicated bugs hard to debug like segmentation fault (access violation), memory leaks, dangling pointers, corruption of data, buffer overruns, therefore lower productivity, sometimes hard to read • C/C++ compiler is slow due to complicated syntax (header files, macros)
  • 13. Why is C (C++) hard? • Because you can find or write code like this: • or this: • or this: Hint: if you don’t know what the last code does try to run with these parameters: obama republican democrat or: Jobs Mac PC nixon republican democrat Gates Mac PC bush republican democrat kennedy republican democrat lincoln republican democrat Source: http://www.ioccc.org/2013/cable1/cable1.c The International Obfuscated C Code Contest, year 2013
  • 14. Now seriously, this is a real C code in the libraries (ffmpeg.c, ~line 327):
  • 15. this is also a real C code (libx264.c, ~line 770): • but you can write also a nice, readable code in C/C++ • and you can write also bad, unreadable code in any other language
  • 16. How C/C++ works Source code files (mostly platform independent) .c, .h, .cpp, .hpp Compiler obj files (platform dependent) Library files (.a) (platform dependent) Linker Native executable code (binary file) Platform (CPU) dependent (different output on every platform) main() function – program entry
  • 17. How C/C++ works on different platforms Source code files (mostly platform independent) .c, .h, .cpp, .hpp Compiler + Linker Win32 x86 Win32 x86 Binary (.EXE) Dynamically linked libraries (DLL) – x86Win32 x86 libraries (.a, .lib) Compiler + Linker Win 64bit Windows 64bit Binary (.EXE) Dynamically linked libraries (DLL) – 64bitWin 64bit libraries (.a, .lib) Compiler + Linker Linux x86 Linux x86 Binary (executable) Dynamically linked libraries x86 (.so)Linux x86 libraries (.a) Compiler + Linker Linux ARM Linux ARM Binary (executable) Dynamically linked libraries ARM (.so)Linux ARM libraries (.a)
  • 18. C/C++ File structure Header files *.h (usually C) *.hpp (C++) Source files *.c (usually C) *.cpp (C++) library files *.lib, *.a
  • 19. C/C++ 101 – Intro to Programming with C/C++ Writing your first program in C
  • 21. Writing your first program in C • Create a new “Win32 Console application, Visual C++” in Visual C++ Express named MyFirstCProgram, select empty project on the application settings screen • Create a new CPP file in “Source Files” in Solution Explorer HelloWorld.c as illustrated below: /* Prints “Hello, World” */ #include <stdio.h> int main() { printf("Hello, worldn"); }
  • 22. Compiling Your First C Program • In Visual C++: Press “F7” or “Debug->Build Solution” from main menu • It’s recommended to save your source files but it’s not required in Visual C++, other IDEs might require it
  • 23. Running Your First C Program • Press Ctrl-F5 to Run your program in Visual C++ • Alternatively you can use F5 or “Debug->Start debugging” from main menu
  • 25. /* Prints “Hello, World” */ #include <stdio.h> int main() { printf("Hello, worldn"); } C program structure Comments Included header files (other libraries) Function Arguments (we will have them later) HelloWorld.c
  • 26. Language Features Basic Built-In Types int char float double bool Type Modifiers short (short int) long (long int) signed (by default) unsigned (unsigned int) Flow Control if else for while Punctuation { { ( ) , ; Assignment = Pointers * & (reference) #include <stdio.h> printf() scanf() Operators + - * / % + + -- > < <= >= == != >> << Derived Types struct enum array union Memory Management malloc() free() realloc() sizeof() Qualifiers const volatire Pre-processor Macros #include #define #ifdef #endif Calling Convention cdecl stdcall fastcall Memory Types code stack heap
  • 27. Built-in Data Types type set of values literal values operators char Characters Numbers (-128..127) ‘A’, ‘@’, ‘0’ 65, 32, 0 Compare int integers 17 12345 add, subtract, multiply, divide double Floating-point numbers 3.1415 6.022e23 add, subtract, multiply, divide bool Truth values true false and, or, not
  • 28. Basic Definitions • Variable - a name that refers to a value. • Assignment statement - associates a value with a variable.
  • 29. Strings • In C there is no string type! (as it is in Java) • But you can use strings as array of chars • In C strings are NULL terminated (array of chars) • String is a pointer to first letter (char in the array) Examples of strings (all strings are static) defined length char str[20]=“Hello World”; defined length without initial value char str[20]; automatic length (by compiler) char str[]=“Hello World”; Automatic, pointer syntax char *str=“Hello World”; same definition
  • 30. What is a pointer? A pointer is a variable which contains the address in memory of another variable. Here is your Hello world string in the memory Memory address, where your string is located Here is the content of the pointer in the memory (bytes are in reverse order because of the LITTLE endian architecture) Memory address, where your pointer is located points to a single byte in memory
  • 31. What is a NULL terminated string? char str[] = “Hello”; ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘0’ (null) str[0] str[1] str[2] str[3] str[4] str[5] • string is finished with a special char (null, ‘0’) • warning: ‘0’ is not ‘0’ • “Hello” string with length 5 characters needs at least 6 characters (bytes) to store the string
  • 33. Strings • You can’t concatenate string in a C with an operator (+ in Java or C#) char *result; char *string1 = “Hello “; char *string2 = “World”; result = string1 + string2;
  • 34. Strings • You can concatenate strings using: – strcat (and similar functions) – printf (print formatted data to console) – sprintf (write formatted data to string) • You need to allocate enough memory for the destination string • strcpy – makes a copy of string
  • 35. Concatenating strings /* make sure there is enough memory for the result */ char result[100]; strcpy(result, “Hello “); strcat(result, “World”);
  • 36. Concatenating strings with other types • Use string formatting functions Expression (def.: char result[100]) Value sprintf(result, “%s%s”, “Hi, “, “Bob”); “Hi, Bob” sprintf(result, “Hi, %s”, “Bob”); “Hi, Bob” sprintf(result, “%d %d %d”, 1, 2, 1); “1 2 1” sprintf(result, “%d + %d”, 1234, 99); “1234 + 99” sprintf(result, “%d%d”, 123, 99); “12399” • If you need just to print on the console you can use printf instead of sprintf and you don’t need to allocate the string
  • 37. Command line arguments #include <stdio.h> int main(int argc, char *argv[]) { } argument count array of string arguments argv[0] is the program name with full path argv[1] is the first argument argv[2] is the second argument, etc.
  • 39. Command Line Arguments • Create a program that takes a name as command-line argument and prints “Hi <name>, How are you?” #include <stdio.h> int main(int argc, char *argv[]) { printf("Hi, "); printf(argv[1]); printf(". How are you?n"); }
  • 40. Command Line Arguments • You need to pass an argument into your command line application, otherwise it will crash or will do nothing • Press Alt-F7 (or menu Project->Properties), expand Configuration Properties, select Debugging and in the second line you will see “Command arguments” • Type here your name, then press OK and run the program again • In the next exercise if you will need more than one argument then just put spaces between each argument
  • 41. Command Line Arguments • You shouldn’t pass an unverified string from your command line directly into printf function, so we will modify it: #include <stdio.h> int main(int argc, char *argv[]) { printf("Hi, "); printf("%s", argv[1]); printf(". How are you?n"); }
  • 42. Command Line Arguments • You can do the previous program with just one printf function now: #include <stdio.h> int main(int argc, char *argv[]) { printf("Hi, %s. How are you?n", argv[1]); }
  • 43. Integer Data Type Data Type Attributes Values Integers between -2E31 to +2E31-1 Typical literals 1234, -99 , 99, 0, 1000000 Operation Add subtract multiply divide remainder Operator + - * / % • Useful for expressing algorithms.
  • 44. Integer Data Type Expression Value Comment 5 + 3 8 5 – 3 2 5 * 3 15 5 / 3 1 no fractional part 5 % 3 2 remainder 1 / 0 run-time error 3 * 5 - 2 13 * has precedence 3 + 5 / 2 5 / has precedence 3 – 5 - 2 -4 left associative (3-5) - 2 -4 better style 3 – (5-2) 0 unambiguous
  • 45. Double Data Type • Useful in scientific applications and floating- point arithmetic • float is a type with a “half precision” • sizeof(float)=4, sizeof(double)=8 (in Bytes) Data Type Attributes Values Real numbers specified by the IEEE 754 standard Typical literals 3.14159 6.022e23 -3.0 2.0 1.41421356237209 Operation Add subtract multiply divide Operator + - * /
  • 46. Double Data Type Expression Value 3.141 + 0.03 3.171 3.141 – 0.03 3.111 6.02e23 / 2 3.01e23 5.0 / 3.0 1.6666666666667 10.0 % 3.141 0.577 1.0 / 0.0 Infinity (INF) sqrt(2.0) (#include <math.h>) 1.4142135623730951 not defined in C!
  • 47. C Math Library (#include <math.h>) Methods sin() cos() log() exp() sqrt() pow() fmin() fmax() abs() http://java.sun.com/javase/6/docs/api/java/lang/Math.html • PI constant: you can define by yourself: #define PI 3.14159265358979323846
  • 49. Exercise: Integer Operations • Create new Win32 console application empty project in Visual C++ called IntOps • Create a source file named IntOps.c that performs integer operations on a pair of integers from the command line and prints the results. > IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46
  • 50. Solution: Integer Operations #include <stdio.h> int main(int argc, char *argv[]) { int a,b; int sum, prod, quot, rem; sscanf(argv[1],"%d", &a); sscanf(argv[2],"%d", &b); sum = a + b; prod = a * b; quot = a / b; rem = a % b; printf("%d + %d = %dn", a, b, sum); printf("%d * %d = %dn", a, b, prod); printf("%d / %d = %dn", a, b, quot); printf("%d %% %d = %dn", a, b, rem); } > IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46