KEMBAR78
Input & Output: Int Void | PDF | Parameter (Computer Programming) | Integer (Computer Science)
0% found this document useful (0 votes)
29 views27 pages

Input & Output: Int Void

The document provides an overview of C programming concepts, focusing on input/output functions, variable declaration, data types, operators, and memory allocation. It explains the use of functions like printf, scanf, and fgets for handling user input and output, as well as the rules for naming and initializing variables. Additionally, it covers various operators including arithmetic, relational, logical, and bitwise operators, along with examples demonstrating their usage.

Uploaded by

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

Input & Output: Int Void

The document provides an overview of C programming concepts, focusing on input/output functions, variable declaration, data types, operators, and memory allocation. It explains the use of functions like printf, scanf, and fgets for handling user input and output, as well as the rules for naming and initializing variables. Additionally, it covers various operators including arithmetic, relational, logical, and bitwise operators, along with examples demonstrating their usage.

Uploaded by

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

.

Input & Output


●​ These functions are part of the standard input/output library <stdio.h>
●​ scanf() takes user inputs (typed using keyboard) and printf() displays output on the console or screen.
●​ arguments passed to printf() that will replace the format specifiers in the formatted string.

1. int main(void)
2. {
3. // This prints "Hello World"
4. printf("Hello World");
5. return 0;
6. }
7.
The structure of the function main() is recommended to use in exams.

You may have also noticed '\n' character. This character is an escape sequence and is used to enter a newline.

Printing Variables Along with String


1. #include <stdio.h>
2. ​
3. int main() {
4. int age = 22;
5.
6. // Prints The value of the variable age is 22
7. printf("The value of the variable age is %d\n", age);
8.
9. return 0;
10. }
11.
fputs()
The fputs() function is used to output strings to the files but we can also use it to print strings to the console screen.

Syntax:

1. 1. fputs("your text here", stdout);


2. 2.
3.
Where, the stdout represents that the text should be printed to console.

Scanf()
scanf() is used to read user input from the console. It takes the format string and the addresses of the variables where the input
will be stored.

Reading an Integer

1. #include <stdio.h>
2.
3. int main() {
4. int age;
5. printf("Enter your age: ");
6.
7. // Reads an integer
8. scanf("%d", &age);
9.
10. // Prints the age
11. printf("Age is: %d\n", age);
12. return 0;
13. }

Output:
Enter your age:

25 (Entered by the user)

Age is: 25

fgets()
fgets() reads the given number of characters of a line from the input and stores it into the specified string. It can read multiple
words at a time.

Syntax

1. fgets(str, n, stdin);
2.
where buff is the string where the input will be stored and n is the maximum number of characters to read. stdin represents
input reading from the keyboard.

Example:

1. #include <stdio.h>
2. #include <string.h>
3. ​
4. int main() {
5.
6. // String variable
7. char name[20];
8.
9. printf("Enter your name: \n");
10. fgets(name, sizeof(name), stdin);
11.
12. printf("Hello, %s", name);
13. return 0;
14. }
15.

Output:
Enter your name:

John (Entered by User)

Hello, John

. Variables
To create a variable in C, we have to specify a name and the type of data it is going to store in the syntax.
1. data_type name;
2. data_type name1, name2, name3, ...;​

Size Format
DataType What it stores Example
(typical) Identifier

int Whole numbers -10, 0, 25 4 bytes %d

float Decimal numbers (low precision) 3.14 4 bytes %f

double Decimal numbers (high precision) 3.14159 8 bytes %lf

char Single character 'A', '9' 1 byte %c

Integer Variants
Type Meaning Range (approx) Format Identifier

short Smaller int −32,768 to 32,767 %hd

long Bigger int −2B to 2B or more %ld

unsigned int Only positive numbers 0 to 4B %u

unsigned char 0–255 %c

What is Format identifier


In C, a format identifier (also called a format specifier) tells printf(), scanf(), and similar functions what kind of data you're
working with.

Rules for Naming Variables in C


We can assign any name to a C variable as long as it follows the following rules:

●​ A variable name must only contain letters, digits, and underscores.


●​ It must start with an alphabet or an underscore only. It cannot start with a digit.
●​ No white space is allowed within the variable name.
●​ A variable name must not be any reserved word or keyword (reserved Words in C that have a specific meaning and
use in the syntax).

