C Program to Print Natural Numbers from 1 to N using for loop

Lets write a simple C program to print natural numbers from 1 to N, using for loop.

Related Read:
For Loop In C Programming Language

Source Code: C Program to Print Natural Numbers from 1 to N using for loop

 
#include<stdio.h>

int main()
{
    int num, count;

    printf("Enter a positive number\n");
    scanf("%d", &num);

    printf("\nNatural numbers from 1 to %d are:\n", num);

    for(count = 1; count <= num; count++)
    {
        printf("%d\t", count);
    }

    printf("\n");

    return 0;
}

Output:
Enter a positive number
5

Natural numbers from 1 to 5 are:
1 2 3 4 5

C Program to Print Natural Numbers from 1 to N using for loop


[youtube https://www.youtube.com/watch?v=sbIwx-_A5D0]

YouTube Link: https://www.youtube.com/watch?v=sbIwx-_A5D0 [Watch the Video In Full Screen.]


Logic To Print Natural Numbers from 1 to N using for loop

We start by assigning 1 to variable count. Now we ask the user to enter a positive number. Now for loop keeps executing until value of count is less than or equal to user entered value. Inside for loop we printout the value of count and then increment the value of count by one for each iteration of loop.

This way we printout all the natural numbers from 1 to N.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

For Loop In C Programming Language

Today lets learn about another loop control statement i.e., for loop. For loop is used to repeatedly execute certain set of instructions.

For loop allows us to specify 3 things in a single line:
1. Loop count initialization.
2. Condition Checking.
3. Modification Statement(increment/decrement statements).

Related Read
while loop in C programming
Relational Operators In C
Logical Operators In C
Video Tutorial: For Loop In C Programming Language


[youtube https://www.youtube.com/watch?v=cMsK_r5kRlo]

YouTube Link: https://www.youtube.com/watch?v=cMsK_r5kRlo [Watch the Video In Full Screen.]

Source Code: For Loop In C Programming Language

#include<stdio.h>
int main()
{
    int i;

    for(i = 0; i < 10; i++)
    {
        printf("%d IBM\n", i );
    }

    return 0;
}

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

#include<stdio.h>
int main()
{
    int i;

    for(i = 0; i < 10; i++)
    {
        printf("%d IBM\n", i + 1);
    }

    return 0;
}

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

i = 1 and i<= 10

#include<stdio.h>

int main()
{
    int i;

    for(i = 1; i <= 10; i++)
    {
        printf("%d IBM\n", i);
    }

    return 0;
}

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

No initialization statement and No Modification Statement

#include<stdio.h>
int main()
{
    int i = 0;

    for(; i < 10;)
    {
        printf("%d IBM\n", i + 1);
        i = i + 1;
    }

    return 0;
}

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

No Curly braces and No initialization statement

#include<stdio.h>

int main()
{
    int i = 0;

    for(; (i < 10); i = i + 1)
        printf("%d IBM\n", i + 1);

    return 0;
}

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

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Basics of Page Component: Ionic 2

In this video tutorial we shall learn some basics of a page component.

Topics Covered
1. Decorators – little bit
2. Class
3. Template File – ionic list items, For loop in ionic template.
4. Variables in Ionic – data type(number, string, Array, any)
5. Importing libraries and using it in our project.
6. Setting home page of our project.

Related Read:
Project Structure: Ionic 2

Video Tutorial: Basics of Page Component: Ionic 2


[youtube https://www.youtube.com/watch?v=Tb4k00ALHeA]

YouTube Link: https://www.youtube.com/watch?v=Tb4k00ALHeA [Watch the Video In Full Screen.]



In this tutorial we are using a blank template and setting home.html as our home page.

inside src/app/app.component.ts file
We import the HomePage page

import { HomePage } from '../pages/home/home';

next inside the class definition we assign this HomePage as root file for our application

rootPage = HomePage;

Full Source Code src/app/app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';

import { HomePage } from '../pages/home/home';


@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
  rootPage = HomePage;

  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();
      Splashscreen.hide();
    });
  }
}

Important: Do NOT forget to import all your classes in app.module.ts file, also specify its class name inside declarations and entryComponents section.

src/app/app.module.ts

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: []
})
export class AppModule {}

Now lets take a look at our HomePage component, which is present inside pages directory and Home folder
src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController) {
  }

}

Here we have imported two important library files. Component is used to configure the decorator and NavController is used for navigation purposes. In this tutorial we’re not using Navigation, but we’ll make use of it in our next video tutorial.

Decorators
There are 3 types on decorators:
1. Component
2. Pipe
3. Directive

I’ll explain each one of them separately in other videos.

Component
In today’s tutorial we’ve a component and it has a selector and a templateUrl. Selector name is used to inject an element or an attribute into the DOM. TemplateUrl tells the class about its associated template file. Components(Decorative) are placed just above the class definition.

Class
A class is a blueprint of an object. This is where we write our logic. It’ll usually have some properties(public or private or protected) and some methods.

In Ionic 2 class, you might have seen export keyword – which means we can import this file in some other class file and make use of its service or output.

variables
In TypeScript variables are typed – which means, variables have data type.
var1: any; Means variable var1 can take value of any data type.
var1: string; Here var1 can be assigned with string value only.
var1: number; as you might have already guessed, var1 takes number value.
var1: Array< {}>; var1 takes an array as its value.
var1: boolean; var1 takes value true or false.

Wrong initialization
var1: number = ‘Satish’;
var1: string = 1;

Correct initialization
var1: number = 1;
var1: string = ‘Satish’;

