[go: up one dir, main page]

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

Variable Naming in C

The document provides an overview of variable names and types in C programming, including rules for naming variables, data types, and their sizes. It also covers formatted input and output using printf and scanf functions, along with examples of basic operations such as addition and swapping values. Additionally, it explains the use of comments in C to enhance code readability.

Uploaded by

cenaj3443
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)
15 views22 pages

Variable Naming in C

The document provides an overview of variable names and types in C programming, including rules for naming variables, data types, and their sizes. It also covers formatted input and output using printf and scanf functions, along with examples of basic operations such as addition and swapping values. Additionally, it explains the use of comments in C to enhance code readability.

Uploaded by

cenaj3443
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/ 22

Basic Types and Formatted I/O

Variable Name
Definition
“Name assigned to a memory location”

• Variables are like containers in your computer's


memory you can store values in them and retrieve or
modify them when necessary.
• In programming a variable is a container (storage area)
to hold data.
• To indicate the storage area each variable should be
given a unique name (identifier)
C Variables Names
Variable Names
1. Names may contain letters, digits and underscores
2. The first character must be a letter or an underscore.
3. Cannot begin with a digit
– 1stName ------ illegal
– devideby10 ---- legal
4. 4. the underscore can be used but watch out!!
– Usually, variables beginning with underscore are used only in special
library routines.
– _validsystemcall ---- legal
5. Case matters!
1. "sum" is different than "Sum“ or “SUM”
6. Each variable has a name, a type and a value. E.g. int a =5;. The
value can be changed hence the name variable. But the name
remains the same during program execution.
Rules for defining variables
• Usually only the first 32 characters are significant
• aReally_longName_moreThan31chars
• aReally_longName_moreThan31characters
• (both of the above identifiers are legal and the same)

• There can be no embedded blanks or special character


• gross salary ( is illegal because it contains space )
• %rate ( is illegal because it contains special
character )
• Keywords or Reserve words cannot be used as identifiers
• float ( is illegal because it contains a
• double key word )
C Variables Names (2)
Suggestions regarding variable names
DO: use variable names that are descriptive
DO: adopt and stick to a standard naming convention
– sometimes it is useful to do this consistently for the entire software
development site
AVOID: variable names starting with an underscore
– often used by the operating system and easy to miss
AVOID: using uppercase only variable names
– generally these are pre-processor macros (later)

present, hello, y2x3, r2d3, ... /* OK */


_1993_tar_return /* OK but don’t */
Hello#there /* illegal */
double /* shouldn’t work */
2fartogo /* illegal */
Variable declaration and initialization.
Variable declaration
• Syntax
• Data_type Variable_name;
• E.g. int age, char location
• A memory location I reserved by name age and location