●​ The name must be unique in the program.

Variable Initialization
1. int num1;
2. num1 = 3;
3. int num2 = 4;
4.//You can declare variables both ways
5. num2 = 12;
6.//We changed the stored value in num2
Note: It is compulsory that the values assigned to the variables should be of the same data type as specified in the
declaration.
Accessing Variables
The data stored inside a C variable can be easily accessed by using the variable's name.

Example:

1. #include <stdio.h>
2. ​
3. int main() {
4.
5. // Create integer variable
6. int num = 3;
7.
8. // Access the value stored in
9. // variable
10. printf("%d", num);
11. return 0;
12. }
13. //Prints 3

How can you use variable in C

1. #include <stdio.h>
2. int main() {
3.
4. // Expression that uses values
5. int sum1 = 20 + 40;
6.
7. // Defining variables
8. int a = 20, b = 40;
9.
10. // Expression that uses variables
11. int sum2 = a + b;
12.
13. printf("%d\n%d", sum1, sum2);
14. return 0;
15. }
16. //Prints 60 60
Memory Allocation of C Variables
When a variable is declared, the compiler is told that the variable with the given name and type exists in the program. But no
memory is allocated to it yet. Memory is allocated when the variable is defined.

The size of memory assigned for variables depends on the type of variable. We can check the size of the variables using sizeof
operator.

1. #include <stdio.h>
2.
3. int main() {
4. int num = 22;
5.
6. // Finding size of num
7. printf("%d bytes", sizeof(num));
8. return 0;
9. //Prints 4 bytes
10. }
Scope of Variables in C
We have told that a variable can be accessed anywhere once it is declared, but it is partially true. A variable can be accessed
using its name anywhere in a specific region of the program called its scope. It is the region of the program where the name
assigned to the variable is valid.

A scope is generally the area inside the {} curly braces.

Example:

1. // num cannot be accessed here


2.
3. int main() {
4.
5. // num cannot be accessed here
6. {
7. // Variable declaration
8. int num;
9. }
10.
11. // Cannot be accessed here either
12. return 0;
13. }
14.
Constants in C
C also provides some variables whose value cannot be changed. These variables are called constants and are created simply by
prefixing const keyword in variable declaration.

Syntax:

1. const data_type name = value;


Constants must be initialized at the time of declaration.

Type conversion
Type conversion means changing one data type into another.

1.​ Implicit Conversion (Automatic)

●​ Done by the compiler

●​ Happens when mixing types

●​ Smaller type → larger type

Example

1. int x = 5;
2. float y = x; // int to float (done automatically)
3.

2. Explicit Conversion (Casting)

●​ You manually convert a type

●​ Use type name in parentheses

Example
1. float a = 5.7;
2. int b = (int) a; // b = 5 (decimal is removed)
3.

2.​ Operators in C
Example:

1. #include <stdio.h>
2. int main() {
3.
4. // Expression for getting sum
5. int sum = 10 + 20;
6.
7. printf("%d", sum);
8. return 0;
9. }
10. //Prints 30
Unary, Binary and Ternary Operators
On the basis of the number of operands they work on, operators can be classified into three types :

1.​ Unary Operators: Operators that work on single operand.​


Example: Increment( ++) , Decrement(--)

2.​ Binary Operators: Operators that work on two operands.​


Example: Addition (+), Subtraction( -) , Multiplication (*)

3.​ Ternary Operators: Operators that work on three operands.​


Example: Conditional Operator( ? : )

Arithmetic operators

Operator Type Meaning Example Result

+ Arithmetic Addition a+b Sum

- Arithmetic Subtraction a-b Difference

* Arithmetic Multiplication a*b Product

/ Arithmetic Division a/b Quotient

% Arithmetic Modulus (remainder) (int) a%b Remainder

+a Unary Unary plus (usually ignored) +a a

-a Unary Unary minus (negation) -a Negative a

++a Pre-increment Add 1 then use x = ++a; a + 1 → x = a

a++ Post-increment Use then add 1 x = a++; x = a → a + 1

--a Pre-decrement Subtract 1 then use x = --a; a-1→x=a


