PIC assignment
PIC assignment
Unit-1
Programming in C
Types of Variables
Variables in C are categorized based on the scope, lifetime, and data
type.
a. Based on Data Type:
1. int (Integer): Used to store whole numbers.
For example, int x = 10;
2. float (Floating Point): Used to store decimal numbers with single
precision. For example, float pi = 3.14;
3. char (Character): Used to store single characters or small integers.
For example, char initial = 'A';
4. void: Indicates that the variable does not hold any value; often
used with pointers or functions.
a. scanf()
scanf() is used to take input from the user. It reads formatted data
from standard input (usually the keyboard).
Example: int num;
printf("Enter a number: ");
scanf("%d", &num);
b. gets()
gets() reads a line of text from standard input, including spaces.
Example: char name[50];
gets(name);
c. fgets()
fgets() is a safer alternative to gets() for reading strings. It allows
you to specify the maximum number of characters to read.
Example: char name[50];
fgets(name, 50, stdin);
b. puts()
puts() is used to display a string followed by a newline character.
Example: char name[50] = "John";
puts(name);
a. Opening a File
fopen() is used to open a file.
Example: *fp = fopen("data.txt", "r");
Modes:
o "r": Open for reading.
o "w": Open for writing (creates a new file or truncates the
existing one).
o "a": Open for appending.
o "r+": Open for both reading and writing.
int main() {
int a = 5;
float b = 3.5;
float result = a + b;
printf("Result: %f\n", result);
return 0;
}
2. Explicit Type Conversion (Type Casting):
Explicit type conversion, also known as typecasting, is when you
manually convert one data type to another by explicitly specifying the
type.
Example of Explicit Conversion:
#include <stdio.h>
int main() {
int a = 10, b = 3;
return 0;
}
3. Type Conversion in Expressions
When different types of variables are used in expressions, C applies
implicit type conversion to ensure the operation is performed correctly.
General Rules:
1. Integer to Floating-point: If an int is combined with a float in an
arithmetic operation, the int is promoted to float.
2. Floating-point to Double: When performing arithmetic with float
and double, float is promoted to double.
Example :
#include <stdio.h>
int main() {
int x = 5;
float y = 2.5;
float result = x * y;
printf("Result: %.2f\n", result);
return 0;
}