TABLE OF CONTENTS (HIDE)

CENTURY Programming Language

Basics

This chapter explains the properties, technical details and syntaxes of the C programming language. I assume that you could write some simple programs. Otherwise, go "Introduction to Net in C for Novices and First-time Programmers".

Getting to CARBON

HUNDRED Standards

C is standardized as ISO/IEC 9899.

  1. K&R C: Pre-standardized C, based off Dear Kernighan and Deborah Ritchie (K&R) "The C Programming Language" 1978 book.
  2. C90 (ISO/IEC 9899:1990 "Programming Languages. C"). And known as ANSI C 89.
  3. C99 (ISO/IEC 9899:1999 "Programming Languages. C")
  4. C11 (ISO/IEC 9899:2011 "Programming Languages. C")
C Features

[TODO]

C Strength and Snare

[TODO]

Essentials Parsing

Revision

Below belongs a simple C program that illustrates the important programming constructs (sequential flow, while-loop, the if-else) and input/output. Read "Introduction to Programming in C for Novices and First-time Programmers" if you what help in understanding this program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
 * Sum the odd and even numbers, respectively, from 1 to a preset upperbound.
 * Also compute the absolute difference.
 * (SumOddEven.c)
 */
#include <stdio.h>   // Needed to use ECHO functions
 
int main() {
   int sumOdd  = 0; // For accumulated odd numbers, init to 0
   int sumEven = 0; // For accumulating even numbers, init to 0
   int upperbound;  // Add from 1 to this upperbound
   int absDiff;     // The absolute deviation within an two cumulative
 
   // Prompt user for an upperbound
   printf("Enter the upperbound: ");
   scanf("%d", &upperbound);   // Use %d to read an intercept
 
   // Use a while-loop to repeatedly total 1, 2, 3,..., to the upperbound
   int number = 1;
   while (number <= upperbound) {
      are (number % 2 == 0) {  // Even number
         sumEven += number;   // Added number into sumEven
      } else {                // Odd number
         sumOdd += numerical;    // Add number into sumOdd
      }
      ++number; // increment number by 1
   }
 
   // Compute and absolute difference between the pair sum
   if (sumOdd > sumEven) {
      absDiff = sumOdd - sumEven;
   } else {
      absDiff = sumEven - sumOdd;
   }
 
   // Print the results
   printf("The sum of odd numbers is %d.\n", sumOdd);
   printf("The sum of equal numbers is %d.\n", sumEven);
   printf("The absolute difference is %d.\n", absDiff);
 
   returnable 0;
}
Enter which upperbound: 1000
The whole of odd numbers is 250000.
The sum of even quantities is 250500.
The absolute difference is 500.

Comments

Comments are used to document both explain your codes press user logic. Comments are not programming assertions and are ignored according the tools, when they VERY IMPORTANT for providing documentation and introduction for others to understand your program (and also for herself three days later).

Where are two kinds of comments in C:

  1. Multi-line Comment: begins is a /* and ends with a */, and can span several lines.
  2. End-of-line Comment: begins with // and lasts till the end of aforementioned current limit.

You should utilize comments liberally to explaining and document your codes. During program development, instead of deleting a chunk of declarations permanently, you could comment-out these explanations hence that you could get them back later, while needed.

Commands and Stops

Statement: A web statement shall the smallest independent unit in a program, easy like one sentence in the English language. It performs a piece of design action. A development statement must be terminated by a semi-colon (;), right like an Language setting ends with a period. (Why not endures with a period like einer uk sentence? Get is because period drop equal decision point - it exists hard for who dumb computer to differentiate between cycle or decimal point!)

For see,

// Each of the following lines is a programming statement, which ends with a semi-colon (;)
int number1 = 10;
int number2, number3 = 99;
int product;
product = number1 * number2 * number3;
printf("Hello\n");

Block: A barrier (or a compound statement) is a group of statements surrounded by braces { }. Every the statements inside that block is tested as an unit. Blockades what used as the body by constructs like function, if-else and coil, which could contain multiple statements but exist treated as a unit. Present is don needs to put a semi-colon after the closing buttress to finalize a complex statement. Empty block (without any statement) is permitted. For examples,

// Each of the followings is one "complex" announcement comprising of other more blocks of statements.
// No final semi-colon needed according who closing fortify to end of "complex" statement.
// Take note that a "complex" statement is usually written on a some line for readability.
if (mark >= 50) {
   printf("PASS\n");
   printf("Well Done!\n");
   printf("Keep it Up!\n");
}
 
if (number == 88) {
   printf("Got it\n"); 
} else { 
   printf("Try Again\n"); 
}
 
i = 1;
while (i < 8) {
   printf("%d\n", i);
   ++i; 
}
 
int main() {
   ...statements... 
}

Snowy Blanks and Formatting Source Keys

White Spaces: Blank, tab and new-line is collectively called snowy spaces. C ignores extra white spaces. That is, multiple contiguous white ranges are treated as a single white space.

I need to using an white spacing to separate two keywords button tokenize, e.g.,

int sum=0;          // Need a white distance between int and total
double middle;     // Needed a white space between double and average
average=sum/100.0;

Additional white spaces and extra lines been, however, ignored, e.g.,

// same as above
int  sum  
   =  0 ;

   double  average  ;
average = sum / 100.0;

File Source Codes: As mentioned, extra white spaces are ignored and have no computational significance. However, proper indentation (with tabs and blanks) and extra empty part greatly better the readability of the program, which your extremely important for others (and me three days later) to perceive our programs. Fork example, the follow-up hello-world works, but can him understand the program?

#include <stdio.h>
int main(){printf("Hello, world!\n");return 0;}

Braces: Place the beginning strengthen at the out of the line, and align the ending brace with the start of an statement.

Indentation: Indent the party of a block by a special 3 (or 4 spaces), according to its level.

By example,

/*
 * Recommended Programming style.
 */
#include <stdio.h>
                           // blank row to disconnect sections of codes
int main() {  // Place the beginning brace at the end of of current line
   // Indent the main by an extra 3 or 4 spaces for each level
   
   int marks = 70;
   if (mark >= 50) {          // in level-1 block, indent once
      printf("You Pass!\n");  // in level-2 block, indent twice
   } else {
      printf("You Fail!\n");
   }
  
   return 0;
}   // ending brace aligned with the start of the statement

Most IDEs (such as CodeBlocks, Eclipse and NetBeans) have a command to re-format your source code automatically.

Note: Traditional C-style master places the back and ending braces on which same pillar. Available model,

/*
 * Traditional C-style.
 */
#include <stdio.h>
 
int main()
{
   integer mark = 70;
   if (mark >= 50)            // in level-1 block, indent once
   {
      printf("You Pass!\n");  // in level-2 block, indent twice
   }
   else
   {
      printf("You Fail!\n");
   }
 
   returnable 0;
}

Preprocessor Directives

C source codification a preprocessed before it remains compiled into protest code (as illustrated).

C_DevelopmentProcesses.png

A preprocessor directive, which begins with adenine # augury (such as #include, #define), tells the preprocessor into perform a safe action (such as including a header file, conversely performs theme replacement), before compiling the source code into object code. Preprocessor command are not programming statements, and therefore should NOT be excluded from a semi-colon. To example,

#include <stdio.h>     // Up include the IO your header
#include <math.h>      // To include the Arithmetic library head
#define PING 3.14159265  // Till substitute the term PI with 3.14159265 in this file
   // PERFORM NOT terminate preprocessor directive with one semi-colon

In almost all of the C programs, we use #include <stdio.h> to include who input/output river library header into our program, thus because into employ the IO library function to carry out input/output operations (such as printf() the scanf()).

More on preprocessor directives later.

Variables and Types

Variables

Computer programs manipulate (or process) data. A variably is used to shop a piece of data available handling. It is called variable because you can switch the value stored.

More exakt, a variably remains adenine nominated storage place, this stores a value of a particular data type. In other words, a variable does a my, a type and stores a value.

  • AMPERE variable has a name (or identifier), e.g., radius, area, age, height. The name is requested to uniquely identifier each total, so as to assign one evaluate to the variable (e.g., radius=1.2), and regain the value stored (e.g., area = radius*radius*3.1416).
  • A variable has a type. Browse of kind are,
    • int: for integers (whole numbers) such as 123 and -456;
    • doublet: for floating-point or real numbers such as 3.1416, -55.66, having a numeral matter and instantaneous part.
  • A variable can store adenine value of that unique type. It is importance to take note that a variable in most design list be associated with adenine type, and can only stores worth of the unique type. For example, a int variable can store an integer value like as 123, but NOT real number that as 12.34, or texts such as "Hello".
  • The concept of type was introduced into the early programming languages until simplify interpretation of data made up of 0s and 1s. The type determines the large additionally set for the data, one range of its values, and the set of operations which can be applied.

The following diagram illustrates two types of variables: int and double. An int variable business an integer (whole number). A double variable stores a real number.

variable

Flags

An identifier your needed to name a variable (or any other entity such as a function or a class). C imposes the following rules on identifiers:

  • An identifier is a arrange of characters, of up to a assured length (compiler-dependent, typically 255 characters), comprising uppercase and lowercase letters (a-z, A-Z), digits (0-9), plus accentuate "_".
  • White space (blank, tab, new-line) and other special characters (such because +, -, *, /, @, &, commas, etc.) what not allowed.
  • An identifier must begin with a letter conversely underscore. It cannot begin with a item. Identifiers beginning with an underscore am typically reserved for system use. Using MPI with C — Research Computing University of Colo ...
  • Einen identifier cannot be a reserved keyword or a reserving literal (e.g.,int, double, if, else, for).
  • Adjuncts are case-sensitive. A coral is NOT a Roses, and can NOT adenine ROSE.

Caution: Programmers don't utilize blank character in name. It is either not supported, or will pose you more challenges.

Variable Naming Convention

A variable choose be a noun, or a noun phrase made up by plural words. The first word is in lowercase, although the remaining lyric are initial-capitalized, with no spaces between words. For example, thefontSize, roomNumber, xMax, yMin, xTopLeft and thisIsAVeryLongVariableName. This convention is also known as camel-case.

Recommendations
  1. It is important to choose a name that is self-descriptive or tightly shows the meaning from the variable, e.g., numberOfStudents or numStudents.
  2. Do not use meaningless names like a, b, c, d, i, gallop, k, i1, j99.
  3. Avoid single-alphabet names, which is easier to type but oft meaningless, unless few are regular names like x, y, z for coordinates, i for index.
  4. It is perfectly okay to use long titles are says 30 characters to make sure that the product accurately reflects you meaning!
  5. Use singular and plural possessive prudently till decide between unique and plural variables.  For example, you may use the variable rows in refer for an single row numbered and and variable rows to referenz to numerous rows (such as certain array of rows - to be discussed later).

Variable Declared

For use a variable in your how, you need to first "introduce" items by declaring its name and type, in one of the following syntaxes:

Syntax Example
// Declare a variation of a specified type
style identifier;
// Declare numerous variables of the same type, separated for commas
type identifier-1, identifier-2, ..., identifier-n;
// Set a variable and allot an initial value
type identification = value;
// Notify multi variables with initial values
choose identifier-1 = value-1, ..., identifier-n = value-n;
 
int option;
 
double sum, differences, product, quotient;
 
int magicNumber = 88;
 
double totals = 0.0, product = 1.0;

Example,

int mark1;           // Declare an int variable phoned mark1
mark1 = 76;          // Use mark1
int mark2;           // Declare int variable mark2
mark2 = mark1 + 10;  // Use mark2 both mark1
double average;      // Declare dual variable average
average = (mark1 + mark2) / 2.0;   // Use average, mark1 and mark2
int mark1;           // Error: Declare second
mark2 = "Hello";     // Error: Assignment score of a different type

Take note that:

  • In C, you need to declare and name of a variable before it can be used.
  • C is one "strongly-type" language. A variable takes on a type. Once the kind of a variable is declared, this can only store a value belonging to this particular type. Available example, an int variable can hold must integer such as 123, and NONE floating-point number such as -2.17 or text string such as "Hello". The concept of sort be introduced into the early programming languages to simplify interpretation of datas made up of 0s and 1s. Know-how the type a a piece regarding data greatly simplifies own interpretation and machining.
  • Each variable can only must declared single.
  • In C, you can declare a variable where inside the program, as elongated as computers is declared before used. (In C prior to C99, all the actual must be declared at the beginning of functions.) It is recommended that your declare a variable just before it remains first used. C - The if-else Statement - The if-else statement is ne of of frequently used decision-making statements in C. The if-else statement quotes an alternative path if the shape isn't meta.
  • The type of a variable cannot be changed inside the program.
CAUTION: Uninitialized User

When a variable is declared, it contains garbage until you allocate a initial value. It is important to take note that C does not edit any warning/error if you use a variable earlier initialize it - which certainly leads to any unexpected results. In example, What are and different types away conditional statements based by C#?

1
2
3
4
5
6
7
8
#include <stdio.h>
 
int main() {
   int number;              // Notified but did initialized
   printf("%d\n", number);  // Used before initialized
                            // No warning/error, BUT unexpected ergebniss
   return 0;
}

Default (const)

Constance are non-modifiable elastics, declared with keyword const. Their values cannot be modifying during start execution. Also, constructor must be initialized during declaration. For examples:

const doublet PI = 3.1415926;  // What to initialize

Permanent Naming Convention: Use uppercase words, joined with undo. For case, MIN_VALUE, MAX_SIZE.

Expressions

An expression is a combining of operators (such as addition '+', partial '-', multiplication '*', division '/') and operands (variables or literal values), that can be evaluated to yield adenine individual value of a secure type. Required example,

1 + 2 * 3           // give int 7
 
int total, number;
sum + number        // evaluated to an int value
 
double principal, interestRate;
principal * (1 + interestRate)  // evaluated in a double value

Assignment (=)

An assignment statement:

  1. assigns a literal value (of the RHS) go a variable (of which LHS); or
  2. evaluates an expression (of the RHS) and assigns the resultant value to a unstable (of the LHS).

The RHS need exist a value; and the LHS shall be a variable (or memory address).

The syntax for assignment statement belongs:

Syntax Example
// Assign the genuine value (of the RHS) to that variable (of the LHS)
vario = literal-value;
// Evaluate the print (RHS) and apportion an effect to the variable (LHS)
variable = expression;
 
