0% found this document useful (0 votes)
15 views27 pages

My Note

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views27 pages

My Note

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Key words for C

C Keywords

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

Constants
If you want to define a variable whose value cannot be changed, you can use
the const keyword. This will create a constant. For example,

const double PI = 3.14;

Basic types
Here's a table containing commonly used types in C programming for quick
access.
Type Size (bytes) Format Specifier

int at least 2, usually 4 %d , %i

char 1 %c

float 4 %f

double 8 %lf

short int 2 usually %hd

unsigned int at least 2, usually 4 %u

long int at least 4, usually 8 %ld , %li

long long int at least 8 %lld , %lli

unsigned long int at least 4 %lu

unsigned long long int at least 8 %llu

signed char 1 %c

unsigned char 1 %c

long double at least 10, usually 12 or 16 %Lf

C Output
In C programming, printf() is one of the main output function. The function
sends formatted output to the screen. For example,
Example 1: C Output
#include <stdio.h>
int main()
{
// Displays the string inside quotations
printf("C Programming");
return 0;
}

Output

C Programming

How does this program work?

 All valid C programs must contain the main() function. The code execution
begins from the start of the main() function.
 The printf() is a library function to send formatted output to the screen. The
function prints the string inside quotations.
 To use printf() in our program, we need to include stdio.h header file using
the #include <stdio.h> statement.
 The return 0; statement inside the main() function is the "Exit status" of the
program. It's optional.
Example 8: ASCII Value
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);

// When %c is used, a character is displayed


printf("You entered %c.\n",chr);

// When %d is used, ASCII value is displayed


printf("ASCII value is %d.", chr);
return 0;
}

Output

Enter a character: g
You entered g.
ASCII value is 103.

Here's a list of commonly used C data types and their format specifiers.

Data Type Format Specifier

int %d

char %c

float %f

double %lf

short int %hd

unsigned int %u
Data Type Format Specifier

long int %li

long long int %lli

unsigned long int %lu

unsigned long long int %llu

signed char %c

unsigned char %c

long double %Lf

C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and
variables).

Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division (modulo division)


C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
C Relational Operators

A relational operator checks the relationship between two operands. If the


relation is true, it returns 1; if the relation is false, it returns value 0.

Relational operators are used in decision making and loops.


Operator Meaning of Operator Example

== Equal to 5 == 3 is evaluated to 0

> Greater than 5 > 3 is evaluated to 1

< Less than 5 < 3 is evaluated to 0

!= Not equal to 5 != 3 is evaluated to 1

>= Greater than or equal to 5 >= 3 is evaluated to 1

<= Less than or equal to 5 <= 3 is evaluated to 0

C Logical Operators

An expression containing logical operator returns either 0 or 1 depending


upon whether expression results true or false. Logical operators are
commonly used in decision making in C programming.

Operator Meaning Example

&& Logical AND. True only if all If c = 5 and d = 2 then, expression ((c==5)
Operator Meaning Example

operands are true && (d>5)) equals to 0.

Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c==5)
||
operand is true || (d>5)) equals to 1.

Logical NOT. True only if the If c = 5 then, expression !(c==5) equals to


!
operand is 0 0.

Example 6: sizeof Operator


#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));

return 0;
}

Output

Size of int = 4 bytes


Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
C if Statement
The syntax of the if statement in C programming is:

if (test expression)
{
// code
}

Example 1: if statement
// Program to display a number if it is negative

#include <stdio.h>
int main() {
int number;

printf("Enter an integer: ");


scanf("%d", &number);

// true if number is less than 0


if (number < 0) {
printf("You entered %d.\n", number);
}

printf("The if statement is easy.");

return 0;
}

Output 1

Enter an integer: -2
You entered -2.
The if statement is easy.

Output 2

Enter an integer: 5
The if statement is easy.
C if...else Statement
The if statement may have an optional else block. The syntax of
the if..else statement is:

if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}

Example 2: if...else statement


// Check whether an integer is odd or even

#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// True if the remainder is 0


if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}

return 0;
}

Output

Enter an integer: 7
7 is an odd integer.
C if...else Ladder
The if...else statement executes two different codes depending upon
whether the test expression is true or false. Sometimes, a choice has to be
made from more than 2 possibilities.
The if...else ladder allows you to check between multiple test expressions and
execute different statements.

