-
Notifications
You must be signed in to change notification settings - Fork 0
/
c programming notes.txt
3137 lines (2403 loc) · 109 KB
/
c programming notes.txt
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=============================
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.
=============================
=============================
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.
=============================
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.
=============================
=============================
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: %ld \n", sizeof(int));
printf("float: %ld \n", sizeof(float));
printf("double: %ld \n", sizeof(double));
printf("char: %ld \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 (%ld), while the next argument returns the sizeof value. In the final output, the %ld (for long 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.
=============================
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.
=============================
=============================
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().
=============================
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().
=============================
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 */
=============================
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.
=============================
=============================
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.
=============================
=============================
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;
}
=============================
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
printf("%d \n", result);
result = a + b / c; // 8
printf("%d \n", result);
result = (a + b) / c; // 5
printf("%d \n", result);
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 or as x * (y * z). If order is important, break the expression into separate statements.
=============================
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:
#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.
=============================
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).
=============================
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.
=============================
=============================
=============================
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
The expression evaluates to either true or false, and statements can be a single statement or a code block enclosed by curly braces { }.
For example:
#include <stdio.h>
int main() {
int score = 89;
if (score > 75)
printf("You passed.\n");
return 0;
}
Try It Yourself
In the code above we check whether the score variable is greater than 75, and print a message if the condition is true.
=============================
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!");
}
Try It Yourself
An expression that evaluates to a non-zero value is considered true.
For example:
int in_stock = 20;
if (in_stock)
printf("Order received.\n");
=============================
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:
#include <stdio.h>
int main() {
int score = 89;
if (score >= 90)
printf("Top 10%%.\n");
else
printf("Less than 90.\n");
return 0;
}
=============================
Conditional Expressions
Another way to form an if-else statement is by using the ?: operator in a conditional expression. The ?: operator can have only one statement associated with the if and the else.
For example:
#include <stdio.h>
int main() {
int y;
int x = 3;
y = (x >= 5) ? 5 : x;
/* This is equivalent to:
if (x >= 5)
y = 5;
else
y = x;
*/
return 0;
}
=============================
=============================
Nested if Statements
An if statement can include another if statement to form a nested statement. Nesting an if allows a decision to be based on further requirements.
Consider the following statement:
if (profit > 1000)
if (clients > 15)
bonus = 100;
else
bonus = 25;
Try It Yourself
Appropriately indenting nested statements will help clarify the meaning to a reader. However, be sure to understand that an else clause is associated with the closest if unless curly braces { } are used to change the association.
For example:
if (profit > 1000) {
if (clients > 15)
bonus = 100;
}
else
bonus = 25;
=============================
The if-else if Statement
When a decision among three or more actions is needed, the if-else if statement can be used.
There can be multiple else if clauses and the last else clause is optional.
For example:
int score = 89;
if (score >= 90)
printf("%s", "Top 10%\n");
else if (score >= 80)
printf("%s", "Top 20%\n");
else if (score > 75)
printf("%s", "You passed.\n");
else
printf("%s", "You did not pass.\n");
Try It Yourself
Carefully consider the logic involved when developing an if-else if statement. Program flow branches to the statements associated with the first true expression and none of the remaining expressions will be tested.
Although indents won't affect the compiled code, the logic of the if-else if will be easier to understand by a reader when the else clauses are aligned.
When possible, an if-else if statement is preferred over nested if statements for clarity.
=============================
=============================
The switch Statement
The switch statement branches program control by matching the result of an expression with a constant case value.
The switch statement often provides a more elegant solution to if-else if and nested if statements.
The switch takes the form: switch (expression) {
case val1:
statements
break;
case val2:
statements
break;
default:
statements
}
For example, the following program outputs "Three":
int num = 3;
switch (num) {
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
case 3:
printf("Three\n");
break;
default:
printf("Not 1, 2, or 3.\n");
}
=============================
The switch Statement
There can be multiple cases with unique labels.
The optional default case is executed when no other matches are made.
A break statement is needed in each case to branch to the end of the switch statement.
Without the break statement, program execution falls through to the next case statement. This can be useful when the same statement is needed for several cases. Consider the following switch statement:
switch (num) {
case 1:
case 2:
case 3:
printf("One, Two, or Three.\n");
break;
case 4:
case 5:
case 6:
printf("Four, Five, or Six.\n");
break;
default:
printf("Greater than Six.\n");
}
Try It Yourself
Caution must be used when constructing the switch this way. Modifications later can lead to unexpected outcomes.
=============================
=============================
Logical Operators
Logical operators && and || are used to form a compound Boolean expression that tests multiple conditions. A third logical operator is ! used to reverse the state of a Boolean expression.
The && Operator
The logical AND operator && returns a true result only when both expressions are true.
For example:
if (n > 0 && n <= 100)
printf("Range (1 - 100).\n");
Try It Yourself
The statement above joins just two expressions, but logical operators can be used to join multiple expressions.
A compound Boolean expression is evaluated from left to right. Evaluation stops when no further test is needed for determining the result, so be sure to consider the arrangement of operands when one result affects the outcome of a later result.
=============================
The || Operator
The logical OR operator || returns a true result when any one expression or both expressions are true.
For example:
if (n == 'x' || n == 'X')
printf("Roman numeral value 10.\n");
Try It Yourself
Any number of expressions can be joined by && and ||.
For example:
if (n == 999 || (n > 0 && n <= 100))
printf("Input valid.\n");
Try It Yourself
Parentheses are used for clarity even though && has higher precedence than || and will be evaluated first.
=============================
The ! Operator
The logical NOT operator ! returns the reverse of its value.
NOT true returns false, and NOT false returns true.
For example:
if (!(n == 'x' || n == 'X'))
printf("Roman numeral is not 10.\n");
Try It Yourself
In C, any non-zero value is considered true and a 0 is false. The logical NOT operator therefore, converts a true value to 0 and a false value to 1.
=============================
=============================
The while Loop
The while statement is called a loop structure because it executes statements repeatedly while an expression is true, looping over and over again. It takes the form: while (expression) {
statements
}
The expression evaluates to either true or false, and statements can be a single statement or, more commonly, a code block enclosed by curly braces { }.
For example:
#include <stdio.h>
int main() {
int count = 1;
while (count < 8) {
printf("Count = %d\n", count);
count++;
}
return 0;
}
Try It Yourself
The code above will output the count variable 7 times.
The while loop evaluates a condition before the loop is entered, making it possible that the while statements never execute.
An infinite loop is one that continues indefinitely because the loop condition never evaluates to false. This may cause a run-time error.
=============================
The do-while Loop
The do-while loop executes the loop statements before evaluating the expression to determine if the loop should be repeated.
It takes the form: do {
statements
} while (expression);
The expression evaluates to either true or false, and statements can be a single statement or a code block enclosed by curly braces { }.
For example:
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Count = %d\n", count);
count++;
} while (count < 8);
return 0;
}
Try It Yourself
Note the semicolon after the while statement.
The do-while loop always executes at least once, even if the expression evaluates to false.
=============================
break and continue
The break statement was introduced for use in the switch statement. It is also useful for immediately exiting a loop.
For example, the following program uses a break to exit a while loop:
int num = 5;
while (num > 0) {
if (num == 3)
break;
printf("%d\n", num);
num--;
}
Try It Yourself
This program displays:
5
4
and then exits the loop.
When you want to remain in the loop, but skip ahead to the next iteration, you use the continue statement.
For example:
int num = 5;
while (num > 0) {
num--;
if (num == 3)
continue;
printf("%d\n", num);
}
Try It Yourself
The program output displays:
4
2
1
0
As you can see, the value 3 is skipped.
In the code above, if num was decremented after the continue statement an infinite loop would be created.
Although the break and continue statements can be convenient, they should not be a substitute for a better algorithm.
=============================
=============================
The for Loop
The for statement is a loop structure that executes statements a fixed number of times.
It takes the form: for (initvalue; condition; increment) {
statements;
}
The initvalue is a counter set to an initial value. This part of the for loop is performed only once.
The condition is a Boolean expression that compares the counter to a value before each loop iteration, stopping the loop when false is returned.
The increment increases (or decreases) the counter by a set value.
For example, the program below displays 0 through 9:
int i;
int max = 10;
for (i = 0; i < max; i++) {
printf("%d\n", i);
}
=============================
The for Loop
The for loop can contain multiple expressions separated by commas in each part.
For example:for (x = 0, y = num; x < y; i++, y--) {
statements;
}
Also, you can skip the initvalue, condition and/or increment.
For example:
int i=0;
int max = 10;
for (; i < max; i++) {
printf("%d\n", i);
}
Try It Yourself
Loops can also be nested.
When writing a program this way, there is an outer loop and an inner loop. For each iteration of the outer loop the inner loop repeats its entire cycle.
In the following example, nested for loops are used to output a multiplication table:
int i, j;
int table = 10;
int max = 12;
for (i = 1; i <= table; i++) {
for (j = 0; j <= max; j++) {
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}
Try It Yourself
A break in an inner loop exits that loop and execution continues with the outer loop.
A continue statement works similarly in nested loops.
{ For Loop: Initializer, Condition, Modifier }
=============================
=============================
=============================
Functions in C
Functions are central to C programming and are used to accomplish a program solution as a series of subtasks.
By now you know that every C program contains a main() function. And you're familiar with the printf() function.
You can also create your own functions.
A function:
• is a block of code that performs a specific task
• is reusable
• makes a program easier to test
• can be modified without changing the calling program
Even a simple program is easier to understand when main() is broken down into subtasks that are implemented with functions.
For example, it's clear that the goal of this program is to calculate the square of a number: int main() {
int x, result;
x = 5;
result = square(x);
printf("%d squared is %d\n", x, result);
return 0;
}
In order to use the square function, we need to declare it.
Declarations usually appear above the main() function and take the form: return_type function_name(parameters);
The return_type is the type of value the function sends back to the calling statement. The function_name is followed by parentheses. Optional parameter names with type declarations are placed inside the parentheses.
A function is not required to return a value, but a return type must still be in the declaration. In this case, the keyword void is used.
For example, the display_message function declaration indicates the function does not return a value: void display_message();
=============================
Functions in C