Learning C/C++ Step-By-Step - Page 3

03. Step-by-Step C/C++ --- C Programming - Basic IO Statements

Contents

  • Structure of a C program
    1. I/O Statements
    2. Printf
    3. Escape Characters
    4. Using Variables in programs
    5. Scanf
  • More IO Statements
    1. gets
    2. puts
    3. getch
    4. putch
    5. getche
    6. getchar

As discussed, every program is a set of statements, and statement is an instruction to the computer, which is a collection of constants, variables, operators and statements.

 

Structure of a C program

<return type> main( arg-list )
{
     <declaration part>

     <Statement block>

     <Return Values >
}

We are going to start with Input / Output Statements as they play important roles in our further programs.

 

I/O Statements

Printf

This statement displays the given literal / prompt / identifiers on the screen with the given format.

Syntax:

printf(<"prompt/literal/format id/esc char. ">, id1,id2, .....);

E.g.:

printf("Hello");
printf("Student number : %d", sno);
printf("Student name : %s", name);
printf("3Subjects Marks : %d, %d, %d", m1, m2, m3);

1. Program to print a message:

/* 02_print.c */
#include <stdio.h>
int main( )
{
     printf("Hello");
     return 0;
}

 

Escape Characters

Common Escape Sequences

Escape Sequence

Character

\a

Bell(beep)

\b

Backspace

\f

Form feed

\n

New line

\r

Return

\t

Tab

\\

Backslash

\’

Single quotation mark

\”

Double quotation marks

\xdd

Hexadecimal representation

2. Program to print a message in a new line
- Compare with the last program.

/* 03_esc.c */
#include <stdio.h>
int main()
{
     printf("\nHello");
     return 0;
}

3. Program to display address of a person
- Multiple statements in main

/* 04_multi.c */
#include <stdio.h>
int main()
{
     printf("\nName of the Person");
     printf("\nStreet, Apartment//House No. ");
     printf("\nzip, City");
     printf("\nCountry");
     return 0;
}

 

Using Variables in programs

Basic Variable Types

Keyword

Range: low

Range: high

Digits of precision

Bytes of memory

Format-ID

Char

-128

127

n/a

1

%c

Int

-32, 768

32, 767

N/a

2

%d

Long

-2,147, 483, 648

2, 147, 483, 647

N/a

4

%ld

Float

3.4 x 10-38

3.4 x 1038

7

4

%f

Double

1.7 x 10-308

1.7 x 10308

15

8

%lf

long double

3.4 x 10-4932

3.4 x 10-4932

19

10

%Lf

4. Program to find the sum of two values
- Variables are introduced in this program

/* 05_var.c */
#include <stdio.h>
int main()
{
     int a , b , c;
     a = 5;
     b = 10;
     c = a + b;
     printf("%d", c);
     return 0;
}

5. Program to find the sum of two values with message
- Compare with the last program

#include <stdio.h>
int main()
{
     int a, b, c;
     a = 5;
     b = 10;
     c = a + b;
     printf("\nSum is %d", c);
     /* We have inserted extra text before printing the value*/
     return 0;
}

 

Scanf

Using this statement we can accept and values to variables during the execution of the program.

Syntax:

scanf(<format id/esc char">, id1,id2, .....);

Eg.

scanf("%d", &sno);
scanf("%s", name);
scanf("%d%d%d", &m1, &m2, &m3);

6. Program to find the sum of two value using scanf
- When you run the program it shows you the cursor and waits for your input, enter a numeric value and press "Return", do this twice and you will get the output.

/* 07_scanf.c */
#include <stdio.h>
int main()
{
     int a , b, c;      scanf("%d", &a);
     scanf("%d", &b);
     c = a + b;
     printf("\nSum is %d", c);
     return 0;
}

More Excercises:

7. Program to find the sum of two values with message display
- Messages are optional but introduces user-friendly interaction
- Compare with the last program

/* 08_sum.c */
#include <stdio.h>
int main()
{
     int a , b, c;      printf("Enter A value "); scanf("%d", &a);
     printf("Enter B value "); scanf("%d", &b);
     c = a + b;
     printf("\nSum is %d", c);
     return 0;
}

8. Program to find the result of ( a+ b )2
- Similar to sum of two values program but the formulae is different

/* 09_formula.c */
#include <stdio.h>
int main()
{
     int a, b, c;
     printf("Enter A value "); scanf("%d", &a);
     printf("Enter B value "); scanf("%d", &b);
     c = a * a + b * b + 2 * a * b;

     printf("Result is %d", c);
     return 0;
}

9. Program to find the annual salary of an employee
- input : eno, name, sal
- Process : Asal = sal * 12
- Output : Eno, name, sal, asal
- This program introduces the different types of variable

/* 10_emp.c */
#include <stdio.h>
int main()
{
     int eno;
     char name[10]; /* name with 10 characters width */
     float sal, asal; /* sal & asal as real values */
     printf("Enter Employee number "); scanf("%d", &eno);
     printf("Enter Employee name "); scanf("%s", name);
     printf("Enter Employee salary "); scanf("%f", &sal);

     asal = sal * 12;
     printf("\nEmployee number %d", eno);
     printf("\nEmployee name %s", name);
     printf("\nEmployee salary %f", sal);
     printf("\nAnnual Salary %f", asal);
     return 0;
}

10. Write a program to find the total and average marks of a student
- Input : Sno, name, sub1, sub2, sub3
- process : total = sub1 + sub2 + sub3; avg = total / 3
- output : sno, name, total, avg
- Similar to the above program just accept, process, and print the values

/* 11_stud.c */
#include <stdio.h>
int main()
{
     int sno, sub1, sub2, sub3, total;
     char name[10];
     float avg;

     clrscr(); /* clear the screen before its output */
     printf("Enter Student number "); scanf("%d", &sno);
     printf("Enter Student name "); scanf("%s", name);
     printf("Enter Subject1 marks "); scanf("%d", &sub1);
     printf("Enter Subject2 marks "); scanf("%d", &sub2);
     printf("Enter Subject3 marks "); scanf("%d", &sub3);

     total = sub1 + sub2 + sub3;
     avtg = total / 3;

     printf("\nStudent number %d", sno);
     printf("\nStudent name %s", name);
     printf("\nTotal marks %d", total);
     printf("\nAverage marks %f" , avg);
     return 0;
}

 

More IO Statements

Gets:

To accept a string from the key board. It accepts string value up to the carriage return.

Syntax:

gets( <id.> );

E.g.:

gets(name);
gets(street);

 

puts

It displays the given string value on the screen.

Syntax:

puts( <id.> / <“prompt”>);

E.g.:

puts(name);
puts(street);

 

getch - Read char without echo

getche - read char with echo

getchar - read char and accept carriage return

 

putch

It can print a character on the screen.

Syntax:

putch(<char>).

E.g.:

putch(‘a’);
putch(65);

 

getch

It accepts a character from console.

Syntax:

char = getch().

E.g.:

ch = getch();
option = getch();

Share this page:

19 Comment(s)

Add comment

Comments

From: at: 2009-01-09 15:11:23

The tutorial looks so great. But I have some doubts. Why do you use "clrscr()" function and conio.h library, if you are using the C/C++ standard? (I found that in the pages number 4 and 5, but that is as far as i got).

From: at: 2009-01-20 16:25:53

I tried to lead learners from learning C to C++, so the pages 4 and 5 reflects most of the usage of C language, so it introduces users to learn about other header files.

From: Shantanu Goel at: 2009-01-08 04:44:05

Great tutorial Ganesh. And here is a link for people who finish your tutorial and want to learn a bit about how to make their code secure and optimized: Safer Code - Secure Coding in C/C++ This has a lot of stuff regularly published to cater to various security and performance related issues with C/C++ and anyone can follow it easily at a gradual pace.

From: Anonymous at: 2010-02-01 06:01:52

Very nice!

From: pickatutorial at: 2010-10-09 12:52:44

Great Work. Keep it up.

From: TodaysTech at: 2011-07-12 21:31:29

If anyone is interested, I have an ongoing blog that is covering the transition from the Business world to the Programming world.  Since it's from my own perspective, I think it can be easy to read and relate to for most first timers.

 http://livingtodaystech.blogspot.com/2011/07/learning-c.html

From: Crosility at: 2012-12-06 23:44:36

In the chart, it says 'vhar', not 'char'.

From: Jason at: 2013-04-16 14:58:31

Why using conio.h ?   It is not part of C standard, C++ standard, nor is it part of any Linux or Unix libraries.  

The inclusions of Microsoft specific libraries in chapters 4 & 5 have me doubting the validity the rest of the tutorial (learning c/cpp on Linux).

The tutorial is well written, however,  but I think it would be more appropriate on a .Net or Msdn blog. 

Thanks Ganesh!

From: Anonymous at: 2009-09-01 11:56:38

Shouldn't

\* 0001_hello.c *\ and  \* 0001_hello.cpp *\

 be

/* 0001_hello.c */ and /* 0001_hello.cpp */

?

 

From: Scott_R at: 2012-01-03 22:24:55

The numbering for the examples is off by one.

For example:

"10. Write a program to find the total and average marks of a student"

/* 11_stud.c */

From: Erica at: 2012-12-31 19:56:21

In 11_stud.c

avtg = total / 3;

should be

avg = total / 3;

Also the clrscr() function won't compile in g++. If others need you can add // to the start of the line and the line will become a comment.

From: Bob at: 2011-09-09 12:50:09

Ex 13 :

  if ( age >= 13 and age <= 19 ) printf("Teen Age");
  if ( age >= 20 and age <= 35 ) printf("Young Age");
  if ( age >= 36 and age < 50 ) printf("Middle Age");

should read as :

      if ( age >= 13 && age <= 19 ) printf("Teen Age");
      if ( age >= 20 && age <= 35 ) printf("Young Age");
      if ( age >= 36 && age < 50 ) printf("Middle Age");

From: Anonymous at: 2009-06-25 12:57:51

Example 14 would be less ....rectangular and much more triangular if, instead of

for (j=1;j<=5;j++)

one had

for (j=i; j<=5;j++)

From: Snehal at: 2009-06-15 07:00:15

In the difference between union and structure ,the names are misplaced ...means in union , structure points are placed and viceversa... Make it correct

From: bzero in c programming at: 2014-07-30 10:54:51

Hi,

There is a bug in the number 4 example. You will get compilation error while running this program you will get a compilation error like below:

 binaryover.cpp:31:11: error: expected ‘;’ before ‘t1’

binaryover.cpp:32:6: error: ‘t3’ was not declared in this scope

binaryover.cpp:32:11: error: ‘t1’ was not declared in this scope

binaryover.cpp:32:16: error: ‘t2’ was not declared in this scope

Because you are using "using namespace std;" but in the standard library there is a function named time (). So, to solve the problem, you can change the name of the function time ()  to any other name like time1 (), then you will be able to run your code without any error. 
 

From: Abhijeet at: 2009-01-11 01:25:52

Though i haven't done it myself, mingw32 can create win32 executables from linux. As its description says "Minimalist GNU win32 (cross) compiler, A Linux hosted, win32 target, cross compiler for C/C++, Freedom through obsolescence. Those who still really need to can now build windows executables from the comfort of Debian." You could check it out.

From: Paul at: 2009-01-07 22:40:39

Thanks, this is a nice tutorial, I'm actually a php programer and I saw a lot similar with php's language, but I have a question:

Can I compile a c++ program under linux to make a .exe to run on windows and viceversa?

And how to do that if it is possible?

From: dbrion at: 2009-06-30 11:58:40

"Can I compile a c++ program under linux to make a .exe to run on windows "

Yes :

I confirm the last post and cross compilers can natively be found with recent Fedora (and any linux distribution, messeems!) The way all the stuff necessary could be downloaded and made working can be found with adaptations of :

cran.r-project.org/doc/contrib/cross-build.pdf 

(one just has to stop at "make xtools": they are downloaded and put into a proper place).

Else, if you like linux and have "only"  Windows, you can use cygwin (avoids dualbooting or switching to another computer)  with the sources (it is very rare that sources need to be different between both systems, they use the same compiler -gcc/g+++- and almost the same include file names.... ) ...

 

"and viceversa"

No (not because linux executables do not have a .exe suffix!):

 but you can edit/compile/test your program(s) under cygwin (google search can find it) until it works and port it (i.E the source, the compilation  and test scripts) to Linux (there is almost no effort, apart the efforts linked with different disk nomenclatures, of course).

 Else, unless emulating linux with vmplayer/qemu/vbox -all these emulators are Windows ported-? but it is more complicated than C/C++....

From: Iftekhar Ahmed at: 2010-05-14 19:31:55

Dude........

Its relly helpful, I have 48 Hrs for my Exams..........................

Thanks for posting ............

Regards,

Iftekhar Ahmed