C Language Notes


Introducing C
C is a general-purpose programming language that has been around for nearly 50 years.
C has been used to write everything from operating systems (including Windows and many others) to complex programs like the Python interpreter, Git, Oracle database, and more.
The versatility of C is by design. It is a low-level language that relates closely to the way machines work while still being easy to learn.
Understanding how computer memory works is an important aspect of the C programming language.
C is a:
Photo editing program
Client-side scripting language
General purpose programming language
Hello World!

As when learning any new language, the place to start is with the classic "Hello World!" program:
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}
Try It Yourself

Let's break down the code to understand each line:
#include <stdio.h> The function used for generating output is defined in stdio.h. In order to use the printf function, we need to first include the required file, also called a header file.

int main() The main() function is the entry point to a program. Curly brackets { } indicate the beginning and end of a function (also called a code block). The statements inside the brackets determine what the function does when executed.
Tap Try It Yourself to play around with the code.
Fill in the blanks to include the <stdio.h> header.
#include <
Hello World!

The printf function is used to generate output:
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}
Try It Yourself

Here, we pass the text "Hello World!" to it.
The \n escape sequence outputs a newline character. Escape sequences always begin with a backslash \.
The semicolon ; indicates the end of the statement. Each statement must end with a semicolon.

return 0; This statement terminates the main() function and returns the value 0 to the calling process. The number 0 generally means that our program has successfully executed. Any other number indicates that the program has failed.
Tap Try It Yourself to play around with the code.
Fill in the blanks to output "Hi, everyone!" to the screen:
("Hi, everyone!")
Data Types

C supports the following basic data types:
int: integer, a whole number.
float: floating point, a number with a fractional part.
double: double-precision floating point value.
char: single character.

The amount of storage required for each of these types varies by platform.
C has a built-in sizeof operator that gives the memory requirements for a particular data type.
For example:
#include <stdio.h>

int main() {
printf("int: %d \n", sizeof(int));
printf("float: %d \n", sizeof(float));
printf("double: %d \n", sizeof(double));
printf("char: %d \n", sizeof(char));

return 0;
}
Try It Yourself

The program output displays the corresponding size in bytes for each data type.
The printf statements in this program have two arguments. The first is the output string with a format specifier (%d), while the next argument returns the sizeof value. In the final output, the %d (for decimal) is replaced by the value in the second argument.
Note that C does not have a boolean type.

A printf statement can have multiple format specifiers with corresponding arguments to replace the specifiers. Format specifiers are also referred to as conversion specifiers.
We will learn more about format specifiers in the upcoming lessons.
Which of the following are valid data types in C?
int, float, double, char
int, float, string, char
int, double, char, boolean
int, bool, string
Variables
A variable is a name for an area in memory.
The name of a variable (also called the identifier) must begin with either a letter or an underscore and can be composed of letters, digits, and the underscore character.
Variable naming conventions differ, however using lowercase letters with an underscore to separate words is common (snake_case).
Variables must also be declared as a data type before they are used.

The value for a declared variable is changed with an assignment statement.
For example, the following statements declare an integer variable my_var and then assigns it the value 42: int my_var;
my_var = 42;
You can also declare and initialize (assign an initial value) a variable in a single statement: int my_var = 42;
Let's define variables of different types, do a simple math operation, and output the results:
#include <stdio.h>

int main() {
int a, b;
float salary = 56.23;
char letter = 'Z';
a = 8;
b = 34;
int c = a+b;

printf("%d \n", c);
printf("%f \n", salary);
printf("%c \n", letter);

return 0;
}
Try It Yourself

As you can see, you can declare multiple variables on a single line by separating them with a comma. Also, notice the use of format specifiers for float (%f) and char (%c) output.
The C programming language is case-sensitive, so my_Variable and my_variable are two different identifiers.

Constants


A constant stores a value that cannot be changed from its initial assignment.
By using constants with meaningful names, code is easier to read and understand.
To distinguish constants from variables, a common practice is to use uppercase identifiers.

One way to define a constant is by using the const keyword in a variable declaration:
#include <stdio.h>

int main() {
const double PI = 3.14;
printf("%f", PI);

return 0;
}
Try It Yourself