Operator Type Meaning Example Result

a-- Post-decrement Use then subtract 1 x = a--; x=a→a-1

Example of C Arithmetic Operators

1. #include <stdio.h>
2. ​
3. int main() {
4. ​
5. int a = 25, b = 5;
6. ​
7. // using operators and printing results
8. printf("a + b = %d\n", a + b);
9. printf("a - b = %d\n", a - b);
10. printf("a * b = %d\n", a * b);
11. printf("a / b = %d\n", a / b);
12. printf("a % b = %d\n", a % b);
13. printf("+a = %d\n", +a);
14. printf("-a = %d\n", -a);
15. printf("a++ = %d\n", a++);
16. printf("a-- = %d\n", a--);
17. ​
18. return 0;
19. }
20.

Output:

a + b = 30

a - b = 20

a * b = 125

a/b=5

a%b=0

+a = 25

-a = -25

a++ = 25

a-- = 26

Relational Operators

Operator Meaning Example Result

== Equal to a == b true if equal

!= Not equal to a != b true if not equal

> Greater than a>b true if a > b

< Less than a<b true if a < b


Operator Meaning Example Result

>= Greater than or equal a >= b true if a ≥ b

<= Less than or equal a <= b true if a ≤ b

Example of C Relational Operators

1. #include <stdio.h>
2. ​
3. int main() {
4. int a = 25, b = 5;
5. ​
6. // using operators and printing results
7. printf("a < b : %d\n", a < b);
8. printf("a > b : %d\n", a > b);
9. printf("a <= b: %d\n", a <= b);
10. printf("a >= b: %d\n", a >= b);
11. printf("a == b: %d\n", a == b);
12. printf("a != b : %d\n", a != b);
13. ​
14. return 0;
15. }
16.

Output:
a<b :0

a>b :1

a <= b: 0

a >= b: 1

a == b: 0

a != b : 1

Here, 0 means false and 1 means true.

Logical
Operator Name Description Example

&& Logical AND Returns true if both operands are true a && b

|| Logical OR Returns true if both or any of the operand is true. a||b

! Logical NOT Returns true if the operand is false !a

Example of Logical Operators in C

1. #include <stdio.h>
2. ​
3. int main() {
4. int a = 25, b = 5;
5. ​
6. // using operators and printing results
7. printf("a && b : %d\n", a && b);
8. printf("a || b : %d\n", a || b);
9. printf("!a: %d\n", !a);
10. ​
11. return 0;
12. }
13.

Output:
a && b : 1

a || b : 1

!a: 0

Bitwise operators

Symbol Operator Description Syntax

Performs
bit-by-bit AND
& Bitwise AND operation and a&b
returns the
result.

Performs
bit-by-bit OR
| Bitwise OR operation and a|b
returns the
result.

Performs
bit-by-bit XOR
^ Bitwise XOR operation and a^b
returns the
result.

Flips all the set


Bitwise First
~ and unset bits ~a
Complement
on the number.

Shifts bits to the


left by a given
<< Bitwise Leftshift number of a << b
positions;
multiplies the
Symbol Operator Description Syntax

number by 2 for
each shift.

Shifts bits to the


right by a given
number of
Bitwise
>> positions; a >> b
Rightshilft
divides the
number by 2 for
each shift.

Example of Bitwise Operators

1. #include <stdio.h>
2. ​
3. int main() {
4. int a = 25, b = 5;
5. ​
6. // using operators and printing results
7. printf("a & b: %d\n", a & b);
8. printf("a | b: %d\n", a | b);
9. printf("a ^ b: %d\n", a ^ b);
10. printf("~a: %d\n", ~a);
11. printf("a >> b: %d\n", a >> b);
12. printf("a << b: %d\n", a << b);
13. ​
14. return 0;
15. }
16.

Output:
a & b: 1

a | b: 29

a ^ b: 28

~a: -26

a >> b: 0

a << b: 800

Assignment Operators
Symbol Operator Description Syntax

Assign the value of the


= Simple Assignment right operand to the left a=b
operand.

Add the right operand


and left operand and
+= Plus and assign a += b
assign this value to the
left operand.

Subtract the right


operand and left
-= Minus and assign operand and assign this a -= b
value to the left
operand.

