Module 2.1 - Input and Output Operations
Module 2.1 - Input and Output Operations
int %d %d
char %c %c
string %s %s
e. Address Operator – the & symbol is responsible in accessing the address of your variable in your
computer’s memory. That is why it is important for scanf().
char firstName[50];
gets(firstName);
Example:
#include<conio.h>
int main()
{
char let1, let2;
let1 = getch();
let2 = getche();
}
Output Commands
printf
• Writes formatted output to the standard output device such as the monitor.
• Under the stdio.h library
Syntax:
printf(“format”, &variable_name);
Examples:
1. Output an int variable
int num=5;
printf(“%d”, num);
The first “format” would represent the first variable on the list.
If you put n3 before n1
Ex: printf(“%d %.2f %c %s”, n3, n1, let, str);
There would be an error because, now %d would represent n3 which is a float variable.
6. Adding a ‘new line’.
What if you want your display to look like this? Use the /n symbol.
3 #include<stdio.h>
6.50 int main()
y {
yes int n1 = 3, n2 = 8;
float n3 = 6.5;
char let = ‘y’;
char str[5] = “yes”;
printf(“%d\n%.2f\n%c\n%s”, n1, n3, let, str);
/* 3
6.50
y
yes */
Note:
• unlike in scanf(), there can be other characters inside the quotation mark (“ “), you can customize the way
you display your output.
• Example: I want my display to be “Number is #” instead of just the number directly.
-# is whatever value the user inputs
• Syntax:
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int num; int num1, num2;
scanf(“%d”, &num); scanf(“%d”, &num1);
printf(“Number is %d”, num); scanf(“%d”, &num2);
} printf(“Numbers are %d and %d”, num1, num2);
}
Sample Programs:
1. Create a C program to ask the user for an integer number and display its value.
Expected Display when you run your code:
#include<stdio.h>
int main()
{
int num;
printf(“Input a number: “);
scanf(“%d”, &num);
printf(“Inputted value: %d”, num);
}
#include<stdio.h>
int main()
{
int num1, num2;
printf(“Input first number: “);
scanf(“%d”, &num1);
printf(“Input second number: “);
scanf(“%d”, &num2);
printf(“First Number: %d\n”, num1);
printf(“Second Number: %d”, num2);
}
3. Create a C program to ask the user their name and display it.
Expected Display when you run your code:
#include<stdio.h>
int main()
{
char name[50];
printf(“Enter name: “);
gets(name);
printf(“Hello %s! Welcome to CIT-U!”, name);
}