The value of PI cannot be changed during program execution.
For example, another assignment statement, such as PI = 3.141 will generate an error.
Constants must be initialized with a value when declared.
Another way to define a constant is with the #define preprocessor directive.
The #define directive uses macros for defining constant values.
For example:
#include <stdio.h>

#define PI 3.14

int main() {
printf("%f", PI);
return 0;
}
Try It Yourself

Before compilation, the preprocessor replaces every macro identifier in the code with its corresponding value from the directive. In this case, every occurrence of PI is replaced with 3.14.
The final code sent to the compiler will already have the constant values in place.

The difference between const and #define is that the former uses memory for storage and the latter does not.
Do NOT put a semicolon character at the end of #define statements. This is a common mistake.
We will learn more about preprocessor directives in the next modules.
Fill in the blanks to declare a constant variable PI of type double.
const double  PI = 3.14;


Input


C supports a number of ways for taking user input.
getchar() Returns the value of the next single character input.

For example:
#include <stdio.h>

int main() {
char a = getchar();

printf("You entered: %c", a);

return 0;
}
Try It Yourself

The input is stored in the variable a.

The gets() function is used to read input as an ordered sequence of characters, also called a string.
A string is stored in a char array.
For example:
#include <stdio.h>

int main() {
char a[100];

gets(a);

printf("You entered: %s", a);

return 0;
}
Try It Yourself

Here we stored the input in an array of 100 characters.

scanf() scans input that matches format specifiers.

For example:
#include <stdio.h>

int main() {
int a;
scanf("%d", &a);

printf("You entered: %d", a);

return 0;
}
Try It Yourself

The & sign before the variable name is the address operator. It gives the address, or location in memory, of a variable. This is needed because scanf places an input value at a variable address

As another example, let's prompt for two integer inputs and output their sum:
#include <stdio.h>

int main() {
int a, b;
printf("Enter two numbers:");
scanf("%d %d", &a, &b);

printf("\nSum: %d", a+b);

return 0;
}
Try It Yourself

scanf() stops reading as soon as it encounters a space, so text such as "Hello World" is two separate inputs for scanf().
ype in a code to read a character from the input.
char c = 
();
Output


We have already used the printf() function to generate output in the previous lessons. In this lesson, we cover several other functions that can be used for output.

putchar() Outputs a single character.
For example:
#include <stdio.h>

int main() {
char a = getchar();

printf("You entered: ");
putchar(a);

return 0;
}
Try It Yourself

The input is stored in the variable a.

The puts() function is used to display output as a string.
A string is stored in a char array.
For example:
#include <stdio.h>

int main() {
char a[100];

gets(a);

printf("You entered: ");
puts(a);

return 0;
}
Try It Yourself

Here we stored the input in an array of 100 characters.

scanf() scans input that matches format specifiers.

For example:
#include <stdio.h>

int main() {
int a;
scanf("%d", &a);

printf("You entered: %d", a);

return 0;
}
Try It Yourself

The & sign before the variable name is the address operator. It gives the address, or location in memory, of a variable. This is needed because scanf places an input value at a variable address

As another example, let's prompt for two integer inputs and output their sum:
#include <stdio.h>

int main() {
int a, b;
printf("Enter two numbers:");
scanf("%d %d", &a, &b);

printf("\nSum: %d", a+b);

return 0;
}
Try It Yourself

scanf() stops reading as soon as it encounters a space, so text such as "Hello World" is two separate inputs for scanf().
Fill in the blank to output the single character.
char c = 's';
putchar = (c)

Formatted Input


The scanf() function is used to assign input to variables. A call to this function scans input according to format specifiers that convert input as necessary.
If input can't be converted, then the assignment isn't made.
The scanf() statement waits for input and then makes assignments:
int x;
float num;
char text[20];
scanf("%d %f %s", &x, &num, text);
Try It Yourself

Typing 10 22.5 abcd and then pressing Enter assigns 10 to x, 22.5 to num, and abcd to text.
Note that the & must be used to access the variable addresses. The & isn't needed for a string because a string name acts as a pointer.