src/pages/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
companies: Array< {name: string, code: number}>;
  constructor(public navCtrl: NavController) {
    this.companies = [
      {name: 'Microsoft', code: 1},
      {name: 'Apple', code: 2},
      {name: 'Google', code: 3},
      {name: 'Oracle', code: 4},
      {name: 'IBM', code: 5}
    ];
  }
}

Here we have an array called companies – which has a list of company names like Microsoft, Apple, Google, Oracle, IBM. Each of this is stored as an individual element inside the array.

Using ngFor loop we can iterate through this array and display the company names.

*ngFor loop

<p *ngFor="let company of companies">
</p>

In Ionic 2, we make use of *ngFor for for loop. We declare a new variable company and reference individual elements of the array present inside companies array.

src/pages/home/home.html

<ion-list>  
  <ion-item *ngFor="let company of companies">  
    {{company.name}}  
  </ion-item>  
</ion-list> 

Here I’m making use of ion-list tag and ion-item tags to display the company names.

ion-list-no-lines

If we want to remove the default lines which come along with the ion-list items then we can add no-lines styling to ion-list tag.

<ion-list no-lines>  
  <ion-item *ngFor="let company of companies">  
    {{company.name}}  
  </ion-item>  
</ion-list>  

In next video tutorial lets learn how to navigate to other pages using Ionic 2 routing.

index creation: MongoDB

Lets learn to create index and to optimize the database in MongoDB.

Creating “Database”: “temp”, “Collection”: “no”, and inserting 10 Million documents inside it

1
2
3
4
5
use temp
switched to db temp
 
for(i=0; i< = 10000000; i++)
db.no.insert({"student_id": i, "name": "Satish"});

Since Mongo Shell is built out of JavaScript, you can pass in any valid Javascript code to it. So we write a for loop and insert 10 Million documents inside “no” collection.

creating-index-mongodb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
MongoDB shell version: 2.6.1
connecting to: test
> show dbs
admin    (empty)
daily    0.078GB
local    0.078GB
nesting  0.078GB
school   0.078GB
temp     3.952GB
test     0.078GB
> use temp
switched to db temp
> show collections
no
system.indexes
> db.no.find().pretty()
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cda"),
        "student_id" : 0,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cdb"),
        "student_id" : 1,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cdc"),
        "student_id" : 2,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cdd"),
        "student_id" : 3,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cde"),
        "student_id" : 4,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cdf"),
        "student_id" : 5,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce0"),
        "student_id" : 6,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce1"),
        "student_id" : 7,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce2"),
        "student_id" : 8,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce3"),
        "student_id" : 9,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce4"),
        "student_id" : 10,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce5"),
        "student_id" : 11,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce6"),
        "student_id" : 12,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce7"),
        "student_id" : 13,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce8"),
        "student_id" : 14,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ce9"),
        "student_id" : 15,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cea"),
        "student_id" : 16,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ceb"),
        "student_id" : 17,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cec"),
        "student_id" : 18,
        "name" : "Satish"
}
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833ced"),
        "student_id" : 19,
        "name" : "Satish"
}
Type "it" for more
 
> it

“no” collection has 10 Million record, but it won’t fetch you all records at once, as it would take a lot of time and resources of your computer! So it only fetches 20 records at a time. You can iterate through next 20 documents by using command “it“.

index creation: MongoDB


[youtube https://www.youtube.com/watch?v=zK_mRyiNs-I]

YouTube Link: https://www.youtube.com/watch?v=zK_mRyiNs-I [Watch the Video In Full Screen.]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> db.no.find({"student_id": 5}).pretty()
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cdf"),
        "student_id" : 5,
        "name" : "Satish"
}
 
 
> db.no.findOne({"student_id": 5});
{
        "_id" : ObjectId("53c9020abcdd1ea7fb833cdf"),
        "student_id" : 5,
        "name" : "Satish"
}
> db.no.find({"student_id": 5000000}).pretty()
{
        "_id" : ObjectId("53c90ca6bcdd1ea7fbcf881a"),
        "student_id" : 5000000,
        "name" : "Satish"
}

find() method scans through all the documents present in the collection to find multiple matches for the condition. So in above case, find() method scans through 10 Million documents, hence returns the result slowly. Where as findOne() method stops scanning the collection as soon as it finds the first matching document, so findOne() returns result faster than find() method.

Related Read:
Multi-key Index: MongoDB
index / key: MongoDB

Creating index

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> show collections
no
system.indexes
 
> db.system.indexes.find()
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "temp.no" }
 
> db.no.ensureIndex({"student_id": 1});
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
 
> db.system.indexes.find()
{ "v" : 1, "key" : { "_id" : 1 }, 
                     "name" : "_id_", "ns" : "temp.no" }
{ "v" : 1, "key" : { "student_id" : 1 }, 
                     "name" : "student_id_1", "ns" : "temp.no" }

We create index on “student_id”. It takes little time to create the index, as we have 10 Million documents inside “no” collection.

After creating index on “student_id”, run the same command and you’ll get the results instantly – maybe it takes 0.01 ms, but the delay can’t be noticed.
Why does it return results faster after creating index on “student_id”? Watch this short video lesson to know it: index / key: MongoDB

1
2
3
4
5
6
7
8
9
10
11
12
13
> db.no.find({"student_id": 5000000}).pretty()
{
        "_id" : ObjectId("53c90ca6bcdd1ea7fbcf881a"),
        "student_id" : 5000000,
        "name" : "Satish"
}
> db.no.find({"student_id": 10000000}).pretty()
{
        "_id" : ObjectId("53c914adbcdd1ea7fb1bd35a"),
        "student_id" : 10000000,
        "name" : "Satish"
}
>

So the querys/commands can be optimized by creating indexes on frequently accessed fields.