The C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system.
The C is the most widely used computer language, it keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers.
Presented at Agile Prague (16th September 2014)
Video available at https://vimeo.com/108007508
These days testing is considered a sexy topic for programmers. Who'd have thought it? But what makes for good unit tests (GUTs)? There's more to effective unit testing than just knowing the assertion syntax of a framework.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What style of test partitioning is most common, and yet scales poorly and is ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and can scale as the codebase grows?
Presented at Agile Singapore (13th November 2014)
These days testing is considered sexy for programmers. Who'd have thought it? But there is a lot more to effective programmer testing than the fashionable donning of a unit-testing framework: writing Good Unit Tests (GUTs) involves (a lot) more than knowledge of assertion syntax.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What style of test partitioning is most common, and yet scales poorly and is ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and scalable to large codebases?
Presented at Agile Prague (16th September 2014)
Video available at https://vimeo.com/108007508
These days testing is considered a sexy topic for programmers. Who'd have thought it? But what makes for good unit tests (GUTs)? There's more to effective unit testing than just knowing the assertion syntax of a framework.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What style of test partitioning is most common, and yet scales poorly and is ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and can scale as the codebase grows?
Presented at Agile Singapore (13th November 2014)
These days testing is considered sexy for programmers. Who'd have thought it? But there is a lot more to effective programmer testing than the fashionable donning of a unit-testing framework: writing Good Unit Tests (GUTs) involves (a lot) more than knowledge of assertion syntax.
Testing represents a form of communication and, as such, it offers multiple levels and forms of feedback, not just basic defect detection. Effective unit testing requires an understanding of what forms of feedback and communication are offered by tests, and what styles encourage or discourage such qualities.
What style of test partitioning is most common, and yet scales poorly and is ineffective at properly expressing the behaviour of a class or component? What styles, tricks and tips can be used to make tests more specification-like and scalable to large codebases?
Esoft Metro Campus - Diploma in Information Technology - (Module VIII) Programming with Java
(Template - Virtusa Corporate)
Contents:
Introduction to Java
Features of Java
What you can create by Java?
Start Java Programming
Creating First Java Program
Java Virtual Machine
Basic Rules to Remember
Keywords in Java
Comments in Java Programs
Printing Statements
Primitive Data Types in Java
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Nested If Statement
While Loop
Do While Loop
For Loop
Reading User Input
Arrays
Two Dimensional Arrays
Objects and Classes
Java Classes
Java Objects
Methods with Return Value
Methods without Return Value
Method Overloading
Variable Types
Inheritance
Method Overriding
Access Modifiers
Packages
GUI Applications in Java
Java Applets
● Introduction to Arrays
● Declaration and initialization of one dimensional and two-dimensional
arrays.
● Definition and initialization of String
● String functions
Rule 1: Follow a consistent coding standard
Rule 2: Name things properly, long variable and function names are allowed
Rule 3: Be expressive, write code as you speak and be optimally verbose
Rule 4: Max indent per method should be 2, in case of exceptions 3
Rule 5: Avoid creating god object and long methods
Rule 6: Keep the method in one place, inject the class and call it, DRY
Rule 7: Avoid in-line comments (comment with code), put comments in the method doc
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
Esoft Metro Campus - Diploma in Web Engineering - (Module VI) Fundamentals of PHP
(Template - Virtusa Corporate)
Contents:
Introduction to PHP
What PHP Can Do?
PHP Environment Setup
What a PHP File is?
PHP Syntax
Comments in PHP
echo and print Statements
PHP Variables
PHP Data Types
Changing Type by settype()
Changing Type by Casting
PHP Constants
Arithmetic Operators
String Operators
Assignment Operators
Comparison Operators
Logical Operators
Operators Precedence
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
break Statement
continue Statement
Functions
User Defined Functions
Functions - Returning values
Default Argument Value
Arguments as Reference
Existence of Functions
Variable Local and Global Scope
The global Keyword
GLOBALS Array
Superglobals
Static Variables
Esoft Metro Campus - Diploma in Information Technology - (Module VIII) Programming with Java
(Template - Virtusa Corporate)
Contents:
Introduction to Java
Features of Java
What you can create by Java?
Start Java Programming
Creating First Java Program
Java Virtual Machine
Basic Rules to Remember
Keywords in Java
Comments in Java Programs
Printing Statements
Primitive Data Types in Java
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Nested If Statement
While Loop
Do While Loop
For Loop
Reading User Input
Arrays
Two Dimensional Arrays
Objects and Classes
Java Classes
Java Objects
Methods with Return Value
Methods without Return Value
Method Overloading
Variable Types
Inheritance
Method Overriding
Access Modifiers
Packages
GUI Applications in Java
Java Applets
● Introduction to Arrays
● Declaration and initialization of one dimensional and two-dimensional
arrays.
● Definition and initialization of String
● String functions
Rule 1: Follow a consistent coding standard
Rule 2: Name things properly, long variable and function names are allowed
Rule 3: Be expressive, write code as you speak and be optimally verbose
Rule 4: Max indent per method should be 2, in case of exceptions 3
Rule 5: Avoid creating god object and long methods
Rule 6: Keep the method in one place, inject the class and call it, DRY
Rule 7: Avoid in-line comments (comment with code), put comments in the method doc
● Concept of Structure and Union
● Declaration and Initialization of structure and union
● Nested structures
● Array of Structures
● Passing structure to functions
Esoft Metro Campus - Diploma in Web Engineering - (Module VI) Fundamentals of PHP
(Template - Virtusa Corporate)
Contents:
Introduction to PHP
What PHP Can Do?
PHP Environment Setup
What a PHP File is?
PHP Syntax
Comments in PHP
echo and print Statements
PHP Variables
PHP Data Types
Changing Type by settype()
Changing Type by Casting
PHP Constants
Arithmetic Operators
String Operators
Assignment Operators
Comparison Operators
Logical Operators
Operators Precedence
If Statement
If… Else Statement
If… Else if… Else Statement
Switch Statement
The ? Operator
While Loop
Do While Loop
For Loop
break Statement
continue Statement
Functions
User Defined Functions
Functions - Returning values
Default Argument Value
Arguments as Reference
Existence of Functions
Variable Local and Global Scope
The global Keyword
GLOBALS Array
Superglobals
Static Variables
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
Abstract: Chances are you code in a language that's either descended from C, inspired by C, or run in an interpreter that itself is written in C. Still... do you actually know how to code in C? Despite its long-standing position as a sort of "lingua franca", an agreed-upon common language, more and more developers are putting together successful, satisfying careers, without ever learning this seminal language. But what if you have to call into C code from your favorite scripting language, or use APIs like OpenGL that are written to be called from C? Many developers find C very challenging, particularly its manual memory-management and other low-level concerns. In this session, we'll show you why you shouldn't be afraid of C, how you can use the skills you already have from the languages you code in today, and how to master structs, enums, typedefs, malloc(), free(), and the rest of C's sharp edges. Examples will be from the point-of-view of the C-skewing iPhone SDK, but will be designed to be broadly applicable and platform-agnostic.
Short name for wireless fidelity and is meant to be used generically when referring to any type of IEEE 802.11 network. Whether 802.11b, 802.11a, 802.11g etc.
Wi-Fi is a wireless technology that uses radio frequency (ISM Band, 2.4/5 GHz) to transmit data through data through air.
What are Digital Thermometers?
Digital thermometers are temperature-sensing instruments that are easily portable, have permanent probes, and a convenient digital display.
The way a digital thermometer works depends upon its type. They are generally a resistance temperature detector (RTD), thermocouple digital, or thermistor digital thermometer
An embedded system is closely integrated with the main system
It may not interact directly with the environment
For example – A microcomputer in a car ignition control
Official name of GPS is Navigational Satellite Timing And Ranging Global Positioning System (NAVSTAR GPS)
It costs about $750 million to manage and maintain the system per year
Mainly used for navigation, map-making and surveying
The GPS project was developed in 1973 to overcome the limitations of previous navigation systems
It became fully operational in 1994. Roger L. Easton is generally credited as its inventor
DNS, which stands for domain name system, controls your domain name's website and email settings. When visitors go to your domain name, its DNS settings control which company's server it reaches out to.
RAID (originally redundant array of inexpensive disks, now commonly redundant array of independent disks) is a data storage virtualization technology that combines multiple physical disk drive components into a single logical unit for the purposes of data redundancy, performance improvement, or both.
RAID (originally redundant array of inexpensive disks, now commonly redundant array of independent disks) is a data storage virtualization technology that combines multiple physical disk drive components into a single logical unit for the purposes of data redundancy, performance improvement, or both.
Moisture control project is uses full and interesting project. It can help to farmer. It is consist of BJT, Resisters, Capacitors, I C etc. Moisture control device will be completed by four sections. The basis of operation for this system is the Over – watering and under watering both are harmful for plants. Roots need air as well as water. If the soil is constantly saturated, air cannot reach the roots and they suffocate. Also, excess water weakens the plant and makes it susceptible to various diseases, particularly fungal attacks, under watering on the other hand, is equally harmful, plants not receiving enough water droop from the top down and leaf edge turn brown. Moisture monitor provides a solution to the above problem by monitoring the moisture level of the soil and producing an audio – visual alert when the moisture goes below a preset level, indicating that the plant needs to be watered.
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfFlorence Consulting
Quattordicesimo Meetup di Milano, tenutosi a Milano il 23 Maggio 2024 dalle ore 17:00 alle ore 18:30 in presenza e da remoto.
Abbiamo parlato di come Axpo Italia S.p.A. ha ridotto il technical debt migrando le proprie APIs da Mule 3.9 a Mule 4.4 passando anche da on-premises a CloudHub 1.0.
Understanding User Behavior with Google Analytics.pdfSEO Article Boost
Unlocking the full potential of Google Analytics is crucial for understanding and optimizing your website’s performance. This guide dives deep into the essential aspects of Google Analytics, from analyzing traffic sources to understanding user demographics and tracking user engagement.
Traffic Sources Analysis:
Discover where your website traffic originates. By examining the Acquisition section, you can identify whether visitors come from organic search, paid campaigns, direct visits, social media, or referral links. This knowledge helps in refining marketing strategies and optimizing resource allocation.
User Demographics Insights:
Gain a comprehensive view of your audience by exploring demographic data in the Audience section. Understand age, gender, and interests to tailor your marketing strategies effectively. Leverage this information to create personalized content and improve user engagement and conversion rates.
Tracking User Engagement:
Learn how to measure user interaction with your site through key metrics like bounce rate, average session duration, and pages per session. Enhance user experience by analyzing engagement metrics and implementing strategies to keep visitors engaged.
Conversion Rate Optimization:
Understand the importance of conversion rates and how to track them using Google Analytics. Set up Goals, analyze conversion funnels, segment your audience, and employ A/B testing to optimize your website for higher conversions. Utilize ecommerce tracking and multi-channel funnels for a detailed view of your sales performance and marketing channel contributions.
Custom Reports and Dashboards:
Create custom reports and dashboards to visualize and interpret data relevant to your business goals. Use advanced filters, segments, and visualization options to gain deeper insights. Incorporate custom dimensions and metrics for tailored data analysis. Integrate external data sources to enrich your analytics and make well-informed decisions.
This guide is designed to help you harness the power of Google Analytics for making data-driven decisions that enhance website performance and achieve your digital marketing objectives. Whether you are looking to improve SEO, refine your social media strategy, or boost conversion rates, understanding and utilizing Google Analytics is essential for your success.
Gen Z and the marketplaces - let's translate their needsLaura Szabó
The product workshop focused on exploring the requirements of Generation Z in relation to marketplace dynamics. We delved into their specific needs, examined the specifics in their shopping preferences, and analyzed their preferred methods for accessing information and making purchases within a marketplace. Through the study of real-life cases , we tried to gain valuable insights into enhancing the marketplace experience for Generation Z.
The workshop was held on the DMA Conference in Vienna June 2024.
Instagram has become one of the most popular social media platforms, allowing people to share photos, videos, and stories with their followers. Sometimes, though, you might want to view someone's story without them knowing.
Ready to Unlock the Power of Blockchain!Toptal Tech
Imagine a world where data flows freely, yet remains secure. A world where trust is built into the fabric of every transaction. This is the promise of blockchain, a revolutionary technology poised to reshape our digital landscape.
Toptal Tech is at the forefront of this innovation, connecting you with the brightest minds in blockchain development. Together, we can unlock the potential of this transformative technology, building a future of transparency, security, and endless possibilities.
Italy Agriculture Equipment Market Outlook to 2027harveenkaur52
Agriculture and Animal Care
Ken Research has an expertise in Agriculture and Animal Care sector and offer vast collection of information related to all major aspects such as Agriculture equipment, Crop Protection, Seed, Agriculture Chemical, Fertilizers, Protected Cultivators, Palm Oil, Hybrid Seed, Animal Feed additives and many more.
Our continuous study and findings in agriculture sector provide better insights to companies dealing with related product and services, government and agriculture associations, researchers and students to well understand the present and expected scenario.
Our Animal care category provides solutions on Animal Healthcare and related products and services, including, animal feed additives, vaccination
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
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
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--;
}
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
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++