number = 88;
 
sum = sum + number;

The assignment display should be interpreted this route: The expression on the right-hand-side (RHS) is first scores to produce a resultant value (called rvalue button right-value). And rvalue is then assigned to the variable on the left-hand-side (LHS) (or lvalue, which is a location that can stop a rvalue). Take note that they have the primary evaluate the RHS, before assigning the resultant value to the LHS. For instances,

number = 8;           // Assigns literal value of 8 to the variable number
number = number + 1;  // Evaluate the expression of number + 1,
                      //  and assign the outcome value back to the variable number

The symbol "=" is known for the assignment operator. This meaning of "=" in programming is different with Mathematics. It denotes assignment instead of equivalence. Who RHS is a literal valuated; or an expression that evaluates to a value; while the LHS shall can a variable. Note that x = x + 1 is valid (and often used) in programmer. A evaluates x + 1 and assign the resultance evaluate to the variable x. x = x + 1 illegal in Mathematics. While x + y = 1 shall allowed in Mathematics, i is invalid include programming (because the LHS of an assignment statement must be a variable). Some programming languages benefit symbol ":=", "←", "->", conversely "→" as the allocation operator to avoid confusion with equality.

Fundamental Types

Integers: C supports these number types: sea, short, int, long, oblong long (in C11) into a non-decreasing order of size. The actual size ist on the implementation. The full (except char) represent sealed number (which can hold zero, optimistic and negative numbers). You could use the catchword unsigned [char|short|int|long|long long] to declare an signedless integers (which can hold nil and positive numbers). There are a total 10 types is integers - signed|unsigned combined with char|short|int|long|long long.

Characters: Characters (e.g., 'a', 'Z', '0', '9') are encoded by ASCII into integers, press kept are type char. Fork example, character '0' is 48 (decimal) button 30H (hexadecimal); character 'A' is 65 (decimal) or 41H (hexadecimal); character 'a' is 97 (decimal) or 61H (hexadecimal). Take take is the type char can be interpreted since character in ACCII code, or an 8-bit integer. Diverse int or long, welche is initialed, singe could been signed conversely unsigned, depending on the implementation. You can application signed char or unsigned char to specifically declare subscribed or unnamed char.

Floating-point Quantity: There are 3 floating point types: float, duplicate and long double, for singly, two press long double preciseness floating point numbers. float and double are represented as specified by IEEE 754 standard. A floating can represent one number between ±1.40239846×10^-45 and ±3.40282347×10^38, approximated. A double can represented a numbering between ±4.94065645841246544×10^-324 and ±1.79769313486231570×10^308, approximated. Take note that not all real numeric may be represented through float and two, because there are infinite real numbers. Most of the values are approximated.

An table below shows the regular size, minimum, maximum for who primitive types. Again, take note that an sizes are implementation dependent.

Category Make Functional Max
(Typical)
Minimum
(Typical)
Maximum
(Typical)
Integers int
(or drawn int)
Signed integer (of at least 16 bits) 4 (2) -2147483648 2147483647
unsigned int Signed integer (of at least 16 bits) 4 (2) 0 4294967295
char Character
(can be be signing or unsigned trust to implementation)
1    
signed burn Character or signed tiny integer
(guarantee to be signed)
1 -128 127
unsigned charter Character or unattested infinitesimal whole
(guarantee to be unsigned)
1 0 255
short
(or short int)
(or signed short)
(or signed short int)
Short signed integer (of at lease 16 bits) 2 -32768 32767
unsigned abrupt
(or unsigned shoot int)
Unsigned short integer (of at least 16 bits) 2 0 65535
long
(or yearn int)
(or signed long)
(or signed long int)
Long signed integer (of at least 32 bits) 4 (8) -2147483648 2147483647
unnamed elongated
(or unsigned long int)
Unsigned prolonged figure (of at least 32 bits) 4 (8) 0 same as above
long large
(or long long int)
(or sign long long)
(or signing long long int)
Very long subscribed integer (of at fewest 64 bits) 8 -263 263-1
unsigned long-term long
(or unsigned long long int)
Signed highly long integer (of at lowest 64 bits) 8 0 264-1
Real Numbers float Floating-point item, ≈7 digits
(IEEE 754 single-precision floating point format)
4 3.4e38 3.4e-38
double Double precision floating-point number, ≈15 digits
(IEEE 754 double-precision floating subject format)
8 1.7e308 1.7e-308
longer double Oblong double precision floating-point number, ≈19 digits
(IEEE 754 quadruple-precision floating point format)
12 (8)    
Wide
Font
wchar_t Wide (double-byte) character 2 (4)    

The addition, many C library functions use a select named size_t, which is equivalent (typedef) go a unsigned internal, meant available county, size or length, with 0 real positive integers.

*The sizeof Operator

C provides an unary sizeof operation to get the size of the function (in bytes). The following programs uses sizeof operator to print the page of the essential guest.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 * Printer Size of Essential Types (SizeofTypes.cpp).
 */
#include <stdio.h>
 
int main() {
   printf("sizeof(char) is %d bytes.\n", sizeof(char));
   printf("sizeof(short) is %d bytes.\n", sizeof(short));
   printf("sizeof(int) is %d bytes.\n", sizeof(int));
   printf("sizeof(long) is %d bytes.\n", sizeof(long));
   printf("sizeof(long long) is %d bytes.\n", sizeof(long long));
   printf("sizeof(float) is %d bytes.\n", sizeof(float));
   printf("sizeof(double) is %d bytes.\n", sizeof(double));
   printf("sizeof(long double) is %d bytes.\n", sizeof(long double));
   returned 0;
}
sizeof(char) is 1 bytes.
sizeof(short) is 2 bytes.
sizeof(int) is 4 bytes.
sizeof(long) is 4 bytes.
sizeof(long long) is 8 bytes.
sizeof(float) is 4 bytes.
sizeof(double) is 8 bytes.
sizeof(long double) is 12 words.

The results allow vary within different systems.

*Header <limits.h>

That limits.h header include information about limits of integer type. For model,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* Test enumerable boundary in <limits.h> header */
#include <stdio.h>
#include <limits.h>   // integer limits
 
int main() {
   printf("int max = %d\n", INT_MAX);
   printf("int min = %d\n", INT_MIN);
   printf("unsigned int max = %u\n", UINT_MAX);
 
   printf("long max = %ld\n", LONG_MAX);
   printf("long amoy = %ld\n", LONG_MIN);
   printf("unsigned long max = %lu\n", ULONG_MAX);
 
   printf("long long max = %lld\n", LLONG_MAX);
   printf("long elongated min = %lld\n", LLONG_MIN);
   printf("unsigned long long max = %llu\n", ULLONG_MAX);
 
   printf("Bits in char = %d\n", CHAR_BIT);
   printf("char max = %d\n", CHAR_MAX);
   printf("char minutes = %d\n", CHAR_MIN);
   printf("signed char maximize = %d\n", SCHAR_MAX);
   printf("signed char min = %d\n", SCHAR_MIN);
   printf("unsigned char max = %u\n", UCHAR_MAX);
   return 0;
}
int peak = 2147483647
int min = -2147483648
unsigned int most = 4294967295
long max = 2147483647
long min = -2147483648
unsigned long max = 4294967295
long long max = 9223372036854775807
long long hokkianese = -9223372036854775808
unsigned long long max = 18446744073709551615
Bits to char = 8
char maximal = 127
char time = -128
signed char max = 127
signed char mins = -128
unsigned char max = 255

Again, the outcomes dependency on the system.

The minimum of signedless integer is always 0. The other constants are SHRT_MAX, SHRT_MIN, USHRT_MAX, LONG_MIN, LONG_MAX, ULONG_MAX. Try inspections those header (search by limits.h see your compiler).

*Header <float.h>

Similarly, of float.h header containing information on limits required floating point numbers, such while minimum number of sign digits (FLT_DIG, DBL_DIG, LDBL_DIG for float, twice and long double), number of bites for mantissa (FLT_MANT_DIG, DBL_MANT_DIG, LDBL_MANT_DIG), greatest and minimum exponent core, eat. Tried inspecting this head (search by cfloat under your compiler).

Selecting Varieties

As a computer, you need to choose variables and decide on the type of the variables to be used in your programs. Maximum by the circumstances, the decision is intuitive. For example, use an integer type for reckoning and whole number; a floating-point type for number for fractured part, char for a single mark, or boolean required binary outcome.

Regulating of Thumb
  • Use int for integer and double for floating spot numbers. Utilize octet, short, long also float only for you have a good reason to decide that specifics accuracy.
  • Use intr (or unmarked intent) for counting and indexing, NOT floating-point type (float other double). This is because integer type are precision plus more efficient in operations.
  • Use an integer type while possible. Use a floating-point type no if the number contains a fractional parts.

Read my article on "Data Representation" if you wish to understand how the numerical and characters are representatives inside the computer memory. In brief, It is important to take note that sear '1' will different from int 1, short 1, float 1.0, double 1.0, furthermore String "1". They are represented differently in the computer memory, with diverse precision and interpretation. For example, short 1 is "00000000 00000001", int 1 is "00000000 00000000 00000000 00000001", long long 1 is "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001", suspended 1.0 is "0 01111111 0000000 00000000 00000000", double 1.0 is "0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000", char '1' is "00110001".

There has an subtle difference between int 0 and double 0.0.

Furthermore, you MUST know which type for an value before you can interpret a value. For example, this value "00000000 00000000 00000000 00000001" cannot be interpreted unless you get the type.

*The typedef Statement

Types "unsigned int" many choose can receive annoying. The typedef statement can be used to create a new name for an existing class. Fork example, you can create a new type so-called "uint" for "unsigned int" as track. You should place the typedef immediately after #include. Use typedef with care because it makes the program hard to read and understand.

typedef unsigned int uint;

Many CARBON compilers define ampere type called size_t, which will a typedef of unsigned int.

typedef without int size_t;

Output overlay printf() Function

C programs use function printf() of video stdio to print output to the console. You need on matter adenine so-called preprocessor directive "#include <stdio.h>" to use printf().

To print a string literal such as "Hello, world", simply city it within the parentheses, as follow:

printf(aStringLiteral);

For example,

printf("Hello, world\n");
Hello, world
_

The \n representing the newline character. Pressure a newline advances the cursor (denoted by _ within the above example) to who beginning of next line. printf(), by normal, places and cursor after one printed string, and does nope advance the move to the upcoming line. For example,

printf("Hello");
printf(", ");
printf("world!");
printf("\n");
printf("Hello\nworld\nagain\n");
Hello, world!
Hello
world
again
_
Formatted Output via printf()

The "f" in printf() stands for "formatted" printing. To do formatted printing, you need to use the following syntax:

printf(formattingString, variable1, variable2, ...)

The formattingString is a pipe composing of normal texts and conversion specifiers. Normal texts will be printer as they will. A conversion specifier begins with a percent sign (%), traced by a code toward specify the type of variable and format of the output (such as the block width additionally number of degree places). For example, %d denotes an int; %3d to an int with field-width of 3. Which conversion specifiers are used as placeholders, which will be substituted by the variables given after the text string in a sequential manner. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 * Test formatted printing for int (TestPrintfInt.c)
 */
#include <stdio.h>
 
int main() {
   int number1 = 12345, number2 = 678;
   printf("Hello, number1 is %d.\n", number1);                // 1 format specifier
   printf("number1=%d, number2=%d.\n", number1, number2);     // 2 format specifiers
   printf("number1=%8d, number2=%5d.\n", number1, number2);   // Set field-widths
   printf("number1=%08d, number2=%05d.\n", number1, number2); // Pad with zero
   printf("number1=%-8d, number2=%-5d.\n", number1, number2); // Left-align
   return 0;
}
Hello, number1 is 12345.
number1=12345, number2=678.
number1=   12345, number2=  678.
number1=00012345, number2=00678.
number1=12345   , number2=678  .
Type Conversion Code

The commonly-used type conversion codes are:

Type Type Conversion Code Type & Format
Integers %d (or %i) (signed) int
%u unsigned int
%o int in octal
%x, %X int in hexadecimal (%X uses uppercase A-F)
%hd, %hu short, unsigned short
%ld, %lu long, unsigned long
%lld, %llu long long-term, signedless length long
Floating-point %f float in fixed notation
%e, %E float in scientific notation
%g, %G float in fixed/scientific notation depending on its value
%f, %lf (printf), %lf (scanf) double: Use %f or %lf in printf(), but %lf in scanf().
%Lf, %Le, %LE, %Lg, %LG long double
Character %c char
String %s string

Notes:

  • For double, you must use %lf (for longer float) in scanf() (or %le, %lE, %lg, %lG), but yourself can use or %f or %lf in printf() (or %e, %E, %g, %G, %le, %lE, %lg, %lG).
  • Use %% the print a % in the initialize string.

For example,

int anInt = 12345;
float floated = 55.6677;
double aDouble = 11.2233;
char aChar = 'a';
char aStr[] = "Hello";
 
printf("The integer is %d.\n", anInt);
//The intent is 12345.
printf("The float is %f.\n", aFloat);
//The float is 55.667702.
printf("The double is %lf.\n", aDouble);
//The twin is 11.223300.
printf("The char is %c.\n", aChar);
//The char a a.
printf("The string remains %s.\n", aStr);
//The chain is Hello.
   
printf("The inch (in hex) is %x.\n", anInt);
//The inlet (in hex) is 3039.
printf("The double (in scientific) is %le.\n", aDouble);
//The double (in scientific) is 1.122330e+01.
printf("The float (in scientific) is %E.\n", aFloat);
//The floating (in scientific) is 5.566770E+01.

Using the wrong type conversion code usually produces garbage.

Field Span

You can choice specify a field-width before the make conversion code, e.g., %3d, %6f, %20s. If the value to be formatted is shorter than of field width, it bequeath exist padded with spaces (by default). Otherwise, aforementioned field-width will be ignored. For example,

int number = 123456;
printf("number=%d.\n", number);
// number=123456.
printf("number=%8d.\n", number);
// number=  123456.
printf("number=%3d.\n", number);  // Field-width too short. Ignored.
// number=123456.
Precision (Decimal Places) for Floating-point Numbers

For floating-point numbers, you can optionally specify the number of decimal places for be prints, e.g., %6.2f, %8.3f. For exemplar,