Syntax of if...else Ladder

if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}
Example 3: C if...else Ladder
// Program to relate two integers using =, > or < symbol

#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if the two integers are equal.


if(number1 == number2) {
printf("Result: %d = %d",number1,number2);
}

//checks if number1 is greater than number2.


else if (number1 > number2) {
printf("Result: %d > %d", number1, number2);
}

//checks if both test expressions are false


else {
printf("Result: %d < %d",number1, number2);
}

return 0;
}

Output

Enter two integers: 12


23
Result: 12 < 23
Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.

Example 4: Nested if...else

This program given below relates two integers using either < , > and = similar
to the if...else ladder's example. However, we will use a
nested if...else statement to solve this problem.

#include <stdio.h>
int main() {
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

if (number1 >= number2) {


if (number1 == number2) {
printf("Result: %d = %d",number1,number2);
}
else {
printf("Result: %d > %d", number1, number2);
}
}
else {
printf("Result: %d < %d",number1, number2);
}

return 0;
}
If the body of an if...else statement has only one statement, you do not
need to use brackets {} .

For example, this code

if (a > b) {
printf("Hello");
}
printf("Hi");

is equivalent to

if (a > b)
printf("Hello");
printf("Hi");

for Loop
The syntax of the for loop is:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

How for loop works?

 The initialization statement is executed only once.

 Then, the test expression is evaluated. If the test expression is evaluated to


false, the for loop is terminated.
 However, if the test expression is evaluated to true, statements inside the
body of the for loop are executed, and the update expression is updated.
 Again the test expression is evaluated.
This process goes on until the test expression is false. When the test
expression is false, the loop terminates.

To learn more about test expression (when the test expression is evaluated to
true and false), check out relational and logical operators.

Example 2: for loop


// Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers

#include <stdio.h>
int main()
{
int num, count, sum = 0;

printf("Enter a positive integer: ");


scanf("%d", &num);

// for loop terminates when num is less than count


for(count = 1; count <= num; ++count)
{
sum += count;
}

printf("Sum = %d", sum);

return 0;
}

Output

Enter a positive integer: 10


Sum = 55
while loop
The syntax of the while loop is:

while (testExpression) {
// the body of the loop
}

How while loop works?

 The while loop evaluates the testExpression inside the parentheses () .

 If testExpression is true, statements inside the body of while loop are


executed. Then, testExpression is evaluated again.
 The process goes on until testExpression is evaluated to false.
 If testExpression is false, the loop terminates (ends).
To learn more about test expressions (when testExpression is evaluated
to true and false), check out relational and logical operators.

Example 1: while loop


// Print numbers from 1 to 5

#include <stdio.h>
int main() {
int i = 1;

while (i <= 5) {
printf("%d\n", i);
++i;
}

return 0;
}
Output

1
2
3
4
5

do...while loop
The do..while loop is similar to the while loop with one important difference.
The body of do...while loop is executed at least once. Only then, the test
expression is evaluated.
The syntax of the do...while loop is:

do {
// the body of the loop
}
while (testExpression);

How do...while loop works?

 The body of do...while loop is executed once. Only then,


the testExpression is evaluated.
 If testExpression is true, the body of the loop is executed
again and testExpression is evaluated once more.
 This process goes on until testExpression becomes false.
 If testExpression is false, the loop ends.
Example 2: do...while loop
// Program to add numbers until the user enters zero

#include <stdio.h>
int main() {
double number, sum = 0;

// the body of the loop is executed at least once


do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

printf("Sum = %.2lf",sum);

return 0;
}
Run Code

Output

Enter a number: 1.5


Enter a number: 2.4
Enter a number: -3.4
Enter a number: 4.2
Enter a number: 0
Sum = 4.70

Here, we have used a do...while loop to prompt the user to enter a number.
The loop works as long as the input number is not 0 .
The do...while loop executes at least once i.e. the first iteration runs without
checking the condition. The condition is checked only after the first iteration
has been executed.
do {
printf("Enter a number: ");
scanf("%lf", &number);
sum += number;
}
while(number != 0.0);

So, if the first input is a non-zero number, that number is added to


the sum variable and the loop continues to the next iteration. This process is
repeated until the user enters 0 .
But if the first input is 0, there will be no second iteration of the loop
and sum becomes 0.0 .