Multiply the right


operand and left
*= Multiply and assign operand and assign this a *= b
value to the left
operand.

Divide the left operand


with the right operand
/= Divide and assign a /= b
and assign this value to
the left operand.

Assign the remainder in


the division of left
%= Modulus and assign operand with the right a %= b
operand to the left
operand.

Performs bitwise AND


&= AND and assign and assigns this value to a &= b
the left operand.
Symbol Operator Description Syntax

Performs bitwise OR and


|= OR and assign assigns this value to the a |= b
left operand.

Performs bitwise XOR


^= XOR and assign and assigns this value to a ^= b
the left operand.

Performs bitwise
Rightshift and assign this
>>= Rightshift and assign a >>= b
value to the left
operand.

Performs bitwise
Leftshift and assign this
<<= Leftshift and assign a <<= b
value to the left
operand.

Example of C Assignment Operators

1. #include <stdio.h>
2. ​
3. int main() {
4. int a = 25, b = 5;
5. ​
6. // using operators and printing results
7. printf("a = b: %d\n", a = b);
8. printf("a += b: %d\n", a += b);
9. printf("a -= b: %d\n", a -= b);
10. printf("a *= b: %d\n", a *= b);
11. printf("a /= b: %d\n", a /= b);
12. printf("a %%= b: %d\n", a %= b);
13. printf("a &= b: %d\n", a &= b);
14. printf("a |= b: %d\n", a |= b);
15. printf("a ^= b: %d\n", a ^= b);
16. printf("a >>= b: %d\n", a >>= b);
17. printf("a <<= b: %d\n", a <<= b);
18. ​
19. return 0;
20. }
21.

Output:

a = b: 5

a += b: 10
a -= b: 5

a *= b: 25

a /= b: 5

a %= b: 0

a &= b: 0

a |= b: 5

a ^= b: 0

a >>= b: 0

a <<= b: 0

4.​ Conditionals
if
Example

1. #include <stdio.h>
2. ​
3. int main() {
4.
5. int i = 10;
6. ​
7. // If statement
8. if (i < 18) {
9. printf("Eligible for vote");
10. }
11. }
12.

Output:
Eligible for vote
if-else
The if-else statement consists of two blocks, one for false expression and one for true expression.
Example

1. #include <stdio.h>
2. ​
3. int main() {
4. int i = 10;
5. ​
6. if (i > 18) {
7. printf("Eligible for vote");
8. }
9. else {
10. printf("Not Eligible for vote");
11. }
12. return 0;
13. }
14.

Output:
Not Eligible for vote
The block of code following the else statement is executed as the condition present in the if statement is false.
Nested if-else
Example

1. #include <stdio.h>
2. ​
3. int main(){
4. int i = 10;
5. ​
6. if (i == 10) {
7. if (i < 18)
8. printf("Still not eligible for vote");
9. else
10. printf("Eligible for vote\n");
11. }
12. else {
13. if (i == 20) {
14. if (i < 22)
15. printf("i is smaller than 22 too\n");
16. else
17. printf("i is greater than 25");
18. }
19. }
20. ​
21. return 0;
22. }
23.

Output:
Still not eligible for vote

1. if-else-if Ladder in C
2. Example
3. #include <stdio.h>
4. ​
5. int main() {
6. int i = 20;
7. ​
8. // If else ladder with three conditions
9. if (i == 10)
10. printf("Not Eligible");
11. else if (i == 15)
12. printf("wait for three years");
13. else if (i == 20)
14. printf("You can vote");
15. else
16. printf("Not a valid age");
17.
18. return 0;
19. }
20.

Output:
You can vote
switch Statement
Example
1. #include <stdio.h>
2. ​
3. int main() {
4.
5. // variable to be used in switch statement
6. int var = 18;
7. ​
8. // declaring switch cases
9. switch (var) {
10. case 15:
11. printf("You are a kid");
12. break;
13. case 18:
14. printf("Eligible for vote");
15. break;
16. default:
17. printf("Default Case is executed");
18. break;
19. }
20. ​
21. return 0;
22. }
23.

Output:
Eligible for vote

Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else statement. It is also
known as the ternary operator as it works on three operands.
Example

