C language
basic Concept
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;
}
int main() {
char a = getchar();
printf("You entered: %c", a);
return 0;
}
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;
int main() {
char a[100];
gets(a);
printf("You entered: %s", a);
return 0;
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;
int main() {
int a;
scanf("%d", &a);
printf("You entered: %d", a);
return 0;
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;
}
int main() {
int a, b;
printf("Enter two numbers:");
scanf("%d %d", &a, &b);
printf("\nSum: %d", a+b);
return 0;
}
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);
float num;
char text[20];
scanf("%d %f %s", &x, &num, text);
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 stringbecause 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 */
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 */
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!" */
/* The tree has 22 apples. */
printf("\"Hello World!\"\n");
/* "Hello World!" */
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.
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. */
/* 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. */
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 effect 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;
}
/* A simple C program
* Version 1.0
*/
int main() {
/* Output a string */
printf("Hello World!");
return 0;
}
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;
}
int main() {
int x = 42; //int for a whole number
//%d is replaced by x
printf("%d", x);
return 0;
}
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;
}
int main() {
int length = 10;
int width = 5;
int area;
area = length * width;
printf("%d \n", area); /* 50 */
return 0;
}
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;
}
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;
}
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;
}
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;
}
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.
Type
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:
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 */
int total = 23;
int count = 4;
average = (float) total / count;
/* average = 5.75 */
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 */
x = x + 1; /* x is now 4 */
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 */
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.
Conditionals
Conditionals are used to perform different computations or actions depending on whether a condition evaluates to true or false.
The if Statement
The if statement is called a conditional control structure because it executes statements when an expression is true. For this reason, the if is also known as a decision structure. It takes the form:if (expression)
statements
Relational
Operators
There are six relational operators that can be used to form a Boolean expression, which returns true or false:
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
For example:
int num = 41;
num += 1;
if (num == 42) {
printf("You won!");
}
num += 1;
if (num == 42) {
printf("You won!");
}
The
if-else Statement
The if statement can include an optional else clause that executes statements when an expression is false.
For example, the following program evaluates the expression and then executes the else clause statement
No comments:
Post a Comment