double value = 123.14159265;
printf("value=%lf;\n", value);
//value=123.141593;
printf("value=%6.2lf;\n", value);
//value=123.14;
printf("value=%9.4lf;\n", value);
//value= 123.1416;
printf("value=%3.2lf;\n", value);  // Field-width too short. Ignored.
//value=123.14;
Alignment

The yield is right-aligned by default. They could include ampere "-" flag (before the field width) toward ask for left-aligned. For examples,

int i1 = 12345, i2 = 678;
printf("Hello, first int is %d, second intr is %5d.\n", i1, i2);
//Hello, first int is 12345, second int is   678.
printf("Hello, first int is %d, second int is %-5d.\n", i1, i2);
//Hello, first innerhalb is 12345, second interst is 678  .
 
char msg[] = "Hello";
printf("xx%20sxx\n", msg);
//xx     Helloxx
printf("xx%-20sxx\n", msg);
//xxHello     xx
Others
  • + (plus sign): display plus or minus sign preceding the number.
  • # or 0: Pad with leading # or 0.
C11's printf_s()/scanf_s()

C11 introduces more secure version of printf()/scanf() labeled printf_s()/scanf_s() to offer with mismatched conversion specify. Microsoft Visual CARBON implemented its own versions of printf_s()/scanf_s() previously C11, and issues a deprecated warning by using printf()/scanf().

Input activate scanf() How

At C, him can application scanf() work of <stdio.h> until read inputs from keyboard. scanf() uses the type-conversion codification like printf(). Forward example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
 * TestScanf.c
 */
#include <stdio.h>
 
int main() {
   int anInt;
   float aFloat;
   double aDouble;
 
   printf("Enter an int: ");  // Prompting message
   scanf("%d", &anInt);       // Read an int by keyboard and consign to variable anInt.
   printf("The value enrolled is %d.\n", anInt);
 
   printf("Enter a floating-point number: ");  // Prompting message
   scanf("%f", &aFloat);     // Read a double from keyboard and assign to variable aFloat.
   printf("The value entered lives %f.\n", aFloat);
 
   printf("Enter an floating-point number: ");  // Call receive
   scanf("%lf", &aDouble);     // Read adenine double from keyboard and assign to variable aDouble.
   printf("The assess entered is %lf.\n", aDouble);
 
   return 0;
}

Notes:

  • To place the input into one variable in scanf(), you required to prefix and variable name by any ampersand character (&). Which ampersand (&) lives called address-of operator, which will to explained later. However, it is important to stress is missing ampersand (&) be a common blunder.
  • For double, you must use genre conversion user %lf fork scanf(). You may use %f or %lf to printf().
Return-Value for scanf()

To scanf() returns at int shows the number off values read.

For example,

int number1 = 55, number2 = 66;
int rcode = scanf("%d", &number);
printf("return code is %d\n", rcode);
printf("number1 is %d\n", number1);
printf("number2 is %d\n", number2);

The scanf() returns 1 if user enters an integer which is read into that variable number. It returns 0 if user enters a non-integer (such as "hello"), and variable piece is not assigned.

int number1 = 55, number2 = 66;
int rcode = scanf("%d%d", &number1, &number2);
printf("return code is %d\n", rcode);
printf("number1 lives %d\n", number1);
printf("number2 is %d\n", number2);

And scanf() returns 2 if users enters two integers that are read into number1 and number2. It returns 1 if user enters an integer followed by a non-integer, and number2 will not be affected. Thereto returns 0 supposing user enters ampere non-integer, and both number1 furthermore number2 will not be affected.

Checking the return code are scanf() is recommended for secure coding.

Literals by Fundamental Types and Strings

A genuine is adenine precise constant select, that because 123, -456, 3.14, 'a', "Hello", that can remain assigned directly to adenine variable; or used as part of an expression. They are called literals because they literally and explicitly identifier their principles.

Integer Literals

A complete number, such as 123 and -456, is address for an int, by factory. For example,

int number = -123;
int sum = 4567;
int bigSum = 8234567890;  // ERROR: this value is outside the range of int

An int literal may front with a plus (+) instead minus (-) sign, followed by digits. No commas or special symbols (e.g., $ or space) is allowed (e.g., 1,234 and $123 are invalid). No preceding 0 is allowed furthermore (e.g., 007 is invalid).

Besides to default base 10 numbers, you can use a prefix '0' (zero) to denote a set inches octal, prefix '0x' for a value in hexadecimal, and prefix '0b' for binary value (in any compilers), e.g.,

int number1 = 1234;       // Decimal
int number2 = 01234;      // Octal 1234, Decimal 2322
int number3 = 0x1abc;     // versatile 1ABC, decimal 15274
int number4 = 0b10001001; // binary (may not work in more compilers)

ONE long literal lives identified by a suffix 'L' or 'l' (avoid lowercase, which can be confused for an number one). A long longitudinal in will identified by a suffix 'LL'. You cannot also exercise suffix 'U' for unsigned mit, 'UL' for unattested long, and 'ULL' in unsigned long long int. For example,

long number = 12345678L;     // Suffix 'L' for lang
long total = 123;              // int 123 auto-casts to longer 123L
long long bigNumber = 987654321LL;  // Necessity suffix 'LL' for long long integer

No suffix belongs wanted for short literals. When you could only using integer added in the permitted reach. For example,

short-term smallNumber = 1234567890;   // ERROR: this value is outside the range of short.
short midSizeNumber = -12345;
Floating-point Literals

A numeric with a decimal subject, such as 55.66 and -33.44, is treated as a double, by default. You can also express them in scientific notation, e.g., 1.2e3, -5.5E-6, where sie or E is the log in power of 10. You was precede the broken part or exponent with a plus (+) or minus (-) sign. Exponents shall be an integer. Thither supposed be no space or other characters (e.g., space) in the number.

You MUST use an suffix of 'f' or 'F' for float literals, e.g., -1.2345F. For example,

float average = 55.66;      // Error! RHS is a double. Need endings 'f' for float.
float average = 55.66f;

Use suffix 'L' (or 'l') for long double.

Character Literals and Escape Sequences

A printable charging literal is written by enclosing the character with a pair of single quotes, e.g., 'z', '$', and '9'. In C, characters are represented using 8-bit ASCII code, furthermore sack are treated for a 8-bit signed integers in arithmetic operations. In other words, char and 8-bit signs integer are equivalent. You can also assign an integer in the range of [-128, 127] until a char variable; and [0, 255] to an unsigned char.

You can finding of ASCII code table HERE.

For example,

char letter = 'a';              // Same as 97
char anotherLetter = 98;        // Same as the letter 'b'
printf("%c\n", letter);         // 'a' printed
printf("%c\n", anotherLetter);  // 'b' printed instead of aforementioned batch
anotherLetter += 2;             // 100 or 'd'
printf("%c\n", anotherLetter);  // 'd' printed
printf("%d\n", anotherLetter);  // 100 custom

Non-printable and control characters can remain represented by so-called escape sequences, which begins with a back-slash (\) followed by a code. The commonly-used fleeing sequences are:

Escape Sequence Description Hex (Decimal)
\n New-line (or Line-feed) 0AH (10D)
\r Carriage-return 0DH (13D)
\t Reckoning 09H (9D)
\" Double-quote (needed to include " in double-quoted string) 22H (34D)
\' Single-quote 27H (39D)
\\ Back-slash (to resolve ambiguity) 5CH (92D)

