programming in c - wordpress.com · few points about switch case 1) case doesn’t always need to...
TRANSCRIPT
Programming in CProf. Vishal Parikh
C Program Structure
• A C program source code can be written in any text editor; however the file should be saved with .c extension. A complete source code demo
/* Demo of a Program */
#include<stdio.h>
int main()
{
int n;
printf(“Enter the number\n”);
scanf(“%d”,&n);
printf(“The value of variable n is %d”, n);
return 0;
}
Lets understand the code:
• Comment: Comment start with’ /*’ and end with ‘*/’. Comments are not mandatory but still it’s a good practice if you use them, it improves the readability of the code. A program can have any number of comments.
• Include section: While writing program we use several keywords & statements such as printf, scanf etc. The file which has definitions of them needs to be included in the program. In the above code we have used stdio.h. There are several libraries and “stdio.h” is one of them, which is used for reading the data from terminal and to display the data on terminal.
• Display statements: printf function has been used in couple of places in the above code. Whatever you gives inside double quotes, it prints as it is at the console.
• Take input from the user: scanf function is used to take the input from the user. When you run this program, it waits for a user input and once user enters the value of n, it does the processing of rest of the statements based on the value of n input by user.
• Main() function: It is the starting point of all the C programs. The execution of C source code begins with this function.
More about main() Function in C program
• The main() function should be present in all C programs as your program won’t begin without this function.
• Return type of main() function: The return type for main () function should always be int.
• Why it has a return type and what’s the need of it? The compiler should know whether your program compiled successfully or it has failed. In order to know this it checks the return value of function main(). If return value is 0 then it means that the program is successful otherwise it assumes that there is a problem.
• Structure of main function: Function name is followed by return type. There should be close parenthesis after function name. If there are parameters or arguments then it must be within this parenthesis. The block of code inside braces is function body.
C Keywords – Reserved Words• In C, we have 32 keywords, which have their predefined meaning and
cannot be used as a variable name. These words are also known as “reserved words”. It is good practice to avoid using these keywords as variable name. These are –
Rules For Constructing Variable Name
• Characters Allowed :• Underscore(_)
• Capital Letters ( A – Z )
• Small Letters ( a – z )
• Digits ( 0 – 9 )
• Blanks & Commas are not allowed
• No Special Symbols other than underscore(_) are allowed
• First Character should be alphabet or Underscore
• Variable name Should not be Reserved Word
• num
• Num
• Num1
• _NUM
• NUM_temp2
• number 1
• num 1
• addition of program
• num_1
• number_of_values
• status_flag
• 1num
• 1_num
• 365_days
Escape Sequences
• Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape sequence is used.
• For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the characters are interpreted by the compiler.
• Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
\0 Null character
Order of Operations : BODMAS
• In mathematics and computer programming, the order of operations (or operator precedence) is a collection of rules that define which procedures to perform first in order to evaluate a given mathematical expression.
• The original order of operations in some countries was BODMAS, which stands for Brackets, Orders or pOwers, Division, Multiplication, Addition, Subtraction. The O is sometimes associated with Of. This mnemonic was common until exponentials were added into the mnemonic.
• For example, in mathematics and most computer languages, multiplication precedes addition.[1] Thus, in the expression 2 + 3 × 4, the answer is 14, not 20. Brackets, ( and ), { and }, or [ and ] — which have their own rules — can indicate an alternate order or reinforce the default order to avoid confusion, thus the preceding expression could be changed to (2 + 3) × 4 to produce 20, or 2 + (3 × 4) to produce 14 (the default if there are no brackets).
1 () [] -> . :: Function call, scope, array/member access
2 ! ~ - + * & sizeof type cast ++ --
(most) unary operators, sizeof and type casts
(right to left)
3 * / % MOD Multiplication, division, modulo
4 + - Addition and subtraction
5 << >> Bitwise shift left and right
6 < <= > >= Comparisons: less-than, ...
7 == != Comparisons: equal and not equal
8 & Bitwise AND
9 ^ Bitwise exclusive OR (XOR)
10 | Bitwise inclusive (normal) OR
11 && Logical AND
12 || Logical OR
13 ? : Conditional expression (ternary)
14= += -= *= /= %= &= |= =̂ <<=
>>=Assignment operators (right to left)
15 , Comma operator
if statement
if (condition)
{
//Block of C statements here
//The above statements will only execute if the condition is true
}
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
#include <stdio.h>
int main()
{
int x, y;
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y");
}
printf("Hi, I'm out of all try blocks");
return 0;
}
if-else statement
if (condition)
{
/*Control will come inside only when the above condition is true*/
//C statement(s)
}
else
{
/*Control will come inside only when condition is false */
//C statement(s)
}
if-else statement
int age;
printf("Input your age:");
scanf("%d",&age);
if(age >=18)
{
printf("you can vote");
}
else
{
printf("you are not eligible for voting");
}
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
//Below – if-else is nested inside another if block
if (var1 >var2)
{
printf("var1 is greater than var2");
}
else
{
printf("var2 is greater than var1");
}
}
else
{
printf("var1 is equal to var2");
}
Nested if else statement
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
}
else if (var1 >var2)
{
printf("var1 is greater than var2");
}
else if (var2 > var1)
{
printf("var2 is greater than var1");
}
else
{
printf("var1 is equal to var2");
}
switch-case Statement
• Switch case statements mostly used when we have number of options (or choices) and we may need to perform a different task for each choice.
Structure of switch case would look like this
switch (variable or an integer expression)
{
case constant:
//C code
;
case constant:
//C code
;
default:
//C code
;
}
Actual code will look like thisint main()
{
int num=2;
switch(num+2)
{
case 1:
printf("Case1: Value is: %d", num);
case 2:
printf("Case1: Value is: %d", num);
case 3:
printf("Case1: Value is: %d", num);
default:
printf("Default: Value is: %d", num);
}
return 0;
}
Output: Value is : 2
Explanation:
• In switch I gave an expression, you can give variable also.
• I gave num+2, where num value is 2 and after addition the expression resulted 4.
• Since there is no case defined with value 4 the default case got executed.
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
case 2:
printf("Case2 ");
case 3:
printf("Case3 ");
case 4:
printf("Case4 ");
default:
printf("Default ");
}
return 0;
}
break statement
• Break statements are useful when you want your program-flow to come out of the switch body. Whenever a break statement is encountered in the switch body, the execution flow would directly come out of the switch.
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0;
}
Few points about Switch Case
1) Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order as per the need of the program.
2) You can also use characters in switch case.
int main()
{
char ch='b';
switch (ch)
{
case 'd':
printf("CaseD ");
break;
case 'b':
printf("CaseB");
break;
case 'c':
printf("CaseC");
break;
case 'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
return 0;
}
3) The expression provided in the switch should result in a constant value otherwise it would not be valid.
Valid expressions for switch –
switch(1+2+23)
switch(1*2+3%4)
Invalid switch expressions –
switch(ab+cd)
switch(a+b+c)
4) Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.
Counter Controlled and Sentinel Controlled Loop
Looping Example:
Based on the nature of the control variables and the kind of value assigned to, the loops may be classified into two general categories; counter controlled and sentinel controlled loops.
Counter controlled loops
• The type of loops, where the number of the execution is known in advance are termed by the counter controlled loop.
• That means, in this case, the value of the variable which controls the execution of the loop is previously known.
• The control variable is known as counter.
• A counter controlled loop is also called definite repetition loop.
• Example: A while loop is an example of counter controlled loop.
sum = 0;
n = 1;
while (n <= 10)
{
sum = sum + n*n;
n = n+ 1;
}
Sentinel controlled loop
• The type of loop where the number of execution of the loop is unknown, is termed by sentinel controlled loop.
• In this case, the value of the control variable differs within a limitation and the execution can be terminated at any moment as the value of the variable is not controlled by the loop.
• The control variable in this case is termed by sentinel variable.
• Example: The following do....while loop is an example of sentinel controlled loop.
do
{
printf(“Input a number.\n”);
scanf("%d", &num);
}
while(num>0);
while loop in C programming with example
• This loop is generally used for performing a same task, a fixed number of times.
• Syntax:
while (condition test)
{
// C- statements, which requires repetition.
// Increment (++) or Decrement (--) Operation.
}
main()
{
int count=1;
while (count <=4)
{
printf("%d ", count);
count++;
}
}
Output: 1 2 3 4
• Step1: first counter variable count got initialized with value 1 and then it has been tested for the condition.
• Step2: If condition holds true then the body of the while loop gets executed otherwise control come out of the loop.
• Step3: count value got incremented using ++ operator then it has been tested again for the loop condition. It keeps happening until the condition returns false.
do while loop in C programming with example
Difference between while and do-while loop?
• do-while loop is similar to while loop, however there is one basic difference between them – do-while runs at least once even if the test condition is false at first place.
With while loop
main()
{
int i=0
while(i==1)
{
printf("while vs do-while");
}
printf("Out of loop");
}
Output : Out of loop
do-while loopmain()
{
int i=0
do
{
printf("while vs do-while\n");
}while(i==1);
printf("Out of loop");
}
Output : while vs do-while
Out of loop
for loop in C programming with example
for (initialization; condition test; increment or decrement)
{
//Code – C statements needs to be repeated
}
Example:
int i;
for (i=1; i<=3; i++)
{
printf("hello, World");
}
• Step 1: first initialization happens and the counter variable gets initialized, here variable is I, which has been assigned by value 1.
• Step 2: then condition checks happen, where variable has been tested for a given condition, if the condition results in true then C statements enclosed in loop body gets executed by compiler, otherwise control skips the loop and continue with the next statement following loop.
• Step 3: After successful execution of loop’s body, the counter variable is incremented or decremented, depending on the operation (++ or –).
Various forms of for loop
1) Here instead of num++, I’m using num=num+1 which is nothing but same as num++.
for (num=10; num<20; num=num+1)
2) Initialization part can be skipped from loop as shown below, the counter variable is declared before the loop itself.
int num=10;
for (;num<20;num++)
Must Note: Although we can skip init part but semicolon (;) before condition is must, without which you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case semicolon (;) is must, after condition logic. The increment part is being done in for loop body itself.
for (num=10; num<20; )
{
//Code
num++;
}
4) Below case is also possible, increment in body and init during declaration of counter variable.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) Counter can be decremented also, In the below example the variable gets decremented each time the loop runs until the condition num>10 becomes false.
for(num=20; num>10; num--)
Nested For Loops
main()
{
for (int i=0; i<=10; i++)
{
for (int j=0; j<=10; j++)
{
printf("%d, %d",i ,j);
}
}
}
Multiple initialization inside for Loop
• for (i=1,j=1;i<10 && j<10; i++, j++)
continue statement in C with example
• Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current iteration.
• Syntax:
continue;
Example:
for (int j=0; j<=8; j++)
{
if (j==4)
{
continue;
}
printf("%d ", j);
}
Output: 0 1 2 3 5 6 7 8
• Value 4 is missing in the output, why?
• When j’s value is 4, the program encountered a continue statement, which makes it to jump at the beginning of for loop for next iteration, skipping the statements for current iteration (that’s the reason printfdidn’t execute when j is equal to 4).
int counter=10;
while (counter >=0)
{
if (counter==7)
{
counter--;
continue;
}
printf("%d ", counter);
counter--;
}
Output: 10 9 8 6 5 4 3 2 1 0
#include <stdio.h>
int main()
{
int j=0;
do
{
if (j==7)
{
j++;
continue;
}
printf("\nvalue of j: %d", j);
j++;
}while(j<10);
return 0;
}
Output
• value of j: 0
• value of j: 1
• value of j: 2
• value of j: 3
• value of j: 4
• value of j: 5
• value of j: 6
• value of j: 8
• value of j: 9
break statement
The break statement in C programming has the following two usages
1. When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax: break;
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}
return 0;
}
Output :
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Dry Run
• A Dry Run (or a practice run) is a testing process where the effects of a possible failure are intentionally mitigated.
• E.g. An Aerospace company may conduct a dry run test of a jet’s new pilot ejection seat, while the jet is parked on the ground, rather than while it is in flight.
• In C programming, a dry run is a mental run of a computer program where the computer programmer examines the source code one step at a time and determines what it will do when run.
• The dry run is frequently assisted by a table with the program or algorithm variables on the top.