Format specifiers begin with a percent sign % and are used to assign values to corresponding arguments after the control string. Blanks, tabs, and newlines are ignored.
A format specifier can include several options along with a conversion character:
%[*][max_field]conversion character
The optional * will skip the input field.
The optional max_width gives the maximum number of characters to assign to an input field.
The conversion character converts the argument, if necessary, to the indicated type:
d decimal
c character
s string
f float
x hexadecimal

For example:
int x, y;
char text[20];

scanf("%2d %d %*f %5s", &x, &y, text);
/* input: 1234 5.7 elephant */
printf("%d %d %s", x, y, text);
/* output: 12 34 eleph */
Try It Yourself

Tap Try It Yourself to experiment with input formats.
Fill in the blanks to input two integer variables using the scanf() function:
int num1, num2;
scanf("%d %d", &num2);
Formatting Output


The printf function was introduced in your very first Hello World program. A call to this function requires a format string which can include escape sequences for outputting special characters and format specifiers that are replaced by values.
For example:
printf("The tree has %d apples.\n", 22);
/* The tree has 22 apples. */

printf("\"Hello World!\"\n");
/* "Hello World!" */
Try It Yourself

Escape sequences begin with a backslash \:
\n new line
\t horizontal tab
\\ backslash
\b backspace
\' single quote
\" double quote

Format specifiers begin with a percent sign % and are replaced by corresponding arguments after the format string. A format specifier can include several options along with a conversion character: %[-][width].[precision]conversion character
The optional - specifies left alignment of the data in the string.
The optional width gives the minimum number of characters for the data.
The period . separates the width from the precision.
The optional precision gives the number of decimal places for numeric data. If s is used as the conversion character, then precision determines the number of characters to print.
The conversion character converts the argument, if necessary, to the indicated type:
d decimal
c character
s string
f float
e scientific notation
x hexadecimal

For example:
printf("Color: %s, Number: %d, float: %5.2f \n", "red", 42, 3.14159);
/* Color: red, Number: 42, float: 3.14 */

printf("Pi = %3.2f", 3.14159);
/* Pi = 3.14 */

printf("Pi = %8.5f", 3.14159);
/* Pi = 3.14159 */

printf("Pi = %-8.5f", 3.14159);
/* Pi = 3.14159 */

printf("There are %d %s in the tree.", 22, "apples");
/* There are 22 apples in the tree. */
Try It Yourself

To print the % symbol, use %% in the format string.
Tap Try It Yourself to experiment with string formats.
Comments
Comments are explanatory information that you can include in a program to benefit the reader of your code. The compiler ignores comments, so they have no affect on a program.
A comment starts with a slash asterisk /* and ends with an asterisk slash */ and can be anywhere in your code.
Comments can be on the same line as a statement, or they can span several lines.
For example:
#include <stdio.h>

/* A simple C program
* Version 1.0
*/

int main() {
/* Output a string */
printf("Hello World!");
return 0;
}
Try It Yourself

As you can see, comments clarify the program's intent to the reader. Use comments to clarify the purpose and logic behind segments of code.
Single-line Comments
C++ introduced a double slash comment // as a way to comment single lines. Some C compilers also support this comment style.
For example:
#include <stdio.h>

int main() {
int x = 42; //int for a whole number

//%d is replaced by x
printf("%d", x);

return 0;
}
Try It Yourself
Adding comments to your code is good programming practice. It facilitates a clear understanding of the code for you and for others who read it.
Fill in the blank to create a single-line comment:
 this is a single-line comment

Arithmetic Operators


C supports arithmetic operators + (addition), - (subtraction), * (multiplication), / (division), and % (modulus division).
Operators are often used to form a numeric expression such as 10 + 5, which in this case contains two operands and the addition operator.
Numeric expressions are often used in assignment statements.
For example:
#include <stdio.h>

int main() {
int length = 10;
int width = 5;
int area;

area = length * width;
printf("%d \n", area); /* 50 */

return 0;
}Try It Yourself

Division


C has two division operators: / and %.
The division / operator performs differently depending on the data types of the operands. When both operands are int data types, integer division, also called truncated division, removes any remainder to result in an integer. When one or both operands are real numbers (float or double), the result is a real number.
The % operator returns only the remainder of integer division. It is useful for many algorithms, including retrieving digits from a number. Modulus division cannot be performed on floats or doubles.
The following example demonstrates division:
#include <stdio.h>