1. #include <stdio.h>
2. ​
3. int main() {
4. int var;
5. int flag = 0;
6. ​
7. // using conditional operator to assign the value to var
8. // according to the value of flag
9. var = flag == 0 ? 25 : -25;
10. printf("Value of var when flag is 0: %d\n", var);
11. ​
12. return 0;
13. }
14.

Output:
Value of var when flag is 0: 25

Jump Statements
These statements are used in C for the unconditional flow of control throughout the functions in a program. They
support four types of jump statements:
A) break
This loop control statement is used to terminate the loop. As soon as the break statement is encountered from within
a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the
loop.
Example

1. #include <stdio.h>
2. ​
3. int main() {
4. int arr[] = { 1, 2, 3, 4, 5, 6 };
5. int key = 3;
6. int size = 6;
7. ​
8. for (int i = 0; i < size; i++) {
9. if (arr[i] == key) {
10. printf("Element found at position: %d",
11. (i + 1));
12. break;
13. }
14. }
15. ​
16. return 0;
17. }
18.

Output:
Element found at position: 3
B) continue
This loop control statement is just like the break statement. The continue statement is opposite to that of the
break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. ​
As the name suggests the continue statement forces the loop to continue or execute the next iteration. When the
continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped
and the next iteration of the loop will begin.

Example

1. #include <stdio.h>
2. ​
3. int main() {
4. for (int i = 1; i <= 10; i++) {
5. ​
6. // If i is equals to 6,
7. // continue to next iteration
8. // without printing
9. if (i == 6)
10. continue;
11. else
12. printf("%d ", i);
13. }
14. ​
15. return 0;
16. }
17.

Output
1 2 3 4 5 7 8 9 10

C) goto
The goto statement in C also referred to as the unconditional jump statement can be used to jump from
one point to another within a function.
Examples

1. #include <stdio.h>
2. ​
3. int main() {
4. int n = 1;
5. label:
6. printf("%d ", n);
7. n++;
8. if (n <= 10)
9. goto label;
10. return 0;
11. }
12.

Output
1 2 3 4 5 6 7 8 9 10

D) return
The return in C returns the flow of the execution to the function from where it is called. This statement does not
mandatorily need any conditional statements. As soon as the statement is executed, the flow of the program stops
immediately and returns the control from where it was called. The return statement may or may not return anything
for a void function, but for a non-void function, a return value must be returned.
Example

1. #include <stdio.h>
2. ​
3. int sum(int a, int b) {
4. int s1 = a + b;
5. return s1;
6. }
7. ​
8. int main()
9. {
10. int num1 = 10;
11. int num2 = 10;
12. int sumOf = sum(num1, num2);
13. printf("%d", sumOf);
14. return 0;
15. }
16.

Output:
20
5.​ Loops
while Loop
Example

1. #include <stdio.h>
2. int main() {
3.
4. // Initialization expression
5. int i = 0;
6.
7. // Test expression
8. while(i <= 5) {
9. printf("%d ", i + 1);
10.
11. // update expression
12. i++;
13. }
14.
15. return 0;
16. }
17.

Output:
123456
for Loop
Example

1. #include <stdio.h>
2. ​
3. int main() {
4.
5. // Loop to print numbers from 1 to 5
6. for (int i = 0; i < 5; i++) {
7. printf( "%d ", i + 1);
8. }
9.
10. return 0;
11. }
12.

Output:
12345
do-while Loop
The do-while loop is an exit-controlled loop, which means that the condition is checked after executing the loop body.
Due to this, the loop body will execute at least once irrespective of the test condition.
Example:

1. #include <stdio.h>
2.
3. int main() {
4.
5. // Initialization expression
6. int i = 0;
7.
8. do
9. {
10. // loop body
11. printf( "%d ", i);
12.
13. // Update expression
14. i++;
15.
16. // Condition to check
17. } while (i <= 10);
18.
19. return 0;
20. }
21.

Output:
0 1 2 3 4 5 6 7 8 9 10

Infinite Loop

1. #include <stdio.h>
2.
3. int main () {
4.
5. ​ // This is an infinite for loop
6. ​ // as the condition expression
7. ​ // is blank
8. ​ for ( ; ; ) {
9. ​ ​ printf("This loop will run forever.");
10. ​ }
11. ​ return 0;
12. }
13.
Output:
This loop will run forever.​
This loop will run forever.​
This loop will run forever.​
...
Using While loop:

1. #include <stdio.h>
2.
3. int main() {
4. ​ while (1)
5. ​ ​ printf("This loop will run forever.\n");
6. ​ return 0;
7. }
8.

Output
This loop will run forever.​
This loop will run forever.​
This loop will run forever.​
...
Using the do-while loop:

1. #include <stdio.h>
2.
3. int main() {
4. ​ do {
5. ​ ​ printf("This loop will run forever.");
6. ​ } while (1);
7.
8. ​ return 0;
9. }
10.

Nested Loops
Example:
1. #include <stdio.h>
2. ​
3. int main() {
4. // Outer loop runs 3 times
5. for (int i = 0; i < 3; i++) {
6.
7. // Inner loop runs 2 times for each
8. // outer loop iteration
9. for (int j = 0; j < 2; j++) {
10. printf("i = %d, j = %d\n", i, j);
11. }
12. }
13. return 0;
14. }
15.

Output
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1

Example:

1. #include <stdio.h>
2. ​
3. int main() {
4. for (int i = 0; i < 5; i++) {
5. if (i == 3) {
6.
7. // Exit the loop when i equals 3
8. break;
9. }
10. printf("%d ", i);
11. }
12. printf("\n");
13.
14. for (int i = 0; i < 5; i++) {
15. if (i == 3) {
16.
17. // Skip the current iteration
18. // when i equals 3
19. continue;
20. }
21. printf("%d ", i);
22. }
23. printf("\n");
24. for (int i = 0; i < 5; i++) {
25. if (i == 3) {
26.
27. // Jump to the skip label when
28. // i equals 3
29. goto skip;
30. }
31. printf("%d ", i);
32. }
33.
34. skip:
35. printf("\nJumped to the 'skip' label %s",
36. "when i equals 3.");
37. ​
38. return 0;
39. }
40.

Output
012
0124
012
Jumped to the 'skip' label when i equals 3.

6.​ Functions
Function definition

1. return_type name () {
2. // Body of function
3. };
4.
●​ return_type: type of value the function return.
●​ name: Name of the function
●​ Body of function: Statements inside curly brackets { } are executed when function call.
Example:

1. void hello(){
2. printf("GeeksforGeeks");
3. }
4.
Function Call
After defining a function, you can use it anywhere in the program by simply calling it with its name followed
by parentheses ().
Example:

1. #include <stdio.h>
2. ​
3. // Function definition
4. void hello() {
5. printf("Persona");
6. }
7. int main() {
8. ​
9. // Function call
10. hello();
11. return 0;
12. }
13.

Output:
Persona
Return Type of Functions
A function can return a value to its caller as a result. It is called the return value, and the type of this value is
called return type of the function. The function only returns one value, and the value type is the same as the
function's return type.
The return keyword is used to return some values from the function.
Example:

1. #include <stdio.h>
2. ​
3. int getThree(){
4. int n = 3;
5. return n;
6. }
7. ​
8. int main() {
9.
10. // Print the value that
11. // is return by getThree()
12. // function
13. printf("%d", getThree());
14. return 0;
15. }
16.

Output:
3
In this program, the getThree() function is of integer type, meaning that when you call this function, it returns an
integer value, which is 3.
Note: void return type is used when no value is returned.

Function Parameters
A function can be provided some values by its caller. These values are called arguments and are provided at the time
of function call. In the function definition, we use the placeholder variables inside the parentheses () to receive these
values. These placeholders are called parameters.

1. // Parameters in the function definition


2. return_type func(type1 name1, type2 name2, ...){
3. // ....
4. }
5.
name1, name2, .... are the names given to the parameters of the function. They will be referred with the same name
inside the function.
Example:

1. #include <stdio.h>
2. ​
3. // Defining a function that
4. // print square of given number
5. void printVal(int num, float real){
6. printf("%d %f\n", num, real);
7. }
8. ​
9. int main() {
10. int a = 3;
11.
12. // Call the printVal function and pass
13. // desired values
14. printVal(a, 1.5);
15. return 0;
16. }
17.

Output
3 1.500000