Variable initialization
You can initialize the variable by specifying an equal sign and a
value
• Syntax
• Data_type Variable_name=value;
• E.g. int age=25, char name=“ali”
C Basic Data Types (1)
There are only a few basic data types in C
char:
• a single byte, capable of holding one character
• Keyword “char” is used for declaring character type variables.
• Char test=‘h’ here test is a character variable . The value of test is
h.
int:
• an integer of fixed length, typically reflecting the natural size of
integers on the host machine (i.e., 32 or 64 bits
• can have both positive and negative values.
• Keyword “int” is used for declaring integer variable.
float:
• single-precision floating point. Can hold real numbers
• We declare a floating point variable in C by using “float” or
“double” keyword.
• double: double precision floating point
Data types and sizes

Data types Size in bytes Range


Char 1 -128 to 127
Int 2 or 4 -32768 to 32767
Unsigned int 2 0 to 65535
Signed int 2 -32768 to 32767
Float 4 3.4e-38 to 3.4e+38
Double 8 1.7e-308 to 1.7e+308
Keywords / Reserved Words
• Some words may not be used as identifiers
• These words have special meaning in C
• There are total of 32 keywords in C

Keywords
auto enum signed
break extern sizeof
case float static
char for struct
const goto switch
continue if typedef
default int union
do Long unsigned
double register void
else return volatile
Short while
Formatted Printing with printf (1)
The printf function is used to output information (both
data from variables and text) to standard output.
– A C library function in the <stdio.h> library.
– Takes a format string and parameters for output.
printf(format string, arg1, arg2, …);
– e.g. printf("The result is %d and %d\n", a, b);
The format string contains:
– Literal text: is printed as is without variation
– Escaped sequences: special characters preceeded by \
– Conversion specifiers: %(place hlder) followed by a single
character
Indicates (usually) that a variable is to be printed at this
location in the output stream.
The variables to be printed must appear in the
parameters to printf following the format string, in the
order that they appear in the format string.
Formatted Printing with printf (2)
Conversion Specifiers
Specifier Meaning

%c Single character
%d or %i Signed decimal integer
%x Hexadecimal number
%f Decimal floating point number
%e Floating point in “scientific notation”
%s Character string (more on this later)
%u Unsigned decimal integer
%% Just print a % sign
%ld, %lld long, and long long

There must be one conversion specifier for each argument


being printed out.
Ensure you use the correct specifier for the type of data you are
printing.
Escape sequence
An escape sequence in C language is a sequence of
characters that doesn’t represent itself when used
inside string literals or characters.
Some special characters re used for formatting
It composed of 2 or more character starting with
backslash and then escape character. E.g. \n
Formatted Printing with printf (3)
Escape Sequences:

Sequence Meaning
\a Bell (alert)
\b Backspace
\n Newline
\t Horizontal tab
\\ Backslash
\' Single quote
\" Double quotation
\xhh ASCII char specified by hex digits hh
\ooo ASCII char specified by octal digits ooo
Formatted Printing with printf (4)
An example use of printf
#include <stdio.h>
#include <conio.h>
int main()
{
int a=10;
int b=42;
int sum=a+b;
printf(“The sum of %d and %d is %d”,a,b,sum);
getch();
}
What is the output?
Example 2
Write a program that display the ascii sum of two
characters.
#include <stdio.h>
#include <conio.h>
int main()
{
char first=‘A’;
char second=‘B’;
int sum= first+second;
printf(“The sum of %c and %c is %d”,first,second,sum);
getch();
}
Reading Numeric Data with scanf (1)
The scanf function is the input equivalent of printf
– A C library function in the <stdio.h> library
– Takes a format string and parameters, much like printf
– The format string specifiers are nearly the same as those
used in printf
Examples:
scanf ("%d", &x); /* reads a decimal integer */
scanf ("%f", &rate); /* reads a floating point value */
The ampersand (&) is used to get the “address” of the
variable
– All the C function parameters are “passed by value”.
– If we used scanf("%d",x) instead, the value of x is passed.
As a result, scanf will not know where to put the number it
reads.
– More about this in Section 15 (“Functions”)
Reading Numeric Data with scanf (2)
Reading more than one variable at a time:
– For example:
int n1, n2; float f;
scanf("%d%d%f",&n1,&n2,&f);
– Use white spaces to separate numbers when input.
5 10 20.3
In the format string:
– You can use other characters to separate the numbers
scanf("%d%f", &value,&ratio);
You must provide input like:
value=27,ratio=0.8
– scanf returns an int
If end-of-file was reached, it returns EOF, a constant defined in
<stdio.h>
Otherwise, it returns the number of input values correctly read from
standard input.
Reading Numeric Data with scanf (3)
One tricky point:
– If you are reading into a long or a double, you must precede
the conversion specifier with an l (a lower case L)
– Example:
int main() {
int x;
long y;
float a;
double b;
scanf("%d %ld %f %lf", &x, &y, &a, &b);
return 0;
}
Adding two runtime values
#include <stdio.h>
#include <conio.h>
int main()
{
int a,b,sum;
printf("Enter the first value");
scanf("%i",&a);
printf("Enter the second value");
scanf("%d",&b);
sum=a+b;
printf("The sum of the two values is %d",sum);
getch();
}
Area of a circle
#include<stdio.h>
#include<conio.h>
int main()
{
int r;
float Area;
float pi;

printf("Enter value of radius:");


scanf("%d",&r);
printf("Enter value of pi:");
scanf("%f",&pi);
Area = pi*(r*r);
printf("The area of circle is: %f",Area);
getch();
}
Swapping values of two variables
#include <conio.h>
#include <stdio.h>
int main ()
{
int num1;
int num2;
int temp;

printf("Enter num1:");
scanf("%d",&num1);
printf("Enter num2:");
scanf("%d",&num2);
temp=num1;
num1=num2;
num2=temp;
printf("The value of num1 after swapping:%d",num1);
printf("\nThe value of num2 after swapping:%d",num2);
getch();
}
Comments in C
• Comments are used to provide information about lines
of code.
• It helps the reader to understand the code clearly
• Its just a way of explaining what a program does.
• Compiler ignores the comments during translation
• Single line comments
• // comment
• Multi line comments
• /* comment
Comment
Comment
*/

You might also like