int main() {
int i1 = 10;
int i2 = 3;
int quotient, remainder;
float f1 = 4.2;
float f2 = 2.5;
float result;

quotient = i1 / i2; // 3
remainder = i1 % i2; // 1
result = f1 / f2; // 1.68

return 0;
}Try It Yourself
Tap Try It Yourself to play around with the code.

Operator Precedence


C evaluates a numeric expression based on operator precedence.
The + and – are equal in precedence, as are *, /, and %.
The *, /, and % are performed first in order from left to right and then + and -, also in order from left to right.
You can change the order of operations by using parentheses ( ) to indicate which operations are to be performed first.
For example, the result of 5 + 3 * 2 is 11, where the result of (5 + 3) * 2 is 16.

For example:
#include <stdio.h>

int main() {
int a = 6;
int b = 4;
int c = 2;
int result;
result = a - b + c; // 4
result = a + b / c; // 8
result = (a + b) / c; // 5

return 0;
}
Try It Yourself

C may not evaluate a numeric expression as desired when the associative property allows any order. For example, (x * y) * z may be evaluated as x * (y * z). If order is important, break the expression into separate statements.
Fill in the blanks to subtract y from x and add z to the result.
int x = 6;
int y = 4;
int z = 2;
int res = x 
 y 
 z;
ype Conversion


When a numeric expression contains operands of different data types, they are automatically converted as necessary in a process called type conversion.
For example, in an operation involving both floats and ints, the compiler will convert the int values to float values.
In the following program, the increase variable is automatically converted to a float:
#include <stdio.h>

int main() {
float price = 6.50;
int increase = 2;
float new_price;

new_price = price + increase;
printf("New price is %4.2f", new_price);
/* Output: New price is 8.50 */

return 0;
}
Try It Yourself

Note the format specifier includes 4.2 to indicate the float is to be printed in a space at least 4 characters wide with 2 decimal places.
When you want to force the result of an expression to a different type you can perform explicit type conversion by type casting, as in the statements:
float average;
int total = 23;
int count = 4;

average = (float) total / count;
/* average = 5.75 */
Try It Yourself

Without the type casting, average will be assigned 5.
Explicit type conversion, even when the compiler may do automatic type conversion, is considered good programming style.
Tap Try It Yourself to play around with the code and experiment with the format specifier.
Explicitly convert the result of the division to float:
average = (
) total / count;
Assignment Operators


An assignment statement evaluates the expression on the right side of the equal sign first and then assigns that value to the variable on the left side of the =. This makes it possible to use the same variable on both sides of an assignment statement, which is frequently done in programming.
For example: int x = 3;
x = x + 1; /* x is now 4 */
To shorten this type of assignment statement, C offers the += assignment operator. The statement above can be written as x += 1; /* x = x + 1 */
Many C operators have a corresponding assignment operator. The program below demonstrates the arithmetic assignment operators:
int x = 2;

x += 1; // 3
x -= 1; // 2
x *= 3; // 6
x /= 2; // 3
x %= 2; // 1
x += 3 * 2; // 7
Try It Yourself

Look carefully at the last assignment statement. The entire expression on the right is evaluated and then added to x before being assigned to x. You can think of the statement as x = x + (3 * 2).
Tap Try It Yourself to play around with the code and experiment with the assignment operators.
Increment & Decrement


Adding 1 to a variable can be done with the increment operator ++. Similarly, the decrement operator -- is used to subtract 1 from a variable.
For example: z--; /* decrement z by 1 */
y++; /* increment y by 1 */
The increment and decrement operators can be used either prefix (before the variable name) or postfix (after the variable name). Which way you use the operator can be important in an assignment statement, as in the following example.
z = 3;
x = z--; /* assign 3 to x, then decrement z to 2 */
y = 3;
x = ++y; /* increment y to 4, then assign 4 to x */
Try It Yourself

The prefix form increments/decrements the variable and then uses it in the assignment statement.
The postfix form uses the value of the variable first, before incrementing/decrementing it.
Tap Try It Yourself to play around with the code and experiment with the increment and assignment operators.





Comments

Popular posts from this blog

Computer Language