Outside the loop, we print the value of sum .

C break
The break statement ends the loop immediately when it is encountered. Its
syntax is:

break;

The break statement is almost always used with if...else statement inside
the loop.
Example 1: break statement
// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, the loop terminates

#include <stdio.h>

int main() {
int i;
double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


printf("Enter n%d: ", i);
scanf("%lf", &number);

// if the user enters a negative number, break the loop


if (number < 0.0) {
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}
Run Code

Output

Enter n1: 2.4


Enter n2: 4.5
Enter n3: 3.4
Enter n4: -3
Sum = 10.30
In C, break is also used with the switch statement. This will be discussed in
the next tutorial.

C continue
The continue statement skips the current iteration of the loop and continues
with the next iteration. Its syntax is:

continue;

The continue statement is almost always used with the if...else statement.

Example 2: continue statement


// Program to calculate the sum of numbers (10 numbers max)
// If the user enters a negative number, it's not added to the result

#include <stdio.h>
int main() {
int i;
double number, sum = 0.0;

for (i = 1; i <= 10; ++i) {


printf("Enter a n%d: ", i);
scanf("%lf", &number);

if (number < 0.0) {


continue;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf", sum);

return 0;
}

Output
Enter n1: 1.1
Enter n2: 2.2
Enter n3: 5.5
Enter n4: 4.4
Enter n5: -3.4
Enter n6: -45.5
Enter n7: 34.5
Enter n8: -4.2
Enter n9: -1000
Enter n10: 12
Sum = 59.70

In this program, when the user enters a positive number, the sum is calculated
using sum += number; statement.
When the user enters a negative number, the continue statement is executed
and it skips the negative number from the calculation.

C switch Statement
In this tutorial, you will learn to create the switch statement in C programming
with the help of an example.

The switch statement allows us to execute one code block among many
alternatives.

You can do the same thing with the if...else..if ladder. However, the
syntax of the switch statement is much easier to read and write.
Syntax of switch...case

switch (expression)
{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
}

How does the switch statement work?


The expression is evaluated once and compared with the values of
each case label.
 If there is a match, the corresponding statements after the matching label are
executed. For example, if the value of the expression is equal to constant2 ,

statements after case constant2: are executed until break is encountered.


 If there is no match, the default statements are executed.

Notes:
 If we do not use the break statement, all statements after the matching label
are also executed.
 The default clause inside the switch statement is optional.
Example: Simple Calculator
// Program to create a simple calculator
#include <stdio.h>

int main() {
char operation;
double n1, n2;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operation);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);

switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;

// operator doesn't match any case constant +, -, *, /


default:
printf("Error! operator is not correct");
}

return 0;
}

Output

Enter an operator (+, -, *, /): -


Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1

The - operator entered by the user is stored in the operation variable. And,
two operands 32.5 and 12.4 are stored in variables n1 and n2 respectively.
Since the operation is - , the control of the program jumps to

printf("%.1lf - %.1lf = %.1lf", n1, n2, n1-n2);

Finally, the break statement terminates the switch statement.

C goto Statement
In this tutorial, you will learn to create the goto statement in C programming.
Also, you will learn when to use a goto statement and when not to use it.

The goto statement allows us to transfer control of the program to the


specified label .
Syntax of goto Statement

goto label;
... .. ...
... .. ...
label:
statement;

The label is an identifier. When the goto statement is encountered, the


control of the program jumps to label: and starts executing the code.

Example: goto Statement


// Program to calculate the sum and average of positive numbers
// If the user enters a negative number, the sum and average are
displayed.

#include <stdio.h>

int main() {

const int maxInput = 100;


int i;
double number, average, sum = 0.0;

for (i = 1; i <= maxInput; ++i) {


printf("%d. Enter a number: ", i);
scanf("%lf", &number);

// go to jump if the user enters a negative number


if (number < 0.0) {
goto jump;
}
sum += number;
}

jump:
average = sum / (i - 1);
printf("Sum = %.2f\n", sum);
printf("Average = %.2f", average);
return 0;
}

Output

1. Enter a number: 3
2. Enter a number: 4.3
3. Enter a number: 9.3
4. Enter a number: -2.9
Sum = 16.60
Average = 5.53

You might also like