Local Variables
Variables declared inside a function are called local variables because they are only accessible within that function.
We cannot access them outside the function.
Example:

1. #include <stdio.h>
2.
3. int getThree(){
4. int n = 3;
5. return n;
6. }
7.
8. int getThreeDummy(){
9.
10. // Try to access a variable
11. // of another function
12. return n;
13. }
14.
15. int main() {
16.
17. printf("%d", getThreeDummy());
18. return 0;
19. }
20.
Output
main.c: In function ‘getThreeDummy’:​
main.c:12:12: error: ‘n’ undeclared (first use in this function)​
12 | return n;​
| ^
In the above program, we attempt to access a variable from another function, but the compiler gives an error saying
that the variable is undefined. This means the local variable is not accessible outside the function.
In contrast, global variables can be accessed anywhere in the program, including inside functions.

7. Header files (Libraries)


You need to use certain libraries in order to use build in functions.

To be able to use this libraries you should write

1. #include <libraryname.h>
2.
<stdio.h> — Standard Input/Output
Function Description

printf() Prints formatted text to the screen (stdout)

scanf() Reads formatted input from the keyboard (stdin)

puts() Prints a string followed by a newline


Function Description

putchar() Prints a single character

getchar() Reads a single character from input

fopen() Opens a file

fclose() Closes an open file

fscanf() Reads formatted data from a file

fprintf() Writes formatted data to a file

<stdlib.h> — General Utilities


Function Description

malloc() Allocates memory dynamically

calloc() Allocates and zero-initializes memory

realloc() Changes the size of previously allocated memory

free() Frees dynamically allocated memory

exit() Exits the program immediately

atoi() Converts a string to an integer

atof() Converts a string to a float

rand() Generates a pseudo-random integer

srand() Seeds the random number generator

<string.h> — String and Memory Handling


Function Description

strlen() Returns the length of a string

strcpy() Copies one string to another

strncpy() Copies a specific number of characters

strcmp() Compares two strings

strcat() Concatenates two strings

strchr() Finds the first occurrence of a character in a string

strstr() Finds a substring in a string


Function Description

memcpy() Copies a block of memory

memset() Fills memory with a constant byte value

<math.h> — Mathematics
Function Description

pow(x, y) Returns x raised to the power y

sqrt(x) Returns the square root of x

fabs(x) Returns the absolute value of a float

ceil(x) Rounds x up to the nearest integer

floor(x) Rounds x down to the nearest integer

sin(x) Returns sine of angle x (in radians)

cos(x) Returns cosine of angle x

tan(x) Returns tangent of angle x

log(x) Returns natural log (base e) of x

log10(x) Returns base-10 log of x

<ctype.h> — Character Classification


Function Description

isalpha(c) Checks if character is a letter

isdigit(c) Checks if character is a digit

isalnum(c) Checks if character is letter or digit

isspace(c) Checks for whitespace (' ', '\t', '\n', etc.)

toupper(c) Converts lowercase letter to uppercase

tolower(c) Converts uppercase letter to lowercase

<time.h> — Time and Date


Function Description

time() Returns current calendar time

clock() Returns CPU time used since program start


Function Description

difftime() Returns the difference between two times

localtime() Converts time to local time structure

strftime() Formats time as a string

<stddef.h> — Common Types


Definition Description

size_t Type for object sizes and array indexing

ptrdiff_t Type for pointer differences

NULL Represents a null pointer

offsetof() Returns offset of a struct member in bytes

<limits.h> — Integer Limits


Constant Description

INT_MAX Maximum value for int

INT_MIN Minimum value for int

CHAR_BIT Number of bits in a byte (usually 8)

<float.h> — Floating Point Limits


Constant Description

FLT_MAX Maximum value for float

FLT_MIN Minimum positive value for float

FLT_EPSILON Smallest float such that 1.0 + eps != 1.0

<stdbool.h> — Booleans (C99+)


Keyword Description

bool Boolean data type (true or false)

true, false Boolean constants


<assert.h> — Debugging
Function Description

assert(expr) Halts program if expr is false

<errno.h> — Error Reporting


Symbol Description

errno Global variable for error code

perror() Prints error message based on errno

strerror() Returns string describing error code

You might also like