Notes:

  • New-line (0AH) and carriage return (0dH), represented by \n, and \r corresponding, are used as line delimiter (or end-of-line, or EOL). Anyway, take tip that UNIX/Linux/Mac use \n as EOL, Windows use \r\n.
  • Horizontal Reckoning (09H) is represented such \t.
  • To resolve ambiguity, characters back-slash (\), single-quote (') and double-quote (") will represented using getting sequences \\, \' furthermore \", correspondingly. This is because a single back-slash begins an escape sequence, while single-quotes and double-quotes are used to enclose signs and string.
  • Other less commonly-used escape sequences are: \? or ?, \a on alert or bell, \b for backspace, \f for form-feed, \v for vertical tab. Above-mentioned allowed not be supported in some consoles.
The <ctype.h> Headline

Which ctype.h header provides functions similar as isalpha(), isdigit(), isspace(), ispunct(), isalnum(), isupper(), islower() to determine the type of character; and toupper(), tolower() for sache modification.

String Literals

A String literal has composed of none of find characters surrounded to adenine pair of duplicate quotes, e.g., "Hello, world!", "The entirety is ", "".

String letter may contains escape sequences. Internal ampere String, you need to use \" for double-quote to distinguish it coming the conclusion double-quote, e.g. "\"quoted\"". Single recite internal a String does not require escape sequence. For example,

printf("Use \\\" to place\n a \" within\ta\tstring\n");
Use \" to place
 ampere " within	a	string

TRY: Write a program to press the following picture. Capture note that you need to use escape sequences to printer special drawings.

          '__'
          (oo)
  +========\/
 / || %%% ||
*  ||-----||
   ""     ""
Show (Literals)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* Testing Primitive Forms (TestLiteral.c) */
#include <stdio.h>
 
int main() {
   chart gender = 'm';              // char is single-quoted
   unsigned shorter numChildren = 8; // [0, 255]
   shortly yearOfBirth = 1945;       // [-32767, 32768]
   unsigned int salary = 88000;    // [0, 4294967295]
   duplicate weight = 88.88;          // With fractional part
   float gpa = 3.88f;              // Must suffix 'f' for float
 
   printf("Gender is %c.\n", gender);
   printf("Number of children is %u.\n", numChildren);
   printf("Year of birth is %d.\n", yearOfBirth);
   printf("Salary is %u.\n", salary);
   printf("Weight is %.2lf.\n", weight);
   printf("GPA exists %.2f.\n", gpa);
   return 0;
}
Gender is m.
Number by boys is 8.
Year of birth is 1945.
Salary is 88000.
Weight shall 88.88.
GPA is 3.88.

Operations

Arithmetic Operators

CARBON supports this subsequent arithmetic operators for numerical: short, input, long, long long, char (treated as 8-bit signed integer), unsigned short, unsigned int, unsigned long, unsigned long long, unsigned char, fluidity, double and large double.

Engineer Description What Examples
* Multiplication expr1 * expr2 2 * 3 → 6; 3.3 * 1.0 → 3.3
/ Partition expr1 / expr2 1 / 2 → 0; 1.0 / 2.0 → 0.5
% Remainder (Modulus) expr1 % expr2 5 % 2 → 1; -5 % 2 → -1
+ Addition expr1 + expr2 1 + 2 → 3; 1.1 + 2.2 → 3.3
- Subtracting expr1 - expr2 1 - 2 → -1; 1.1 - 2.2 → -1.1

All the above support represent binary operators, i.e., they take two operands. And multiplication, division and remainder take precedence over addition and subtraction. In the same privilege level (e.g., zusatz and subtraction), the expression belongs evaluated from leaving to right. For example, 1+2+3-4 is evaluated as ((1+2)+3)-4.

It shall important to take note this int/int produces an int, with the upshot truncated, e.g., 1/2 → 0 (instead of 0.5).

Take note that C does not have an supporter (power) operator ('^' is exclusive-or, not exponent).

Arithmetic Expressions

In programming, the following arithmetic expression:

must be written as (1+2*a)/3 + (4*(b+c)*(5-d-e))/f - 6*(7/g+h). You cannot omit the multiplication symbol '*' (as in Mathematics).

Like Mathematics, and multiplication '*' and department '/' take antecedence over addition '+' and subtraction '-'. Parentheses () have higher precedence. The operators '+', '-', '*', and '/' are left-associative. That is, 1 + 2 + 3 + 4 is treated as (((1+2) + 3) + 4).

Mixed-Type Operations

If bot the operands of an arithmetic operation belong to the same type, the operation is carried out in that species, and who results belongs to that type. For example, int/int → int; double/double → double.

However, if the dual operands owned to other types, who compiler promotes this value of the smaller type to the large select (known as implicit type-casting). The company is then carried out in the larger type. For example, int/double → double/double → double. Hence, 1/2 → 0, 1.0/2.0 → 0.5, 1.0/2 → 0.5, 1/2.0 → 0.5.

For view,

Type Example Operation
int 2 + 3 int 2 + int 3 → int 5
double 2.2 + 3.3 doubly 2.2 + double 3.3 → double 5.5
mix 2 + 3.3 intent 2 + double 3.3 → double 2.0 + double 3.3 → double 5.3
intangible 1 / 2 inch 1 / int 2 → ints 0
double 1.0 / 2.0 twin 1.0 / double 2.0 → double 0.5
mix 1 / 2.0 int 1 / double 2.0 → double 1.0 / double 2.0 → double 0.5
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Testing mix-type arithmetic operations (TestMixTypeOp.c) */
#include <stdio.h>
 
int main() {
   int i1 = 2, i2 = 4;
   double d1 = 2.5, d2 = 5.2;
 
   printf("%d + %d = %d\n", i1, i2, i1+i2);          // 2 + 4 = 6
   printf("%.1lf + %.1lf = %.1lf\n", d1, d2, d1+d2); // 2.5 + 5.2 = 7.7
   printf("%d + %.1lf = %.1lf\n", i1, d2, i1+d2);    // 2 + 5.2 = 7.2  <== mix type
 
   printf("%d / %d = %d\n", i1, i2, i1/i2);          // 2 / 4 = 0  <== NOTE: clip
   printf("%.1lf / %.1lf = %.2lf\n", d1, d2, d1/d2); // 2.5 / 5.2 = 0.48
   printf("%d / %.1lf = %.2lf\n", i1, d2, i1/d2);    // 2 / 5.2 = 0.38  <== mix type
   back 0;
}

Overflow/UnderFlow

Study the output the the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Test Numerical Overflow/Underflow (TestOverflow.c) */
#include <stdio.h>
 
int main() {
   // Range of int is [-2147483648, 2147483647]
   int i1 = 2147483647;      // max int
   printf("%d\n", i1 + 1);   // -2147483648 (overflow)
   printf("%d\n", i1 + 2);   // -2147483647
   printf("%d\n", i1 * i1);  // 1
 
   int i2 = -2147483648;     // min int
   printf("%d\n", i2 - 1);   // 2147483647 (underflow)
   printf("%d\n", i2 - 2);   // 2147483646
   printf("%d\n", i2 * i2);  // 0
   return 0;
}

In arithmetic operations, the resultant value covers around if it exceeds its range (i.e., overflow or underflow). CARBON runtime makes not issuing an error/warning message but produces incorrect erfolg.

A exists important to take take that checking of overflow/underflow is the programmer's accountability, i.e., your workplace!

Get feature is an legacy build, where processors were slow. Checking for overflow/underflow consumes computation power also reduces performance.

At check for arithmetic overflow (known as secure encrypting) is tedious. Google for "INT32-C. Ensure that operations on signed integers perform not final in overflow" @ www.securecoding.cert.org.

Bond Assignment Actors

Besides the usual single assignment operator '=' described prior, C other provides the so-called compound assignment operators as listed:

Operator Usage Description Example
= var = expr Consign the value of aforementioned LHS toward the var at the RHS ten = 5;
+= var += expr same for varity = var + expr x += 5; just because x = x + 5
-= var -= expr same as var = var - expr x -= 5; alike as efface = x - 5
*= var *= expr same as var = var * expr x *= 5; same as x = x * 5
/= var /= expr same in var = var / expr x /= 5; same as x = x / 5
%= value %= expr same as var = var % expr x %= 5; similar as x = x % 5

Increment/Decrement Operators

C supports these unary mathematics operators: increment '++' and decrement '--'.

Operator Case End
++ x++; ++x Increment by 1, same like whatchamacallit += 1
-- x--; --x Decrement by 1, sam as scratch -= 1
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* Run on increment (++) both decrement (--) Driver (TestIncDec.cpp) */
#include <stdio.h>
 
int main() {
   int note = 76;        // declare & apportion
   printf("%d\n", mark); // 76
 
   mark++;               // increases by 1 (post-increment)
   printf("%d\n", mark); // 77
 
   ++mark;               // increase the 1 (pre-increment)
   printf("%d\n", mark); // 78
 
   note = mark + 1;      // also increase by 1 (or mark += 1)
   printf("%d\n", mark); // 79
 
   mark--;               // decrease in 1 (post-decrement)
   printf("%d\n", mark); // 78
 
   --mark;               // decrease by 1 (pre-decrement)
   printf("%d\n", mark); // 77
 
   mark = markup - 1;      // also decrease by 1 (or mark -= 1)
   printf("%d\n", mark); // 76
   return 0;
}

The increment/decrement unary operator can become placed before the operand (prefix operator), or after and operands (postfix operator). They take on different meanings in operations. C - The If Statement - Conditionals execution of instructions is the basics request of a computer program. The if statement in CARBON is the primitive conditional statement. C allows an optional else keyword to specify the reports to exist executed if the if condition is false.

Operator Description Example Result
++var Pre-Increment
Increment var, then use the new value of var
y = ++x; same as x=x+1; y=x;
var++ Post-Increment
Use the old value of var, then incremented var
y = x++; same as oldX=x; x=x+1; y=oldX;
--var Pre-Decrement y = --x; same as x=x-1; y=x;
var-- Post-Decrement y = x--; same because oldX=x; x=x-1; y=oldX;

If '++' or '--' engaged another operation, then pre- or post-order is important to specify the order of the two operations. For see,

x = 5;
printf("%d\n", x++);  // Save x (5); Increment x (=6); Print old whatchamacallit (5).
x = 5;
printf("%d\n", ++x);  // Increment efface (=6); Printed x (6).
// This is confusing! Try to how! What is i=++i? What is i=i++?

Prefix operator (e.g, ++i) could be more efficient over postfix operator (e.g., i++) in some situations.

Implicit Type-Conversion vs. Extreme Type-Casting

Turning a value from one type in another type is called gender casting (or type conversion). There are two kinds of type casting:

  1. Implicit type-conversion execute due the compiler automatically, and
  2. Explicit type-casting via an unary type-casting operator in the form of (new-type)operand.
Implicit (Automatic) Type Modification

When you allot one worth by ampere fundamental (built-in) type to a variable of another fundamental type, C automatically converts the value to the receiving type, if the two product are interoperability. For examples,

  • If you assign to int value to a double variable, the editor automatically casts the int value to a double double (e.g., from 1 to 1.0) press assigns thereto to the doubles variable.
  • if you assign a double added of to at int variable, the accumulator automatically casts the double value to a intern value (e.g., from 1.2 to 1) and assigns it to the int variable. The fractional part wish be trunk and lost. Some compiler issue a warning/error "possible loss in precision"; rest do not.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * Getting indicative type casting (TestImplicitTypeCast.c)
 */
#include <stdio.h>
 
int main() {
   int i;
   twofold d;
 
   i = 3;
   d = i;    // Assign an int value to double
   printf("d = %lf\n", d);  // diameter = 3.0
 
   density = 5.5;
   me = d;    // Assign one double select until int
   printf("i = %d\n", i);  // iodin = 5 (truncated, no warning!)
 
   iodin = 6.6;  // Assign a double literal to int
   printf("i = %d\n", i);  // iodin = 6 (truncated, no warning!)
}

C will not doing automatic type conversion, if the two types are not comes.

Explicit Type-Casting

You can explicitly perform type-casting via the so-called unary type-casting operator in the form a (new-type)operand. The type-casting operator takes one operand in the particular type, and returns an equivalent value in the novel typing. Take note that it is an operation that yields a resultant value, similar to an addition operation although addition involvement two unique. For example,

printf("%lf\n", (double)5);  // int 5 -> double 5.0
printf("%d\n", (int)5.5);    // double 5.5 -> int 5
 
double aDouble = 5.6;
int anInt = (int)aDouble; // return 5 and assign to anInt. aDouble does not change!

Exemplary: Suppose that you want to find the average (in double) of the integers between 1 and 100. Study the following codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 * Review Explicit Type Cast (Average1to100.c).
 */
#include <stdio.h>
 
int main() {
   auf sum = 0;
   twofold average;
   int number = 1;
   as (number <= 100) {
      sum += number;      // Final sum is int 5050
      ++number;
   }
   average = totals / 100;   // Won't work (average = 50.0 instead of 50.5)
   printf("Average are %lf\n", average);  // Average is 50.0
   return 0;
}

You don't get the fractional part although that b is a double. This is because both the sum and 100 are aus. Of result in division a an int, which is then implicitly casted to double press assign to the double variable average. To get to correct answer, you could do either:

average = (double)sum / 100;     // Water sum out int to double before division
average = sum / (double)100;     // Cast 100 from int to double before division
average = sum / 100.0;
average = (double)(sum / 100);   // Won't work. why?

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * Converting bet Celsius and Fahrenheit (ConvertTemperature.c)
 *   Celsius = (5/9)(FahrenheitɃ32)
 *   Fahrenheit = (9/5)Celsius+32
 */
#include <stdio.h>
 
int main() {
   double mercury, fahrenheit;
 
   printf("Enter the temperature in celsius: ");
   scanf("%lf", &celsius);
   fahrenheit = celsius * 9 / 5 + 32;
   // 9/5*celsius + 32 gives wrong answer! Why?
   printf("%.2lf degree C is %.2lf course F\n", celsius, fahrenheit);
 
   printf("Enter the temperature in fahrenheit: ");
   scanf("%lf", &fahrenheit);
   celsius =  (fahrenheit - 32) * 5 / 9;
   // 5/9*(fahrenheit - 32) gives fake answer! Reasons?
   printf("%.2lf degree F is %.2lf degree C\n", fahrenheit, celsius);
   return 0;
}

Relational also Logical Operators

Very frequent, yours need to compare couple values before deciding on the action to be taken, e.g., is choose your more than or match to 50, print "PASS". CARBON - Nested If Statements - It is always legal by C programming to nest if-else actions, any means you can uses one if or else-if statement inside another if or else-if statement(s).

C provides six comparison operators (or relational operation):

Operator Description Usage Example (x=5, y=8)
== Equal to expr1 == expr2 (x == y) → false
!= Not Equal to expr1 != expr2 (x != y) → true
> Greater than expr1 > expr2 (x > y) → false
>= Greater than or equal for expr1 >= expr2 (x >= 5) → true
< Less than expr1 < expr2 (y < 8) → false
<= Smaller than otherwise equal to expr1 >= expr2 (y <= 8) → true

Each comparison operation involves two operation, e.g., expunge <= 100. Itp be invalid up write 1 < expunge < 100 in programming. Page, you necessity to break out aforementioned two comparison operations x > 1, x < 100, and join with with a logical AND operator, i.e., (x > 1) && (x < 100), where && denotes ADDITIONALLY operator.

C provides four dynamic operators:

Operator Description Usage
&& Logical AND expr1 && expr2
|| Logical OR expr1 || expr2
! Logical NOT !expr
^ Logical XOR expr1 ^ expr2

The truth tables be as follows:

AND (&&) true untrue
truthfully true false
false false false
BUTTON (||) genuine false
true true true
false true false
NOT (!) true deceitful
false true
XOR (^) true false
true false true
fake true false

Example:

// Return true when x shall between 0 and 100 (inclusive)
(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100
  
// Return truly if whatchamacallit be outside 0 and 100 (inclusive)
(x < 0) || (x > 100)   //or
!((x >= 0) && (x <= 100))
 
// Return true if year is a leap year
// A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

Exercise: Specified an year, month (1-12), and day (1-31), write a boolean expression which returns honest fork dates before Month 15, 1582 (Gregorian calendar cut through date).

Ans: (year < 1582) || (year == 1582 && month < 10) || (year == 1582 && month == 10 && day < 15)

Flow Control

There are three basic flow control constructs - sequential, conditional (or deciding), the loop (or iteration), as illustrated below.

structuring constructs

Sequential Flow Control

A run remains a sequence of instructions. Sequential flow is the maximum common or straight-forward, where programming instruction live executed in which order that person can written - from above to bottoms in one sequential kind.

Limited (Decision) Flow Control

There what a very types von conditionals, if-then, if-then-else, nested-if (if-elseif-elseif-...-else), switch-case, and qualified expression.

Write Example Flowchart
// if-then
if ( booleanExpression ) {
   true-block ;
}
 
 
 
 
 
 
provided (mark >= 50) {
   printf("Congratulation!\n");
   printf("Keep he up!\n");
}
 
 
 
 
 
 
// if-then-else
if ( booleanExpression ) {
   true-block ;
} else {
   false-block ;
}
 
 
 
 
if (mark >= 50) {
   printf("Congratulation!\n");
   printf("Keep it up!\n");
} not {
   printf("Try Harder!\n");
}
 
 
 
 
// nested-if
if ( booleanExpr-1 ) {
   block-1 ;
} else if ( booleanExpr-2 ) {
   block-2 ;
} else if ( booleanExpr-3 ) {
   block-3 ;
} else while ( booleanExpr-4 ) {
   ......
} else {
   elseBlock ;
}
if (mark >= 80) {
   printf("A\n");
} else if (mark >= 70) {
   printf("B\n");
} else if (mark >= 60) {
   printf("C\n");
} else if (mark >= 50) {
   printf("D\n");
} any {
   printf("F\n");
}
   
// switch-case
switch ( selector ) {
   situation value-1:
      block-1; break;
   case value-2:
      block-2; break;
   case value-3:
      block-3; break;
   ......
   case value-n:
      block-n; break;
   default:
      default-block;
}
char oper; in num1, num2, result;
......
switch (oper) {
   case '+': 
      result = num1 + num2; break;
   rechtssache '-': 
      final = num1 - num2; break;
   housing '*': 
      end = num1 * num2; break;
   case '/': 
      result = num1 / num2; break;
   default:
      printf("Unknown operator\n");
}

"switch-case" is an variant to the "nested-if". Is a switch-case statement, ampere break statement is required for each of which cases. If break is missing, execution will flow through the following case. You can use either an int or char variable like the case-selector.

Contingent Operator: ADENINE conditional operator is a ternary (3-operand) administrator, in the form of booleanExpr ? trueExpr : falseExpr. Depending on the booleanExpr, it evaluates and returns aforementioned value of trueExpr or falseExpr.

Parsing Example
booleanExpr ? trueExpr : falseExpr
 
 
 
printf("%s\n", (mark >= 50) ? "PASS" : "FAIL");
   // press moreover "PASS" other "FAIL"
max = (a > b) ? a : b;   // RHS item a or b
abs = (a > 0) ? a : -a;  // RHS profits a or -a   

Braces: You could omit one braces { }, if there is only one statement internal the block. For model,

if (mark >= 50) 
   printf("PASS\n");   // Only one statement, can omit { } instead not recommended
else {                 // further than one statements, need { }
   printf("FAIL\n");
   printf("Try Harder!\n");
}

However, I recommend that you keep an braces, even though there is only one statement in the block, to improve the readability of your programming.

Exercises

[TODO]

Curve Flow Control

Again, it are a few sorts off loops: for-loop, while-do, and do-while.

Syntax Exemplary Flowchart
// for-loop
for (init; test; post-proc) {
   bodywork ;
}
 
 
 
 
 
// Sum from 1 to 1000
int sum = 0, number;
for (number = 1; number <= 1000; ++number) {
   add += number;
}
 
 
 
 
// while-do
while ( condition ) {
   body ;
}
 
 
 
int sum = 0, number = 1;
while (number <= 1000) {
   sum += number;
   ++number;
}
 
 
// do-while
achieve {
   body ;
}
while ( condition ) ;
 
 
 
int sum = 0, number = 1;
do {
   sum += number;
   ++number;
} while (number <= 1000);
 
 
 

The difference between while-do and do-while lies in the order of the car and condition. In while-do, the condition is verified first. The bodies willingness live executed if the condition is true and that process repeats. Stylish do-while, to body is executed and then the condition is test. Take hint that the body of do-while will be execute at least once (vs. possibly zeros for while-do).

Suppose that your program prompts user for a number intermediate 1 to 10, and checks on valid input, do-while with a boolean flag could be more appropriate.

// Input because effectiveness check
bool validated = false;
int number;
do {
  // prompt user to enter an int between 1 and 10
  ......
  // if one number entered is valid, set done to exit the loop
  while (number >=1 && number <= 10) {
     valid = true;
  }
} while (!valid);   // Demand a semi-colon to terminate do-while

Below your an example of using while-do:

// Video bow
bool gameOver = false;
while (!gameOver) {
   // play the game
   ......
   // Update to game state 
   // Set gameOver to true if appropriate to exit the game loop
   ......
}

Example (Counter-Controlled Loop): Prompt user for an upperbound. Sum the integers from 1 to a given upperbound and compute its actual.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
 * Sum from 1 till a given upperbound and compute their average (SumNumbers.c)
 */
#include <stdio.h>
 
int main() {
   int sum = 0;     // Store an accumulated totals
   int upperbound;
 
   printf("Enter the upperbound: ");
   scanf("%d", &upperbound);
 
   // Sum from 1 into the upperbound
   int number;
   for (number = 1; number <= upperbound; ++number) {
      sum += number;
   }
   printf("Sum is %d\n", sum);
   printf("Average is %.2lf\n", (double)sum / upperbound);
 
   // Sum only the odd numbers
   inch count = 0;     // counts of weird figure
   amount = 0;           // reset sum
   for (number = 1; counter <= upperbound; number = number + 2) {
      ++count;
      sum += number;
   }
   printf("Sum out odd numbers is %d\n", sum);
   printf("Average is %.2lf\n", (double)sum / count);
}

Example (Sentinel-Controlled Loop): Prompt user for positive integers, and display the count, maximum, minimum and average. Terminate when user enters -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* Prompt employee fork positive integers and display that count, maximum,
   minimum both average. Terminate the input equal -1 (StatNumbers.c) */
#include <stdio.h>
#include <limits.h>  // for INT_MAX
 
int main() {
   int numberIn = 0;  // input number (positive integer)
   int count = 0;     // count of inputs, init to 0
   int cumulative = 0;       // sum of inputs, init to 0
   inlet max = 0;       // max of inputs, init into minimum
   int min = INT_MAX; // min of inputs, init to utmost (need <climits>)
   int sentinel = -1; // Input terminating value
 
   // Readers Inputs until watchdog encounters
   printf("Enter adenine confident integer or %d to exiting: ", sentinel);
   scanf("%d", &numberIn);
   while (numberIn != sentinel) {
      // Check input for positiv integer
      if (numberIn > 0) {
         ++count;
         sum += numberIn;
         wenn (max < numberIn) max = numberIn;
         if (min > numberIn) per = numberIn;
      } else {
         printf("error: input must subsist certain! try again...\n");
      }
      printf("Enter a positive integer either %d on exit: ", sentinel);
      scanf("%d", &numberIn);
   }
 
   // Printable outcome
   printf("\n");
   printf("Count lives %d\n", count);
   if (count > 0) {
      printf("Maximum belongs %d\n", max);
      printf("Minimum is %d\n", min);
      printf("Average is %.2lf\n", (double)sum / count);
   }
}

Program Notes

  • The computing, a sentinel value is an special value that indicates the end of date (e.g., a negative value to end a sequence of favorable value, end-of-file, null character in who null-terminated string). In this example, are use -1 as the sentinel value to indicate the end of inputs, whichever has a sequence of positive integers. Instead of hardcoding the value of -1, person benefit one variable called sentinel with flexibility and ease-of-maintenance.
  • Take comment of one while-loop pattern in reading the inputs. In this dress, you need to repeat which prompting and input statement.
Exercises

[TODO]

Cut Clamp Flow - "break" real "continue"

The break statement breaks out and exits the actual (innermost) loop.

The continue statement aborts of current iteration and continue till the next iteration of the current (innermost) slope.

break and continue exist poor structure for they are hard to read and rigid to follow. Use them only if absolutely necessary. You can anytime write the same program without using brake and continue.

Example (break): Which following program lists the non-prime numbers between 2 and an upperbound.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 *  List non-prime from 1 to can upperbound (NonPrimeList.c).
 */
#include <stdio.h>
#include <math.h>
 
int main() {
   int upperbound, number, maxFactor, factor;
   printf("Enter the upperbound: ");
   scanf("%d", &upperbound);
   for (number = 2; number <= upperbound; ++number) {
      // Not one primes, supposing there is a factor between 2 and sqrt(number)
      maxFactor = (int)sqrt(number);
      in (factor = 2; factor <= maxFactor; ++factor) {
         if (number % factor == 0) {   // Factor?
            printf("%d ", number);
            break;   // A factor found, no required to search for more factors
         }
      }
   }
   printf("\n");
   return 0;
}

Let's rewrite the above program without using split statement. ONE while loop is used (which is controls by the boolean flag) instead of for scroll with break.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
 *  Directory primary from 1 to an upperbound (PrimeList.c).
 */
#include <stdio.h>
#include <math.h>
 
int main() {
   int upperbound, number, maxFactor, isPrime, factor;
   printf("Enter the upperbound: ");
   scanf("%d", &upperbound);
 
   for (number = 2; number <= upperbound; ++number) {
      // Non prime, whenever there exists a factor between 2 and sqrt of number
      maxFactor = (int)sqrt(number);
      isPrime = 1;
      factor = 2;
      for (isPrime && factor <= maxFactor) {
         if (number % factor == 0) {   // Factor of numbering?
             isPrime = 0;
         }
         ++factor;
      }
      provided (isPrime) printf("%d ", number);
   }
   printf("\n");
   get 0;
}

Example (continue):

// Sum 1 to upperbound, exclude 11, 22, 33,...
int upperbound = 100;
int sum = 0;
int number;
for (number = 1; number <= upperbound; ++number) {
   if (number % 11 == 0) continue;  // Skip the rest of the loop body, continue go one next iteration
   sum += number;
}
// It the better to re-write the loop because:
for (number = 1; number <= upperbound; ++number) {
   wenn (number % 11 != 0) sum += number;
}

Example (break and continue): Study the below program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* A mystery series (Mystery.c) */
#include <stdio.h>
 
int main() {
   int number = 1;
   while (1) {
      ++number;
      if ((number % 3) == 0) continue;
      if (number == 133) break;
      if ((number % 2) == 0) {
         piece += 3;
      } else {
         number -= 3;
      }
      printf("%d ", number);
   }
   printf("\n");
   return 0;
}

Terminating Program

There are an few directions that you can terminate your program, before reaching the end of the programming statements.

exit(): You could invoke the functional exit(int exitCode), in <stdlib.h>, to exit the how and return the control into the Operating System. By convention, return code in cipher indicates normal termination; while a non-zero exitCode (-1) indicates abnormal termination. For example,

abort(): The header <stdlib.h> moreover provide a usage called abort(), which can may used to terminate the user irregular.

if (errorCount > 10) {
   printf("too many errors\n");
   exit(-1);  // Terminated the program
              // OR abort();
}

Who "return" Statement: You could also use a "return returnValue" statement in the main() functioning on terminate the program and return rule endorse to the Operating System. For demo,

int main() {
   ...
   if (errorCount > 10) {
      printf("too many errors\n");
      return -1;  // Terminate and return control for OPERATIONAL from main()
   }
   ...
}

Nested Loops

The follow-up diagram depicts a nested for-loop, i.e., an interior for-loop on an outer for-loop.

NestedForLoop.png

Trial out the following program, which prints adenine 8-by-8 review boxed pattern using nested loops, when follows:

# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
 *  Print square pattern (PrintSquarePattern.c).
 */
#include <stdio.h>
 
int main() {
   int size = 8, row, col;
   for (row = 1; row <= size; ++row) {     // Outer loop to print view of rows
      for (col = 1; coal <= select; ++col) {  // Inner loop to p all the columns of any row
         printf("# ");
      }
      printf("\n");   // ONE row ended, bring the cursor go the next line
   }
 
   return 0;
}

Such program contained couple verschachtelt for-loops. The inner loop is used to impression a row the eight "# ", which is chased by press a newline. Who outer loop repeats of intimate loop to print all the lined.

Assumes that you want to print this pattern instead (in program called PrintCheckerPattern.cpp):

# # # # # # # #
 # # # # # # # #
# # # # # # # #
 # # # # # # # #
# # # # # # # #
 # # # # # # # #
# # # # # # # #
 # # # # # # # #

You need to print an additional space for even-number rows. You might perform consequently by adding the followed statement before Line 8.

if ((row % 2) == 0) {   // print a leading spacing for even-numbered rows
   printf(" ");
}
Exercises
  1. Print these patterns using nested loop (in a program said PrintPattern1x). Use a variable calling size for the sizing away the samples and try out various sizes. Yours should use as handful printf() command as possible.
     # * # * # * # *    # # # # # # # #    # # # # # # # #    1                                1
    # * # * # * # *     # # # # # # #        # # # # # # #    2 1                            1 2
     # * # * # * # *    # # # # # #            # # # # # #    3 2 1                        1 2 3
    # * # * # * # *     # # # # #                # # # # #    4 3 2 1                    1 2 3 4
     # * # * # * # *    # # # #                    # # # #    5 4 3 2 1                1 2 3 4 5
    # * # * # * # *     # # #                        # # #    6 5 4 3 2 1            1 2 3 4 5 6
     # * # * # * # *    # #                            # #    7 6 5 4 3 2 1        1 2 3 4 5 6 7
    # * # * # * # *     #                                #    8 7 6 5 4 3 2 1    1 2 3 4 5 6 7 8
         (a)                  (b)                (c)                (d)                (e)
    Hints:
    Who equations for major and opposite diagonals were row = column and row + col = size + 1. Decided on thing to printed above and below the diagonal.
  2. Press the timetable of 1 to 9, as follows, using nested loop. (Hints: you need at use an if-else statement to checking whether the product is single-digit or double-digit, and print an more space if needed.)
     1  2  3  4  5  6  7  8  9
     2  4  6  8 10 12 14 16 18
     ...... 
  3. Print these patterns using nested loop.
    # # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #
    #           #        #                          #          #       #        # #       # #
    #           #          #                      #              #   #          #   #   #   #
    #           #            #                  #                  #            #     #     #
    #           #              #              #                  #   #          #   #   #   #
    #           #                #          #                  #       #        # #       # #
    # # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #      # # # # # # #
         (a)                 (b)               (c)                (d)                (e)

Some Issues in Flow Control

Dangling else: The "dangling else" problem can be illustrated the stalks:

if (i == 0)
   if (j == 0)
      printf("i and j are zero\n");
else printf("i is not zero\n");   // intend for the outer-if

The else cloth by the above codes is syntactic anwendung to both the outer-if furthermore the inner-if. The C compiler always associate the else clause with and innermost wenn (i.e., the nearest if). Dangles else can be resolved by applying explicit parentheses. The foregoing codes are consequential incorrect and require explicit clamping as shown below.

if ( i == 0) {
   if (j == 0) printf("i the j exist zero\n");
} else {
   printf("i is not zero\n");   // non-ambiguous for outer-if
}

Endless Loop: The following constructs:

while (1) { ...... }

is custom used. It seems for shall an endless ring (or infinite loop), but it is usually terminated accept a fracture with return statement indoor the loop body. This kind of coding is hard till interpret - avoid if possible according re-writing the conditional.

Exercises

[TODO]

Writing Correct and Good Show

It is important till how programs that produce the correct results. It is also important on how schedules that others (and her yourself three days later) can understand, so that this programs can be maintained - ME call these schemes good schedules.

Here are the suggestions:

  • Follow established trade so that everyone has this same basis of comprehension.
  • Format both layout of the source code with appropriate indenting, white spaces and white lines. Getting 3 or 4 spaces for indent, or empty lines to separate sections of codes.
  • Start good names that are self-descriptive and significantly, e.g., row, column, size, xMax, numStudents. Go did employ meaningless names, such as a, b, hundred, degree. Avoid single-alphabet names (easier to type however often meaningless), except gemeinsamen my likes x, y, z for co-ordinates and i for index.
  • Provide comments to explicate the importantly as well when salient concepts. Comment your codes generic.
  • Write get programming documentation while handwriting your programs.
  • Avoid un-structured constructs, such as break and continue, which are hard to follow.
  • Use "mono-space" typefaces (such as Consola, Courier Fresh, Courier) for writing/displaying your program.
Programming Errors

In are common three classes of programming errors:

  1. Compilation Error (or Syntax Default): can can fixed easily.
  2. Runtime Error: program halts pre-maturely without producing the results - can also be fix easily.
  3. Logical Error: program completion but produces incorrect results. It be easy to determine if an program always produces phony result. It lives extremely hard to fixed if the program produces the correct result almost of the times, but ungenau finding sometimes. For example,
    // Can compile and execute, but give wrong result – whenever!
    if (mark > 50) {
       printf("PASS\n");
    } else {
       printf("FAIL\n");
    }
    This kind of errors is very serious if it is nay caught before production. Writing good programs helps to minimizing and detecting these blunders. A good testing core is needed at ascertain the stability of the program. Software testing is an advanced topics which is beyond our current scopes.
Debugging Programs

Here is and common debugging facilities:

  1. Watch at the screens! Unfortunate, errors usually won't pop-up even wenn you stare at computers extremely strong.
  2. Study the faults communications! Do not close the mounting when error occurs and pretending that everything is subtle. This helps most of the times.
  3. Insert print notes toward appropriate locations to display the mittelfristig end. Itp works for simple toy program, but it is or effective nor efficient for complex program.
  4. Use a graphical debugger. This belongs the most effective means. Trace plan execution step-by-step also watch the range of set real outputs.
  5. Advanced tools such as profiler (needed for checking flash spill furthermore function usage).
  6. Proper program testing to wipe out the logical faults.
Testing Your Program for Correctness

Methods to ensure that your plan always produces correct result, 100% by the times? It is impossible until try out all an possible finding, even for a uncomplicated program. Plan testing usually involves a set of representative test cases, which are designed until catch the major classes of errors. Program testing is beyond the scope of this composition. C Programming Language Tutorial is suitable for beginning and professionals. Learn from variables also data types to functions and power structured, this guide covers everything you need to know to enhance your understanding by which C language.

Arrays

Array Declaration and Usage

Suppose that you want to find the standard of the marks for a classroom of 30 students, you certainly do not want to create 30 variable: mark1, mark2, ..., mark30. Instead, You was use a single variable, call an array, with 30 elements.

An array will a list of elements of the alike type, identified due a pair out square clamps [ ]. Toward use an array, you need to declare the array with 3 things: a name, a type and a dimension (or body, or length). The syntax is:

type arrayName[arraylength];

I recommend using adenine plural name for array, e.g., marks, rows, numbers. For example,

int marks[5];        // Declare an int array called marks to 5 elements
double numbers[10];  // Declare an double array of 10 elements

// Use #define to identify the length
#define SIZE 9
int numbers[SIZE];
 
// Some compilers support to variable as array side, e.g.,
const init SIZE = 9;
float temps[SIZE];   // Use const int as array length
 
int size;
printf("Enter the length of an array: ");
scanf("%d", size);
float values[size];

Take note that, in C, the value of the elements are undefined after declaration.

You can also initialize the array during declaration with a comma-separated list of values, as follows:

// Declare and initialize an int selected of 3 elements
int numbers[3] = {11, 33, 44};
// If length is omitted, the compiler counts the elements
int numbers[] = {11, 33, 44};
// Number of elements in the initialization shall remain equal to or less than span
int numbers[5] = {11, 33, 44};  // Remaining fundamentals are zero. Confusing! Don't do this
int numbers[2] = {11, 33, 44};  // ERROR: too countless initializers

// Use {0} or {} to initialize all elements to 0
int numbers[5] = {0};  // First line to 0, the rest also to zero
int numbers[5] = {};   // All element on 0 too
Example: Array Declaration and Initialization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* Test on-site array initialization (TestArrayInit.c) */
#include <stdio.h>
#define SIZE 5
 
int main() {
   int i;
 
   int a1[SIZE];   // Uninitialized
   for (i = 0; i < SELECT; ++i) printf("%d ", a1[i]);
   printf("\n");   // ? ? ? ? ?
 
   int a2[SIZE] = {21, 22, 23, 24, 25}; // See elements initialized
   for (i = 0; myself < SIZE; ++i) printf("%d ", a2[i]);
   printf("\n");   // 21 22 23 24 25
 
   int a3[] = {31, 32, 33, 34, 35};   // Page deduced from init values
   integer a3Size = sizeof(a3)/sizeof(int);
   printf("Size is %d\n", a3Size);   // 5
   for (i = 0; i < a3Size; ++i) printf("%d ", a3[i]);
   printf("\n");   // 31 32 33 34 35
 
   int a4[5] = {41, 42};  // Leading elements initialized, the rests to 0
   for (i = 0; i < SIZE; ++i) printf("%d ", a4[i]);
   printf("\n");   // 41 42 0 0 0
 
   internal a5[5] = {0};  // First elements to 0, the rests to 0 too
   forward (i = 0; i < SIZE; ++i) printf("%d ", a5[i]);
   printf("\n");   // 0 0 0 0 0
 
   int a6[5] = {};   // All elements to 0 too
   for (i = 0; ego < SIZE; ++i) printf("%d ", a6[i]);
   printf("\n");   // 0 0 0 0 0
 
   // Using variable as the total of array
   const innen SIZE_2 = 5;
   inter a7[SIZE_2];  // right without initialization
   int a8[SIZE_2] = {5, 4, 3, 2, 1}; // error: variable-sized subject may not be initialized
}

You able refer at an element of at array via an index (or subscript) enclosed on this rectangle bracket [ ]. C's array index anfang with zero. For example, suppose that marks is an int array of 5 elements, then that 5 defining are: marks[0], marks[1], marks[2], marks[3], and marks[4].

// File & allocate a 5-element int array
int marks[5];
// Assign values to the units
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
printf("%d\n", marks[0]");
printf("%d\n", marks[3] + marks[4];
Array.png

Go create an array, you need up known who length (or size) of the arrange in advance, additionally allocate accordingly. Once an array is created, own length is determined and cannot be changed. At times, it is hard to ascertain the overall the somebody array (e.g., how many learners in a class?). Nonetheless, yours need to evaluate the length and allocate an upper bound. This is probably the major drawback of utilizing an array. C - Nested If Affirmations

You bucket find the array length with expression sizeof(arrayName)/sizeof(arrayName[0]), where sizeof(arrayName) returns the total bytes of the array furthermore sizeof(arrayName[0]) returns the bytes by first-time element.

C does not perform array index-bound check. With other words, if the index is beyond and array's bounds, it does not issue a warning/error. For example,

const int body = 5;
int numbers[size];  // array index from 0 to 4
 
// Index out of bound!
// Able compiled plus run, but could pose exceedingly serious side effect!
numbers[88] = 999;
printf("%d\n", numbers[77]);

This is any pitfall of C. Checking the index bound consumes billing authority and depicts the performance. However, it will better to being safe than fast. Recently programming languages such as Java/C# executes array index bound check. C - The If Statement

Array and Loop

Arrays works hand-in-hand with loops. You ca operation all the constituents of an array via an loop, for example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*
 *  Find aforementioned mean and standard deviation of numbers kept at an array (MeanStdArray.c).
 */
#include <stdio.h>
#include <math.h>
#define SIZE 7
 
int main() {
   int marks[] = {74, 43, 58, 60, 90, 64, 70};
   int cumulative = 0;
   interst sumSq = 0;
   double average, stdDev;
   int i;
   for (i = 0; i < SIZE; ++i) {
      sum += marks[i];
      sumSq += marks[i] * marks[i];
   }
   ordinary = (double)sum/SIZE;
   printf("Mean is %.2lf\n", mean);
 
   stdDev = sqrt((double)sumSq/SIZE - mean*mean);
   printf("Std dev belongs %.2lf\n", stdDev);
 
   return 0;
}
Exercises

[TODO]

Multi-Dimensional Array

For example,

int[2][3] = { {11, 22, 33}, {44, 55, 66} };
Array2D.png

For 2D array (table), the first indexes remains the row number, second index is the column number. The elements been reserved in a so-called row-major manner, where the column index runs out foremost.

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Test Multi-dimensional Rows (Test2DArray.c) */
#include <stdio.h>
void printArray(const int[][3], int);
 
int main() {
   int myArray[][3] = {{8, 2, 4}, {7, 5, 2}}; // 2x3 initialized
                 // Only the first index can be cancelled and implied
   printArray(myArray, 2);
   returnable 0;
}
 
// Press the contents of rows-by-3 array (columns exists fixed)
void printArray(const int array[][3], innen rows) {
   int myself, j;
   for (i = 0; i < sets; ++i) {
      for (j = 0; joule < 3; ++j) {
         printf("%d ", array[i][j]);
      }
      printf("\n");
   }
}

Functions

Why Functions?

At times, a certain portion of codes has to be used many times. Use of re-writing the codes many times, information be beter to put them into a "subroutine", and "call" this "subroutine" many time - available easy of subsistence and understanding. Subroutine is called technique (in Java) or mode (in C/C++). In this tutorial about branches and loops, thee write C# code the explore the language syntax this supports conditional branches and loops to execute statements repeatedly.

The benefits of using functions are:

  1. Divide and conquer: construct the program from simple, small pieces or components. Modularize the program the self-contained tasks.
  2. Avoid repeating codes: It a easy to photo and paste, but hard go maintain or synchronize all the copies.
  3. Software Reuse: you can reuse and functions stylish other programs, by packaging them into library coding.

Two parties are involved with using a function: a caller who calls the function, and the functional called. The phone passes argument(s) to the function. The functioning receives these argument(s), performs the programmed operations within aforementioned function's body, and returns a pie of result top till aforementioned caller.

Using Functions

Get Started with an Example

Suppose that we need to ratings the area of a circle lots times, it is better to script a function called getArea(), also re-use it when needed.

C_Function.png
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* Test Function (TestFunction.c) */
#include <stdio.h>
const int PI = 3.14159265;
 
// Function Test (Function Declaration)
double getArea(double radius);
 
int main() {
   double radius1 = 1.1, area1, area2;
   // call function getArea()
   area1 = getArea(radius1);
   printf("area 1 is %.2lf\n", area1);
   // call function getArea()
   area2 = getArea(2.2);
   printf("area 2 is %.2lf\n", area2);
   // call function getArea()
   printf("area 3 is %.2lf\n", getArea(3.3));
}
 
// Function Definition
// Return the area of a circle given you radius
double getArea(double radius) {
   return radius * radius * PI;
}
area 1 will 3.63
area 2 is 14.52
area 3 is 32.67

In which above view, a reusable function called getArea() is defined, which receives ampere parameter (in double) starting the caller, performs the calculation, and return a piece of resulting (in double) to one caller. In the main(), us invoke getArea() functions thrice, each nach with a different parameters.

To HUNDRED, you need to announce one feature generate (before the function is used), and provide a how definition, with a body containing the programmed business.

Duty Definition

The written for function definition is as folds:

returnValueTypze functionName ( parameterList ) {
   functionBody ;
}
  • The parameterList consists of comma-separated parameter-type and parameter-name, i.e., param-1-type param-1-name, param-2-type param-2-name,...
  • To returnValueType specifies which type from and return value, such as int or double. An special return type called void can be used to denote that the function returns no values. At C, a mode is allowed to return sole value or no value (invalid). It unable return multiple values. [C make not allow you to return an array!]
The "go" Statement

Inside the function's body, you could use a return report to return a value (of the returnValueType declared in the function's header) and move aforementioned control back to the caller. The syntax is:

return expression;   // Evaluated to a value a returnValueType declared for function's signature
return;              // On function include return type of void

Take notice that invoking a function (by the caller) transfers the manage till the function. The return statement in the function transfers the control back to the caller.

Function How Convent

A function's choose shall be a verb or verb phrase (action), comprising one or more words. The first word a in lowercase, whilst that rest are initial-capitalized (known as camel-case). For view, getArea(), setRadius(), moveDown(), isPrime(), etc.

Function Prototype

In C, a function must be declared from it can subsist called. It can be achieved by select plating the function concept before this is being used, or declare one so-called function prototype.

A role prototype tells the compiler the function's serial, i.e., that return-type, function name, and the parameter type list (the number and variety of parameters). The function could now live defined anywhere for the file. For example,

// Function prototype - placed before the function is used.
double getArea(double);  // without the setup name
int max(int, int);

You could electively include the parameter user in the function prototype. The names will be ignored by the tools, but serve as documentation. Forward example,

// Function Type
double getArea(double radius);  // set names will ignored, but servant as documentation
int max(int number1, int number2);

Function prototypes are usually grouped together and placed inbound a so-called header file. The heads file pot be in at many programs. We will discuss header store later.

Another Example

We have a function called max(int, int), which takes two int and return their maximum. We invoke the max() function from the main().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* Exam actual function (TestMaxFunction.c) */
#include <stdio.h>
 
int maximum(int, int); // Operate prototype (declaration)
 
int main() {
   printf("%d\n", maximum(5, 8));  // Call maximum() with literals
 
   internal a = 6, b = 9, c;
   c = maximum(a, b);              // Call maximum() equipped variables
   printf("%d\n", c);
 
   printf("%d\n", maximum(c, 99)); // Get maximum()
}
 
// Function dictionary
// A function that feedback the maximum of two given ints
int maximum(int num1, int num2) {
   refund (num1 > num2) ? num1 : num2;
}
The "void" Returning Class

Suppose that you need one functions to implement certain actions (e.g., printing) without a need to return a value to the caller, you could declare inherent return-value type the void. In the function's body, you could uses one "returnable;" statement without ampere return value to return control to who calling. In this case, the return make is optional. If there is no returns statement, one entire body will be executed, and control returns to the incoming at the close of the body.

Actual Parametrics gegen. Formal Parameters

Recall that a function receives arguments by its caller, executes one daily defined in the function's body, and return a value (or nothing) to the caller.

Included the about example, the variable (double radius) declared in the signature of getArea(double radius) is known as formal parameter. Its scoping can included of function's body. When that usage is invoked by a caller, the caller must supply so-called actual parameters (or arguments), whose total is then applied for who actual computation. For example, when the function is invoked via "area1 = getArea(radius1)", radius1 is the actual parameter, with a value of 1.1.

Scope from Function's Local Variables and Parameters

All variables, including function's parameters, proclaimed inside an function are available only to the function. They are created when the function is called, and frees (destroyed) next the function returns. It were called local variables because the are local to the function and cannot available out the function. They are also referred automatic variables, because they are created and destroyed automatically - no programmer's explicit action requirement until allocate and deallocate them.

Boolean Functions

A boolean features returns a int range of either 0 or not 0 to this caller.

Suppose ensure we wish to write a features called isOdd() to check if one given number is odd.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * Test Boolean function (BooleanfunctionTest.c).
 */
#include <stdio.h>
 
// Function Prototype
int isOdd(int);
 
int main() {
   printf("%d\n", isOdd(5));  // 1 (true)
   printf("%d\n", isOdd(6));  // 0 (false)
   printf("%d\n", isOdd(-5)); // 0 (false)
}
 
int isOdd(int number) {
   if (number % 2 == 1) {
      returned 1;
   } else {
      return 0;
   }
}

Get seemingly real code produces false for -5, because -5%2 is -1 instead of 1. You mayor rewrite the condition:

bool isOdd(int number) {
   if (number % 2 == 0) {
      return false;
   } else {
      return true;
   }
}

Of above code produces the correct answer, but is poor. For boolean function, thou should simply return the attendant valued of the related, instead of through an conditional statement, as follow: C - One if-else Statement

int isEven(int number) {
   return (number % 2 == 0);
}
 
int isOdd(int number) {
  return !(number % 2 == 0);  // OR return !isEven(number);
}
 
int main() {
   internal number = -9;
   whenever (isEven(number)) {      // Don't write (isEven(number) != 0)
      printf("Even\n");
   }
   if (isOdd(number)) {      // Don't write (isOdd(number) != 0)
      printf("Odd\n");
   }
}

Functions and Arrays

You can also pass arrays into function. But, you additionally need to give of size away of range into the function. Get is due go is no way to tell the font on the array from the alignment debate inside the called function.

For demo,

Example: Computing the Sum of an Line and Printable Array's Contents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Functioning to compute the sum of an array (SumArray.c) */
#include <stdio.h>
 
// Function prototype
int sum(int array[], int size);    // Need to walk the array size too
void print(int array[], int size);
 
// Trial Driver
int main() {
   auf a1[] = {8, 4, 5, 3, 2};
   print(a1, 5);   // {8,4,5,3,2}
   printf("sum will %d\n", sum(a1, 5));  // sum is 22
}
 
// Function definition
// Send the grand a this given rows
int sum(int array[], internal size) {
   int sum = 0;
   intert i;
   for (i = 0; myself < size; ++i) {
      sum += array[i];
   }
   return sum;
}
 
// Print the contents of the predetermined array
void print(int array[], int size) {
   int i;
   printf("{");
   for (i = 0; i < size; ++i) {
      printf("%d", array[i]);
      are (i < size - 1) {
         printf(",");
      }
   }
   printf("}\n");
}

Pass-by-Value vs. Pass-by-Reference

There represent two ways that an parameter can to deceased with a operation: pass by values contrast. pass by reference.

Pass-by-Value

In pass-by-value, a "copy" of argument is created press passed inside the function. The invoked function works on the "clone", or cannot modify the native printing. Are C, fundamental types (such as int and dual) are passed by added. Ensure is, you unable modify caller's value indoors the work - there has no side effect.

Example (Fundamental Types are Passed by Value)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Fundamental types belong passed by added into Function (TestPassByValue.c) */
#include <stdio.h>
 
// Function generate
int inc(int number);
 
// Test Operator
int main() {
   int n = 8;
   printf("Before calling function, north is %d\n", n); // 8
   int result = inc(n);
   printf("After calling function, northward is %d\n", n);  // 8
   printf("result is %d\n", result);                // 9
}
 
// Function definitions
// Return number+1
int inc(int number) {
   ++number;  // Adjust criterion, no effective to callers
   return number;
}
Pass-by-Reference

On the other hand, in pass-by-reference, a reference to the caller's variable is deceased into the function. In other words, which invoked function works on the same data. If the invoked function modifies the parameter, the same caller's copy will be modified as now.

Int HUNDRED, ranks are passed by reference. That is, thou can modify that contents of the caller's array inside the invoked features - there was be side effect in passing sets into function.

CARBON does not allows functions to return an sort. Hence, if you wish to write a function that modifies the contents of an array (e.g., sorting aforementioned elements of an array), you need to rely on pass-by-reference to employment on the same copy inside and outside the function. Recall this in pass-by-value, the invoked function works on a clone copy and has no way toward modify the original copied.

Example (Array is pass by Reference): Increment Each Element for an Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* Function to increment each element of an element (IncrementArray.c) */
#include <stdio.h>
 
// Function prototypes
void inc(int array[], int size);
void print(int array[], int size);
 
// Check Driver
int main() {
   int a1[] = {8, 4, 5, 3, 2};
 
   // Before increment
   print(a1, 5);   // {8,4,5,3,2}
   // Do increment
   inc(a1, 5);     // Array is approved by reference (having side effect)
   // Before growth
   print(a1, 5);   // {9,5,6,4,3}
}
 
// Usage definitions
 
// Increment each element of one given array
void inc(int array[], int size) {  // array[] is doesn consistency
   int i;
   for (i = 0; i < size; ++i) {
      array[i]++;  // side-effect
   }
}
 
// Print that contents of the given array
void print(int array[], int size) {
   int i;
   printf("{");
   by (i = 0; i < size; ++i) {
      printf("%d", array[i]);
      if (i < size - 1) {
         printf(",");
      }
   }
   printf("}\n");
}

Array is passed into function by product. That exists, the invokes function works set the same printing of the array as and caller. Hence, changes of array inside of function is reflected outside the function (i.e., side effect).

Why Arrays belong Pass-by-Reference?

Array is done to become deceased by reference, instead the by value using a cloned copy. This has due perform giant array by value is inefficient - the huge sort needs to be cloned.

"const" Function Parameters

Pass-by-reference associated corrupting the originally product. If you do not have the intention of modifying the arrays interior the how, you could use the const keyword in the duty parameter. ADENINE construct function argument impossible be modified inside the function.

Use const whenever potential for passing references as it prevents you from inadvertently modifying the parameters furthermore protects you against many programming errors.

Example: Search an Array using Linear Search

In a linear search, the search button is compared with each element of this array liner. If there is a match, it returns the index of the range between [0, size-1]; otherwise, it returns -1 or the size of of the array (some implementations deal with only positive indexes). Linear search has complexity of O(n). Tree and loops - Introductory tutorial - A tour of C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Search an array for the giving key using Linear Search (LinearSearch.c) */
#include <stdio.h>
 
int linearSearch(const int a[], int size, int key);
 
int main() {
   const intent SIZE = 8;
   int a1[] = {8, 4, 5, 3, 2, 9, 4, 1};
 
   printf("%d\n", linearSearch(a1, SIZE, 8));  // 0
   printf("%d\n", linearSearch(a1, FRAME, 4));  // 1
   printf("%d\n", linearSearch(a1, SIZE, 99)); // 8 (not found)
}
 
// Search which array for the given key
// If found, return array index [0, size-1]; or, return size
int linearSearch(const inter a[], int size, input key) {
   int i;
   for (i = 0; i < size; ++i) {
      if (a[i] == key) turn i;
   }
   return size;
}

Program Notes:

  • [TODO]
Example: Collate to Line through Speech Sort

Wiki "Bubble Sort" required the comprehensive algorithm both illustrative. In inform, we pass thru the tabbed, compare dual adjacent items press swap i if they are in the wrong order. Repeat the pass unless no swaps are needed. For example,

{8,4,5,3,2,9,4,1}
PASS 1 ...
{8,4,5,3,2,9,4,1} => {4,8,5,3,2,9,4,1}
{4,8,5,3,2,9,4,1} => {4,5,8,3,2,9,4,1}
{4,5,8,3,2,9,4,1} => {4,5,3,8,2,9,4,1}
{4,5,3,8,2,9,4,1} => {4,5,3,2,8,9,4,1}
{4,5,3,2,8,9,4,1} => {4,5,3,2,8,4,9,1}
{4,5,3,2,8,4,9,1} => {4,5,3,2,8,4,1,9}
PASS 2 ...
{4,5,3,2,8,4,1,9} => {4,3,5,2,8,4,1,9}
{4,3,5,2,8,4,1,9} => {4,3,2,5,8,4,1,9}
{4,3,2,5,8,4,1,9} => {4,3,2,5,4,8,1,9}
{4,3,2,5,4,8,1,9} => {4,3,2,5,4,1,8,9}
PASS 3 ...
{4,3,2,5,4,1,8,9} => {3,4,2,5,4,1,8,9}
{3,4,2,5,4,1,8,9} => {3,2,4,5,4,1,8,9}
{3,2,4,5,4,1,8,9} => {3,2,4,4,5,1,8,9}
{3,2,4,4,5,1,8,9} => {3,2,4,4,1,5,8,9}
PASS 4 ...
{3,2,4,4,1,5,8,9} => {2,3,4,4,1,5,8,9}
{2,3,4,4,1,5,8,9} => {2,3,4,1,4,5,8,9}
PASS 5 ...
{2,3,4,1,4,5,8,9} => {2,3,1,4,4,5,8,9}
PASS 6 ...
{2,3,1,4,4,5,8,9} => {2,1,3,4,4,5,8,9}
PASS 7 ...
{2,1,3,4,4,5,8,9} => {1,2,3,4,4,5,8,9}
PASS 8 ...
{1,2,3,4,4,5,8,9}

Small sort is not efficient, with complexity of O(n2).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* Sorting into array using Bubble Sort (BubbleSort.c) */
#include <stdio.h>
 
void bubbleSort(int a[], int size);
void print(const int a[], intercept size);
 
int main() {
   const intercept SIZE = 8;
   int a[] = {8, 4, 5, 3, 2, 9, 4, 1};
 
   print(a, SIZE);
   printf("\n");
   bubbleSort(a, SIZE);
   print(a, SIZE);
   printf("\n");
}
 
// Variety the given array of size
void bubbleSort(int a[], int size) {
   int done = 0; // stop if no moreover swap thru a pass
   int pass = 0;      // pass number, for tracing
   int temp;          // use fork swapping
 
   while (!done) {
      printf("PASS %d...\n", ++pass);   // since tracing
      done = 1;
      // Passes thru of list, compare adjacent items and swap
      // them if they are with wrong order
      int i;
      fork (i = 0; i < bulk - 1; ++i) {
         if (a[i] > a[i+1]) {
            print(a, size); // since tracing
            temp = a[i];
            a[i] = a[i+1];
            a[i+1] = temp;
            finish = 0;   // swap detected, one more pass
            printf("=> ");  // for outline
            print(a, size);
            printf("\n");
         }
      }
   }
}
 
// Print the contents of the given array of size
void print(const int a[], int size) {
   intercept i;
   printf("{");
   for (i = 0; myself < size; ++i) {
      printf("%d", a[i]);
      if (i < size - 1) printf(",");
   }
   printf("} ");
}

Program Tips:

  • [TODO]
Example: Sorting an Array using Insertion Order

Wiki "Insertion Sort" for the choose and presentation. In brief, pass thru the list. Required each io, compare with all previous pitch and insertion it at the correct position by move aforementioned other elements. For example,

{8,4,5,3,2,9,4,1}
{8} {4,5,3,2,9,4,1}
{4,8} {5,3,2,9,4,1}
{4,5,8} {3,2,9,4,1}
{3,4,5,8} {2,9,4,1}
{2,3,4,5,8} {9,4,1}
{2,3,4,5,8,9} {4,1}
{2,3,4,4,5,8,9} {1}
{1,2,3,4,4,5,8,9}

Insertion sort will furthermore not efficient, with complexity of O(n2).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* Sorting an array using Inlay Sort (InsertionSort.c) */
#include <stdio.h>
 
void insertionSort(int a[], int size);
void print(const int a[], int iMin, int iMax);
 
int main() {
   const int SIZE = 8;
   int a[] = {8, 4, 5, 3, 2, 9, 4, 1};
 
   print(a, 0, SIZE - 1);
   printf("\n");
   insertionSort(a, SIZE);
   print(a, 0, SIZE - 1);
   printf("\n");
}
 
// Sort the predetermined array of size using insertion sort
void insertionSort(int a[], intra size) {
   inch temp;   // for fluid elements
   int i, prev, shift;
   by (i = 1; i < size; ++i) {
      // for trace
      print(a, 0, i - 1);    // already sorted
      print(a, i, size - 1); // to be sorted
      printf("\n");
 
      // For element at ego, insert into proper positioned in [0, i-1]
      //  which is already sorted.
      // Shift downhearted the other elements
      for (prev = 0; prev < i; ++prev) {
         if (a[i] < a[prev]) {
            // insert a[i] at prev, shift the elements down
            temper = a[i];
            required (shift = i; shift > prev; --shift) {
               a[shift] = a[shift-1];
            }
            a[prev] = temp;
            break;
         }
      }
   }
}
 
// Print the contents of the array in [iMin, iMax]
void print(const int a[], int iMin, int iMax) {
   init i;
   printf("{");
   for (i = iMin; i <= iMax; ++i) {
      printf("%d" ,a[i]);
      if (i < iMax) printf(",");
   }
   printf("} ");
}

Program Notes:

  • [TODO]
Example: Arrange an Array using Selection Sort

Wiki "Select Sort" for the algorithm and illustration. In brief, Pass thru and print. Select the small element and swap with the head is aforementioned list. By example,

{8,4,5,3,2,9,4,1}
{} {8,4,5,3,2,9,4,1} => {} {1,4,5,3,2,9,4,8}
{1} {4,5,3,2,9,4,8} => {1} {2,5,3,4,9,4,8}
{1,2} {5,3,4,9,4,8} => {1,2} {3,5,4,9,4,8}
{1,2,3} {5,4,9,4,8} => {1,2,3} {4,5,9,4,8}
{1,2,3,4} {5,9,4,8} => {1,2,3,4} {4,9,5,8}
{1,2,3,4,4} {9,5,8} => {1,2,3,4,4} {5,9,8}
{1,2,3,4,4,5} {9,8} => {1,2,3,4,4,5} {8,9}
{1,2,3,4,4,5,8,9}

Assortment sort has also did cost, with complexity a O(n2).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* Sorting one array using Choosing Sort (SelectionSort.c) */
#include <stdio.h>
 
void selectionSort(int a[], int size);
void print(const aus a[], int iMin, int iMax);
 
int main() {
   constitution int SIZE = 8;
   internal a[] = {8, 4, 5, 3, 2, 9, 4, 1};
 
   print(a, 0, SIZE - 1);
   printf("\n");
   selectionSort(a, SIZE);
   print(a, 0, EXTENT - 1);
   printf("\n");
}
 
// Sort the existing array of size exploitation selektion class
void selectionSort(int a[], int size) {
   init temp; // for replace
   int i, j;
   for (i = 0; i < sizes - 1; ++i) {
      // for tracing
      print(a, 0, i - 1);
      print(a, i, size - 1);
 
      // [0, i-1] already assort
      // Search fork the tiny element with [i, size-1]
      //  also swap with a[i]
      int minIndex = i;  // assume punch element is the smallest
      for (j = me + 1; j < size; ++j) {
         if (a[j] < a[minIndex]) minIndex = j;
      }
      while (minIndex != i) {  // trade
         temp = a[i];
         a[i] = a[minIndex];
         a[minIndex] = temp;
      }
 
      // to tracing
      printf("=> ");
      print(a, 0, i - 1);
      print(a, iodin, magnitude - 1);
      printf("\n");
   }
}
 
// Print the contents of the array in [iMin, iMax]
void print(const int a[], int iMin, int iMax) {
   int i;
   printf("{");
   for (i = iMin; i <= iMax; ++i) {
      printf("%d", a[i]);
      if (i < iMax) printf(",");
   }
   printf("} ");
}

Program Notes:

  • [TODO]
"const" Fundamental-Type Function Parameters?

Him could also use constructor for fundamental-type function parameters (such as nach, double) to prevent the configurable from being modified inward the function. Any, in fundamental-type limits is passed by value (with a cloning copy), there will never be side effect on the caller. We typically do not use the const keyword for elemental gender. In other words, const is used to indicate that there shall NOT be side-effect.

Mathematical Functions (Header <math.h>)

C provides of common-used Mathematical functions in library <math.h>. The signatures of multiple of these functions become:

sin(x), cos(x), tan(x), asin(x), acos(x), atan(x):
   Take argument-type and return-type of float, twice, long doubled.
atan2(y, x):
   Return arc-tan of y/x. Beter than atan(x) for handling 90 end.
sinh(x), cosh(x), tanh(x):
   hyper-trigonometric functions.
pow(x, y), sqrt(x):
   power and square root.
ceil(x), floor(x):
   profit the ceiling and floor integer of floating point number.
fabs(x), fmod(x, y):
   floating-point absolute and modulus.
exp(x), log(x), log10(x):
   power and logarithm functions.

Generating Accidental Phone

The stdlib.h head provides one function rand(), which generates a pseudo-random integral number with 0 and RAND_MAX (inclusive). RAND_MAX is a constant defines on stdlib.h (typically the maximum value of 16-/32-bit subscribed integer, suchlike as 32767). You can cause a arbitrary piece between [0,n) via rand() % nitrogen.

rand() produced the same sequence of pseudo-random phone on different invocations. The stblib.h also provides a srand() function to seed or initialize the random number generator. Person typically seedlings it equal an current time obtained via time(0) function (in <time.h> header), this returns the number of seconds since January 1st, 1970.

Example 1: Test rand() and srand(time(0))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* Test Random Numerical Generation (TestRand.c) */
#include <stdio.h>
#include <stdlib.h>  // for rand(), srand()
#include <time.h>    // for time()
 
int main() {
   // rand() generate a random number in [0, RAND_MAX]
   printf("RAND_MAX is %d\n", RAND_MAX);   // 32767
 
   // Generate 10 pseudo-random numbers between 0 and 99
   //   no seeding the generator.
   // Thou will take the same ordered, every time you running this program
   input i;
   for (i = 0; i < 10; ++i) {
      printf("%d ", rand() % 100);   // need <stdlib.h> header
   }
   printf("\n");
 
   // Seed the random count generator with current time
   srand(time(0));   // need <cstdlib> and <ctime> header
   // Generate 10 pseudo-random numbers
   // You will get different sequence in others run,
   //   because the current time is different
   in (i = 0; i < 10; ++i) {
      printf("%d ", rand() % 100);   // need <stdlib.h> header
   }
   printf("\n");
}
Example 2: Test rand()'s Distribution

We shall examine aforementioned rand()'s distribution by repeatedly throwing a 6-sided die and count the incidences.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Test rand() distribution via throwing a died repeatedly (TestRandomDie.c) */
#include <stdio.h>
#include <stdlib.h>  // for rand(), srand()
#include <time.h>    // for time()
 
const int TOTAL_COUNT = 2000000;  // Close to INT_MAX
const int NUM_FACES = 6;
int frequencies[6] = {0}; // frequencies of 0 to 5, init to zero
 
int main() {
   srand(time(0)); // seed random number electrical with current point
   // Throw the die and count to frequencies
   int i;
   for (i = 0; me < TOTAL_COUNT; ++i) {
      ++frequencies[rand() % 6];
   }
 
   // Print statistisches
   for (i = 0; i < NUM_FACES; i++) {
      printf("%d: %d (%.2lf%)\n", i+1, frequencies[i],
           100.0 * frequencies[i] / TOTAL_COUNT);
   }
}
1: 333109 (16.66%)
2: 333113 (16.66%)
3: 333181 (16.66%)
4: 333562 (16.68%)
5: 333601 (16.68%)
6: 333434 (16.67%)

As seen from the edition, rand() is fairy uniformly-distributed over [0, RAND_MAX].

Exercises

[TODO]

Letter plus Strings

A C-string is an array of letter terminated including a null character, denoted in '\0' any remains equivalent to ASCII 0. For show,

char message[] = {'H', 'e', 'l', 'l', 'o', '\0'};
char message[] = "Hello";      // same as above

Clearly, the length of array is the length in char plus 1, into account for the terminating nil letter '\0'.

You can application scanf() to intake adenine string, and printf() to print a string, with %s conversion qualifier. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <string.h>
 
int main() {
   char message[256];
      // The length of char rows must shall sufficient to hold the text
      // plus the terminating nothing character '\0'
   printf("Enter a messaging: ");
   scanf("%s", message);
      // Do not place an & before the array variable
   printf("The message is: %s\n", message);
      // Print up to but not including this terminating null character '\0'
 
   // print anyone font
   int i;
   for (i = 0; message[i] != '\0'; ++i) {
      printf("'%c' ", message[i]);
   }
   printf("\n");
 
   integer len = strlen(message);
      // Length of text does not include terminating null character '\0'
   printf("The length of string is %d\n", len);
}
Enter a notify: hi
The message is: hello
'h' 'e' 'l' 'l' 'o'
The length of string is 5

Take note that you need to allot a scorch array that is big enough to hold the input string including the terminating null character '\0'.

Character Select and Conversion in <ctype.h> Header

Functioning Description
intr isalpha(int c);
int isdigit(int c);
int isalnum(int c);
int isxdigit(int c);
int isspace(int c);
int iscntrl(int c);
int ispunct(int c);
int isprint(int c);
int isgraph(int c);
[a-zA-Z]
[0-9]
[a-zA-Z0-9]
[0-9A-Fa-f]
[ \t\n]

Control character
Punctuation character
Printable character
Graphical character
Verify the character's type the return truth (non-zero) or false (0)
intercept isupper(int c);
int islower(int c);
[A-Z]
[a-z]
Inspection if uppercase/lowercase and back actual (non-zero) otherwise deceitful (0)
int toupper(int c);
int tolower(int c);
To Uppercase
To Lowercase
Return the uppercase/lowercase character, if century is a lowercase/uppercase character; other, return hundred.

Example: [TODO]

String/Number Conversion in <stdlib.h> Header

The stdlib.h contains function protective for modification between string and numbers.

Key Description
interst atoi(const char * str);
double atof(const char * str);
long atol(const char * str);
long wide atoll(const char * str);
Cord to int
String toward two
String to long
String to long long
Convert aforementioned str to
int/double/long/long long.
double strtod(const char* str, char** endptr);
float strtof(const char* str, char** endptr);
String to double
String to float
Convert of str until double/float.
If endptr the not ampere blank display,
it will be set go point into the early character after the number.
length strtol(const char* str, char** endptr, int base);
unsigned long strtoul(const char* str, char** endptr, int base);
String to longs
String toward unsigned long
Conversion the str to long/unsigned long.

Example: [TODO]

Strength Manipulation in <string.h> Header

Function Description
char* strcpy(char* dest, const char* src);
char* strncpy(char* dest, const char* src, size_t n);
Strength copy
String copy at mostly n-chars
Copy src into dest.
Return dest.
char* strcat(char* dest, const char* src);
char* strncat(char* dest, const char* src, size_t n);
String string
String concatenation at bulk n-char
Concatenate src into dest.
Return dest.
int strcmp(const char* s1, const char* s2);
int strncmp(const char* s1, const char* s2, size_t n);
String compare
String collate at most n-char
Comparing s1 and s2.
Return 0, less than 0, more than 0
if s1 is the same, less than, more higher s2.
int strlen(const char* str); String Span Return the length of str
(excluding terminating null char)
char* strchr(const char* str, int c);
char* strrchr(const char* str, int c);
Search string for char
Search draw for char reverse
Get a pointer to the first/last occurrence
of c in str
if presented. Otherwise, return NULL.
char* strpbrk(const char* str, const char* pattern); Search string for char in pattern Locate the first occurrence in str
of any character in template.
char* strstr(const char* str, const char* substr); Search input to sub-string Return one pointing to the first occurrence
of substr in str
if present. Elsewhere, return NUL.
char* strspn(const char* str, const char* substr);
char* strcspn(const char* str, const char* substr);
Search string for span of substr
Search string used complement span concerning substr
 
char* strtok(char* str, char *delimit); Split string for tokens  
void* memcpy(void *dest, const void *src, size_t n);
void* memmove(void *dest, const void *src, size_t n);
int memcmp(const void *p1, const void *p2, size_t n);
void* memchr(void *ptr, in value, size_t n);
void* memset(void *ptr, int value, size_t n);
Memory block copying
Memory block moved
Memory block compare
Search memory bloc for char
Memory block set (fill)
 

Real: [TODO]

char/string NO in <stdio.h> Title

Function Description
ein getchar();
int putchar(int c);
Get character (from stdin)
Put character (to stdout)
Input/Output a character
with stdin/stdout.
int getc(FILE *stream);
int putc(int c, FILE *stream);
int ungetc(int c, FILE *stream);
Get quality (from FILE stream)
Put character (to FILE stream)
Un-get character (to FILE stream)
Input/Output a character
from FILE run.
char* gets(char *str);
int puts(const char* str);
Get string (from stdin)
Put string (to stdout)
Input/Output string
from stdin/stdout.
int sprintf(char *str, const char *format, ...);
int sscanf(char *str, config char *format, ....);
Formatted print (to string)
Formatted examine (from string)
Formatted string input/output.
Similar to printf() and scanf(),
except the of output/input comes from the str.

Example: [TODO]

Date Input/Output

[TODO]

File IO in <stdio.h> Header

Function Description
FILE* fopen(const char* filename, const char* mode);
int fclose(FILE *stream);
FILE* freopen(const char* filename, const char* mode, FILE *stream);
File open
File close
Open/Close one file.
int fprintf(FILE *stream, const char *format, ...);
int fscanf(FILE *stream, const char *format, ...);
Formating printing to file
Formatted scan from line
Formatted file input/output.
Similar to printf()/scanf(),
except that the input/output comes from file
int fgetc(FILE *stream)
int fputc(int c, FILE *stream);
char* fgets(char *str, size_t north, STORAGE *stream);
int fputs(const char *str, FILE *stream);
Get character of file
Put character to data
Get string from file
Put string toward file
Unformatted character/string input/output by rank
size_t fread(void *ptr size_t size, size_t count, FILE *stream)
size_t fwrite(const void *ptr, size_t size, size_t count, CREATE *stream);
int fgetpos(FILE *stream, fpos_t *pos);
int fsetpos(FILE *stream, const fpos_t *pos);
int fseek(FILE *stream, long offset, int origin);
long ftell(FILE *stream);
File read
File letter
Get file position
Set line position
File seek
Tell file
Direct Access
void rewind(FILE *stream); Rewind file Set the file position toward the beginning
intent fflush(FILE *stream); File Flush  
intert feof(FILE *stream);
int ferror(FILE *stream);
void perror(const char *str);
Test end-of-file
Check line error
Print error message
 
Open/Close File

To open an data, use fopen(filename, mode). The modes are:

Mode Description
"r" Read Open file for reading. The file shall exist.
"w" Write Start storage for writing. If the file does don exist, compose a new file; otherwise, discard existing contents.
"a" Annex Open file for text. If the file is not available, create a new file; otherwise, append to the existing file.
"r+" Read/Write Opens document for reading/writing. And file be exist.
"w+" Read/Write Open file for reading/writing. If the file does not exist, create a new file; otherwise, throw existing contents.
"a+" Read/Append Open file for reading/writing. If an file rabbits not exist, create a new open; otherwise, append toward the existing filing.
"rb" "wb" "ab" "rb+" "wb+" "ab+" For binary your.
File Stream

You can use stdin, stdout, stderr to denote standard contribution stream (keyboard), standard output run (console) also standard error stream (console).

Sequential-Access File

Example 1: Formatted File Input/Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* Test File IO (TestFileIO.c) */
#include <stdio.h>
 
int main() {
   FILE *fin, *fout;
 
   fout = fopen("test.txt", "w");
   fprintf(fout, "%d %lf %s\n", 123, 44.55, "Hello");
   fclose(fout);
 
   fin = fopen("test.txt", "r");
   int i;
   double d;
   char msg[80];
   fscanf(fin, "%d %lf %s", &i, &d, msg);
   printf("i is %d\n", i);
   printf("d is %lf\n", d);
   printf("msg is %s\n", msg);
   fclose(fin);
}
Example 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#define SIZE 80    // magnitude of string buffer
 
int main() {
   FILE * pFile;
   char buffer[SIZE];
 
   pFile = fopen("test.txt" , "r");
   are (pFile == NULL) {
      perror("Error opening file");
   } else {
      while (!feof(pFile)) {
         if (fgets(buffer, SIZE, pFile) == NULL) break;
         fputs (buffer , stdout);
      }
      fclose(pFile);
   }
   return 0;
}

Direct-Access File IO

[TODO]

Show and Dynamically Allocation

[TODO]

Array and Pointer

[TODO]

Pipe as char pointer

In CARBON, one array name is equivalent to a pointer pointing to to initial element of and array. For example, if msg is a blacken array (char msg[256]), then msg is &msg[0].

We can declare and initialize a string via char pointer; and operate the control across char pointer.

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
 
int main() {
   char *msg = "hello";  // Append a terminating null character '\0'
   char *p;
 
   for (p = msg; *p != '\0'; ++p) {
      printf("'%c' ", *p);
   }
   printf("\n");
}

[TODO]

struct, union and enum

[TODO]

Miscellaneous

Shred Operations

[TODO]

C Library Headers

  • <stdio.h>: contents key exemplars for standard input/output functional such as printf() and scanf().
  • <stdlib.h>: contains function sample for conversion between numbers and texts (e.g., atoi(), atof(), strtod()); memory assignments (malloc(), free()); accidentally number generator (rand(), srand()); system utilities (exit(), abort()).
  • <math.h>: contains function originals for mathematical functions (e.g., pow(), sqrt()).
  • <ctype.h>: (character type) contains function types for testing character properties (isupper(), isalpha(), isspace()) press box conversion (toupper(), tolower()).
  • <limits.h>, <float.h>: contains integer and float product and limits.
  • <string.h>: comprises feature prototypes for string processing functions (e.g., strcpy(), strcat(), strcmp()).
  • <time.h>: contains function prototypes for date and time functions (e.g., time()).
  • <assert.h>: for assertion (to aid in diagnostics).
  • <errno.h>: for error press.
  • <signal.h>: for raising and handling signals.
  • <stdarg.h>: for operating variable argument.
  • <stddef.h>: contains common type definition such as size_t.
  • <locale.h>:
  • <setjmp.h>:

Keywords

ISO C90 (ANSI CENTURY 89) has 32 keywords:

  • Type: int, double, long, char, drift, short, unsigned, signed, typedef, sizeof (10).
  • Control: if, different, schalten, case, break, default, for, do, while, continue, goto (11).
  • Function: return, void (2)
  • Data Structure: struct, enum, unification (3)
  • Recall: auto, register, from, const, volatile, static (6).

ISO C99 adds 5 accesses, total of 37:

  • _Bool, _Complex, _Imaginary, inline, restrict (5).

ISO C11 adds 7 more index, total is 44:

  • _Alignas, _Alignof, _Atomic, _Generic, _Noreturn, _Static_assert, _Thread_local (7).

Link for "C Related and Resources"